Tuesday, July 27, 2010

Wpf Dispatcher Misuse

Unlike the Highlander there can be more than one Dispatcher.  Just because you invokeSystem.Windows.Threading.Dispatcher.CurrentDispatcher does not mean you will always get the Dispatcher responsible for executing tasks on the logical tree.

Consider this example:

<Window 
    x:Class="WpfDispatcherInfalibility.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="75" 
    Title="MainWindow" 
    Width="100">

    <Grid>
        <TextBlock Text="{Binding Path=Field1}" />
    </Grid>

</Window>

namespace WpfDispatcherInfalibility
{
    using System;
    using System.ComponentModel;
    using System.Threading;
    using System.Windows.Threading;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : INotifyPropertyChanged 
    {
        private string field1 = "Default";

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;

            var thread = new Thread(this.WorkerMethod) { Name = "My worker thread 1" };
            thread.Start();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public string Field1
        {
            get
            {
                return this.field1;
            }

            set
            {
                this.field1 = value;
                this.RaisePropertyChanged("Field1");
            }
        }

        private void RaisePropertyChanged(string name)
        {
            var handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        private void WorkerMethod()
        {
            // This will not retrieve the UI dispatcher because it is simply getting a dispatcher associated 
            // with this thread and this is not the UI thread. Just because you invoke Dispatcher.CurrentDispatcher
            // does not mean you will be given the dispatcher associated with the UI.
            var dispatcher = Dispatcher.CurrentDispatcher;
            string threadName = Thread.CurrentThread.Name;

            // The lambda will never be invoked because the dispatcher retrieved is not running.
            dispatcher.BeginInvoke(new Action(() => this.Field1 = "Field set from thread " + threadName));
        }
    }
}

As expected the UI shows the following window. And this window's text does not change.
What is the moral of the story?

Keep a reference to the dispatcher from a known point inside the controller for your xaml.  Or you can get it from any derivative of DispatcherObject (which is the root object of all Xaml components).

Monday, July 26, 2010

External Dependency Wrapping and Unit Testing

A project I am currently working on requires us to reference a third party assembly.  As is quite often the case the assembly is not exposing types that are unit testing friendly.  Ideally interfaces or abstract base classes would be great, but this is seldom the case.  I've been refining a strategy to consume dependencies in a indirect manner so the hard coded types don't work their way through my code essentially having a "Medusa" effect. IE: Casting all of my types into stone and then they too cannot be replaced with test mocks.
Consider the schematic diagram below.  The blue assembly is the Medusa assembly, wanting to cast all my types into stone. But wait I have a magic mirror shield! The External Type Factory.  This is intended to control the creation of types I need to consume from the external assembly.  The other issue is being able to invoke methods in the external assembly that require the hard types(Widget, Color, and Thing) as parameters.  The External Type Factory has adaptor methods to unwrap my wrappers back to their original types in an indirect manner to stop the petrification effect.



The good:
  • Stops the external hard types from preventing unit testing.
  • Can also have life cycle management benefits - ie all calls to the assembly are managed through one area of code allowing other benefits such as life cycle management (correct instantiation and disposal) and logging.
  • Fits well with IoC containers.
  • Allows tossing the external dependency away and replacement with something else at a future date with little effort.

The bad:
  • A slight overhead of more code.
  • A slight overhead of more complexity with the indirection.
  • You still need to ensure that all developers use your factory instead of going direct and preventing unit testing.
  • All types that want to use the external assembly need to have a factory available to them to be able to get the types.
  • Not really usable in XAML code.

I might add detail to this as I continue the journey down this path.

Sunday, July 25, 2010

Using the Factory Pattern as an Assembly Gateway

Sometimes its useful to tightly control access to a framework or utility assembly to ensure it is either used correctly or is easy to use.  We as developers are guilty of often building in too much flexibility, and too much always equates to more complexity.  This normally results in questions from consuming developers like:

 "How do I use this, there seems to be more than one way to do anything?"

Having one way to do anything can sometimes create a intuitive and easy to use API.  Having only one way to do certain things obviously has trade offs in flexibility, it very much depends on the use case of your utility assembly and the consequences if consumers misuse it.  My personal preference is to think about possible extensions and where functionality could be added but not necessarily expose them publically or add the extension code at all until there is a demand for them. (Demand > 1 BTW).

Its also worth considering implementing strict and few use cases for your assembly if its consumers are likely to be unit testing.  A Test Driven Developer will want to have your babies if you are exposing nothing but interfaces and all references between objects are interfaces and creation is controlled through an interfaced factory.  Not to mention that using this approach means your consumers are forced to write code that is unit testable.

Enter the Factory Method Patten.

Basically, using a factory, will create an object for you and return you a reference through an interface. You are not in control what exact concrete type is behind the interface nor should you care, as long as you get an instance with the right interface.  The factory is also interfaced so that when it comes time to test, you can use a different factory or change its configuration to return a different type. (See IoC containers).

Here's a schematic diagram showing the idea of using a factory as a gateway into a shared assembly:


Most types  within the assembly are "internal" (ie the class is declared as internal).  Each type that can be used externally are interfaced, and the interface is public.  All references to other types, refer to the other type using an interface. For example type C and type A both have a reference to type B, but instead of referencing B directly they reference an interface of B.  The Factory is responsible for creating types and returning a reference to an interface.  The factory itself also implements an interface to allow the entire Assembly to be replaced with a complete set of test Mocks.

Lets see a code example.  First lets start by looking at the end result usage:
The protected assembly in this example is the "InterfaceIntoAssembly" namespace.  


namespace ConsoleApplication1
{
    using System;
    using InterfaceIntoAssembly;

    /// <summary>
    /// A Test Console application
    /// </summary>
    public static class Program
    {
        private static IFactory factory;

        public static IFactory Factory
        {
            get
            {
                // If no factory has been supplied yet, create the factory live production
                // code will use.
                return factory ?? (factory = new Factory());
            }

            set
            {
                // Provided for testing (alternatively could be constructor argument).
                factory = value;
            }
        }

        /// <summary>
        /// Main entry point
        /// </summary>
        /// <param name="args">The command line args.</param>
        public static void Main(string[] args)
        {
            IConnection connection = Factory.CreateConnection();
            IMessage message = connection.CreateMessage();
            IMessage reply = message.CreateReply();
            connection.Send(reply);
        }
    }
}
This code is from a Console application that consumes the InterfaceIntoAssembly.DLL.  So to relate to the diagram above this code is from the "External Consumer of Assembly" green box. First thing to note is that I'm using a class scoped Factory property, this is to allow a Unit Test to create this class in test mode, and then inject a mocked Test Factory into the Factory property.  I prefer to have a property for a factory rather than pass it into the constructor of the class; although sometimes passing a factory into the constructor is necessary. You might ask why don't I just create an application wide static property and refer to the factory that way, much like using the StructureMapstatic ObjectFactory.CurrentContainer property?  When you run your tests with a multi-threaded parallel runner get back to me on the use of static object factories.

Lets look next at the Factory code:

namespace InterfaceIntoAssembly
{
    public class Factory : IFactory
    {
        public IMessage CreateMessage()
        {
            return new Message();
        }

        public IConnection CreateConnection()
        {
            return new Connection();
        }
    }
}
There are many ways to implement this, and this is the most basic.  For more flexibility reach straight for StructureMap.  
The methods available here are the Types that you want external consumers to be able to create. So if a consuming developer needs to be able to "new-up" a class you will instead of making that class public create a method here to create it.  Types that are only created internally and references are passed out of the assembly then you will not need a create method.

Finally lets take a look at the connection object to round out the example.


namespace InterfaceIntoAssembly
{
    using System;

    public interface IConnection
    {
        int Status { get; }

        IMessage Receive();

        void Send(IMessage message);

        IMessage CreateMessage();
    }

    internal class Connection : IConnection
    {
        public int Status { get; private set; }

        public IMessage Receive()
        {
            throw new NotImplementedException();
        }

        public void Send(IMessage message)
        {
            throw new NotImplementedException();
        }

        public void HiddenMember()
        {
            throw new NotImplementedException();
        }

        public IMessage CreateMessage()
        {
            throw new NotImplementedException();
        }
    }
}

Note that all references to other classes are to interfaces, or alternatively you could use abstract class if that suits better (but remember not to put code in it that will hinder different usages like testing etc).
Also note that "HiddenMember" does not appear externally outside the assembly. So from the consuming console application described above you cannot see this member.  This method perhaps should be declared as internal for clarity. All interface members must be declared as public.

I'm not using a IoC framework in this example, but you certainly can.  However my personal preference for framework or base level assemblies to avoid excessive dependencies unless there's a strong reason to include them.  This simple factory definitely does the job in this case.
I'm also intending on posting another example of consuming a third party DLL that does not expose interfaces, and how to write unit testable code against such a dependency.

When does this not work well?
  • When your framework/utility assembly has types you expect consumers to inherit from.
  • When you cannot anticipate all use cases of your framework assembly.
  • When your target audience is very senior level developers who know exactly what they are doing and want unforeseen and creative ways to extend your assembly. (In this case you'd still interface and probably just ditch the factory gateway).
When does it work well?
  • When the consequences of misusing your assembly are severe (memory leaks, financial loss etc).
  • When you are trying to make it very easy for consuming developers to use your API.
  • When you know your use cases up front and can reasonably anticipate possible extensions to your DLL.
  • When you are making extensive use of unit testing.

Note to self, when you read this again and have forgotten where the source code is, you can find it here.

Monday, July 19, 2010

Usage of C# 'this' keyword

Use of the this keyword, is very much a style thing.  However there is a great deal of logic behind the recommendation to use it.  

Most developers have some kind of consistent style they follow, and consistency is a good thing.  In my opinion following historic 'traditions' need to be occasionally challenged to ensure the science and logic behind the original recommendation is still valid.  I'm sure everyone would agree that technology and methodology in the software industry is extremely fast moving. So keeping all things current make sense.

The overall goal in any style convention is to consistently add value to code by narrowing the number of ways a piece of code can be interpreted. However the code should always be as readable as possible. The more readable it is, the less chance for bugs.

Here's an example of how the 'this' keyword can make code more readable, indicate scope, and indicate member or static access:

// Its clear m_Something is a field, 
// but what is Something2?
// Something2 could be property, or a 
// method reference, or a static member.
// Its clear something is a field 
//- "this" means instance; lowercase 
// first letter 's' means private field.
// Something2 is clearly a static member 
// or constant by the Class name prefix 
// and the captial letter also indicates
// constant or readonly static.
m_Something = Something2;this.something = ClearerUsage.Something2;
// What is Something.Bar? Static class 
// with a static property or member property
// access?

// Something4 same questions as above.
// Something can only be a member property, it 
// cannot be a field due to casing of 
// the 'S'. And Bar is a member access of 
// Something. It cannot be a static of 
// Something otherwise it would be Foo.Bar 
// (Foo being the type of Something).
// Something4 same as above Something2,3,5.
Something.Bar = Something4;this.Something.Bar = ClearerUsage.Something4;
// Could be a instance or static method.// This can only be a member method.
SomethingElse();this.SomethingElse();
Logically 'this' definitely adds value and is much clear than using Hungarian style prefixes. This also indicates scope as well as static versus member access. I know the code will compile without it, but increasing readability of the code and reducing ambiguity DOES reduce bugs. Using a built in language construct does make more sense than inventing a prefixing or suffixing scheme.

Log4Net Demo

When it comes to logging, there is one open source library that stands out, Log4Net.  One could even go as far as saying its the defacto standard for .Net logging.  At the very least you would be wasting a great deal of time reproducing even the basic functionality this library provides...for free.  Did I mention its free?  

The best way to demo this is with a code walk through.  I have created a C# Console application and have this code in the Program.cs file:


namespace Log4NetDemo {
    using log4net;
    using log4net.Config;

    public class LogTest {
        private static readonly ILog logger = LogManager.GetLogger(typeof(LogTest));

        static void Main(string[] args) {
            XmlConfigurator.Configure();  // Directs Log4Net to use the app.config

            logger.Debug("Here is a debug log.");
            logger.Info("... and an Info log.");
            logger.Warn("... and a warning.");
            logger.Error("... and an error.");
            logger.Fatal("... and a fatal error.");
        }
    }
}

The DOMConfigurator.Configure(); line is used to point Log4Net to the app.config file to read in its configuration.  You could implement a trigger in your application to re-read the settings if required.
Log4Net provides ultimate flexibility by reading log "appenders" from the app.config file.  In fact all its configuration comes from the app.config file.



<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    </configSections>

    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>

    <!-- Logging config -->
    <log4net>
        <!-- Debug Log Appender -->
        <appender name="OutputDebugStringAppender" type="log4net.Appender.OutputDebugStringAppender">
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%5.5thread%6.6level %35.35logger:[%4.4thread] %message"/>
            </layout>
        </appender>

        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
            <file value=".\RollingLog.log"/>
            <appendToFile value="true"/>
            <maximumFileSize value="1024KB"/>
            <maxSizeRollBackups value="2"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%5.5thread%6.6level %35.35logger:[%4.4thread] %message"/>
            </layout>
        </appender>
        
        <appender name="AspNetTraceAppender" type="log4net.Appender.AspNetTraceAppender">
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
            </layout>
        </appender>
        
        <appender name="FileAppender" type="log4net.Appender.FileAppender">
            <file value=".\AppenderLog.log"/>
            <appendToFile value="true"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
            </layout>
        </appender>

        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="[Header]\r\n" />
                <param name="Footer" value="[Footer]\r\n" />
                <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
            </layout>
        </appender>

        <!-- Set up root logger -->
        <root>
            <!-- levels: DEBUG, INFO, WARN, ERROR, FATAL, OFF    -->
            <level value="ALL"/>
            <appender-ref ref="RollingFile"/>
            <appender-ref ref="FileAppender"/>
            <appender-ref ref="ConsoleAppender"/>
            <appender-ref ref="OutputDebugStringAppender"/>
        </root>
    </log4net>
</configuration>

Things to note here are the appender declarations.  You can have as many or as few of these as you like, and obviously these can be changed at runtime.  Each appender has its own configuration element defining where and what format to log.
Note how the AspNetTraceAppender is declared but not referenced by the root element.  This means it will not be logged to at runtime. It might just be there in case someone would like to use it in the future.  This practise saves looking up the declaration syntax when you in hurry to activate the logging.

For a complete list of appenders see the Log4Net site.  At last count there were approaching 40 built-in appenders.

Here's the output of the console app:


2010-06-19 10:30:45,613 [6964] DEBUG Log4NetDemo.LogTest Here is a debug log.
2010-06-19 10:30:45,639 [6964] INFO  Log4NetDemo.LogTest ... and an Info log.
2010-06-19 10:30:45,639 [6964] WARN  Log4NetDemo.LogTest ... and a warning.
2010-06-19 10:30:45,639 [6964] ERROR Log4NetDemo.LogTest ... and an error.
2010-06-19 10:30:45,639 [6964] FATAL Log4NetDemo.LogTest ... and a fatal error.
Press any key to continue . . .


In The console window you can see the output of the ConsoleAppender.  The other 3 appenders defined in the app.config are logging elsewhere.
Two files have been created in the same folder as the console app's exe:


2010-06-19 10:16:26,416 [7184] DEBUG Log4NetDemo.LogTest [(null)] - Here is a debug log.
2010-06-19 10:16:26,444 [7184] INFO  Log4NetDemo.LogTest [(null)] - ... and an Info log.
2010-06-19 10:16:26,444 [7184] WARN  Log4NetDemo.LogTest [(null)] - ... and a warning.
2010-06-19 10:16:26,444 [7184] ERROR Log4NetDemo.LogTest [(null)] - ... and an error.
2010-06-19 10:16:26,444 [7184] FATAL Log4NetDemo.LogTest [(null)] - ... and a fatal error.
2010-06-19 10:30:45,613 [6964] DEBUG Log4NetDemo.LogTest [(null)] - Here is a debug log.
2010-06-19 10:30:45,639 [6964] INFO  Log4NetDemo.LogTest [(null)] - ... and an Info log.
2010-06-19 10:30:45,639 [6964] WARN  Log4NetDemo.LogTest [(null)] - ... and a warning.
2010-06-19 10:30:45,639 [6964] ERROR Log4NetDemo.LogTest [(null)] - ... and an error.
2010-06-19 10:30:45,639 [6964] FATAL Log4NetDemo.LogTest [(null)] - ... and a fatal error.

AppenderLog.log


 7184 DEBUG                 Log4NetDemo.LogTest:[7184] Here is a debug log. 7184  INFO                 Log4NetDemo.LogTest:[7184] ... and an Info log. 7184  WARN                 Log4NetDemo.LogTest:[7184] ... and a warning. 7184 ERROR                 Log4NetDemo.LogTest:[7184] ... and an error. 7184 FATAL                 Log4NetDemo.LogTest:[7184] ... and a fatal error. 6964 DEBUG                 Log4NetDemo.LogTest:[6964] Here is a debug log. 6964  INFO                 Log4NetDemo.LogTest:[6964] ... and an Info log. 6964  WARN                 Log4NetDemo.LogTest:[6964] ... and a warning. 6964 ERROR                 Log4NetDemo.LogTest:[6964] ... and an error. 6964 FATAL                 Log4NetDemo.LogTest:[6964] ... and a fatal error.
RollingLog.log
Note how this log file does not contain any new-lines. This is because the format in the app.config did not include the %newline glyph.

<conversionPattern value="%5.5thread%6.6level %35.35logger:[%4.4thread] %message"/>
Compare this to the AppenderLog.log format:

<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
And last but not least the logging information was also being logged to the Debug window in Vs.  DebugView is another useful utility to pick up text sent to the debug stream.  Here's the logging output as picked up by DebugView.


Extensibility of Log4Net
Firstly if you're like me you probably have an interface to isolate your logger implementation from you consuming code.  Obviously you can implement a new derived type that directs logging to log4net.  So choosing to use Log4Net should be an issue to start using within an existing app.

Log4Net provides extensive support for custom formats, filtering and different style of using the appenders. See thisLog4Net page for more information.  In my use of the library I have never had to write a custom plug-in for Log4Net but that is possible too. See the Plug-In page for more information.


Hope that helps someone.
B.

Friday, July 16, 2010

Software is Unpatentable in NZ

There's a blow to certain people who think otherwise.

Posted by Paul Matthews at 12:52 on Thursday, July 15. 2010 in NZCS Blog
Despite what appears to be a big-budget lobbying effort by the pro-patent fraternity, Hon Simon Power announced today that he wouldn't be modifying the proposed Patents Bill hence software will be unpatentable once the Bill passes into law.
This is significant. As we've previously pointed out software patents aren't black and white, and there are certainly pros and cons. However on balance, we believe they represent a far greater risk to smaller NZ-based software providers than opportunity, and there are many cases where they have significantly stifled innovation.Interesting. Software is unpatentable in New Zealand.

Monday, July 5, 2010

Service Oriented Architecture Resources

This page is a organic list of links and information on SOA and SaaS.
Some service oriented architecture links:


"Design Patterns for .Net"'s Pattern for flexible WCF Services

Keyboard and Mouse OS Level Hooks

Intercepting mouse and keyboard events anywhere in the operating system was easier than I thought. It can all be done in C# while using the User32 SetWindowsHookEx method.

Links to more information:
I have a half finished proof of concept of a keyboard and mouse hook for user presence detection as well as global hotkeys.  I'll post it when I get time.

See this December post for more on this topic.