Thursday, 29 January 2009

Another great error message from MS

Spent the last 2 hours trying to diagnose an error message.  I am writing a batch file which simply executes a SQL script using sqlcmd.  This is the command:

sqlcmd -S %SQLServerName% -E -i InstallSql.sql > InstallSql.txt

For the life of me, I have no idea what is going wrong.  The error message is incredibly useful

Sqlcmd: Error: Microsoft SQL Server Native Client 10.0 : Syntax error, permission violation, or other nonspecific error

Ok, so it could be one thing, or maybe it’s another, oh actually it could be anything at all really.  Essentially they're saying YOU ARE ON YOUR OWN WITH THIS ONE, trial and error is the only way.

Anyone got any ideas what this could be? I’m gonna throw my laptop out of the Window soon!

Wednesday, 28 January 2009

Azure Event Log and log4net

I have been experimenting with Windows Azure recently for hosting a small application I wrote.  Thus far I am fairly impressed; despite a few periods of downtime and the odd bug with deployments, things seem to be stabilising fairly quickly and it’s all working well now (well I can’t complain as it’s currently free!)

Azure’s hosting platform provides a number of services which allow you to interact with the platform.  These are mostly through the Microsoft.ServiceHosting.ServiceRuntime.RoleManager class.  For example, you are able to retrieve configuration settings from the service configuration file, access local non persistent resources, and log messages to the Azure Event Log, via the RoleManager.WriteToLog method.

Messages can be copied from the log to any Azure Storage account simply by clicking a button on the configuration menu of the hosting instance:

image

These logs are copied to the “blobs” area of your chosen Azure Storage account (there are also tables and remote queues) and Microsoft have provided a fairly simple REST API for managing the data stored within the account.  There is also a .NET api which wraps the REST API but I am yet to look at it (I will do once I build a persistence layer for my application).

A few tools have been written for viewing the log files – Azure Storage Explorer seems to be the best that' I’ve tried, those there may be more which I’ve not found yet.  You simply put the URLs of the REST endpoints into the config file and you get a nice viewer which lets you see all the messages and delete

Now all my applications tend to standardise on log4net for logging messages, which provides configurable and customisable routing of logging messages to pretty much any target you want.  I wrote a simple log4net appender which can be used to route messages to the Azure Event Log.  Here is the source code

public class AzureAppender : AppenderSkeleton
{
    protected override void Append(LoggingEvent loggingEvent)
    {
        RoleManager.WriteToLog(GetLogName(loggingEvent), loggingEvent.RenderedMessage);
    }

    private static string GetLogName(LoggingEvent loggingEvent)
    {
        if (loggingEvent.Level == Level.Critical)
            return EventLogNames.Critical;

        if (loggingEvent.Level == Level.Error)
            return EventLogNames.Error;

        if (loggingEvent.Level == Level.Warn)
            return EventLogNames.Warning;

        if (loggingEvent.Level == Level.Info)
            return EventLogNames.Information;

        if (loggingEvent.Level == Level.Verbose)
            return EventLogNames.Verbose;

        return EventLogNames.Error;
    }

    private static class EventLogNames
    {
        public const string Critical = "Critical";
        public const string Error = "Error";
        public const string Warning = "Warning";
        public const string Information = "Information";
        public const string Verbose = "Verbose";
    }
}

Note that log4net has lots more log levels than Azure supports, so I just default to Error if I get a message which is not one of the matching levels.

Monday, 28 July 2008

Microsoft Sponsors Open Source Apache

Given that Microsoft have invested lots of time and money in their own web server (IIS), this is a true endorsement of changes afoot at Microsoft http://news.bbc.co.uk/1/hi/technology/7528857.stm

I personally think this makes complete sense for them. I truly believe as we move to a more service delivered software models, the value of source code (or software IP) becomes less important, as licence revenue becomes less of a percentage of total revenue for the big boys such as MS.

For companies like Microsoft, interoperability is very important and its relevance is definitely growing. For example, I am sure that to allow users to be able to transfer services currently running on a LAMP architecture to run on Microsoft's own hosted Windows "cloud" architecture is going to be important for them in future (even if it's not running on a .NET platform). Here is some more detailed info

Interestingly enough, their competitor Apple seems to be going in the other direction with their iPhone SDK, for which the licence agreement apparently does not allow people to build open source software... hmm!

Wednesday, 23 July 2008

Is INotifyPropertyChanged an anti-pattern?

Something is starting to bother me recently about data binding and the INotifyPropertyChanged interface. It's just that EVERY class you write ends up having to implement it (I am generally talking about writing WPF/Silverlight applications here). And that's just not sitting well with me!

It doesn't sit well because I believe it violates the principles of separations of concern. The major annoyance for me lies with calculated properties (those which are derived from another). Lets start with a simple class, Order, which contains two properties, ItemPrice and Quantity (other fields and methods omitted for sake of brevity):

public class Order : INotifyPropertyChanged
{
  public decimal ItemPrice 
  { 
    get { return this.itemPrice; }
    set 
    {
       this.itemPrice = value;
       this.RaisePropertyChanged("ItemPrice");
    }
  }

  public int Quantity 
  { 
    get { return this.quantity; }
    set 
    {
       this.quantity= value;
       this.RaisePropertyChanged("Quantity");
    }
  }
}

We need to add a property TotalPrice to this entity which will expose the total price of the order. What do we do here? This is a calculated value so should clearly be read only, and I usually implement the calculation within the property itself. What I have found myself doing many times in the past (and I have seen done in a lot of examples) is:

public class Order : INotifyPropertyChanged
{
  public decimal ItemPrice 
  { 
    get { return this.itemPrice; }
    set 
    {
       this.itemPrice = value;
       this.RaisePropertyChanged("ItemPrice");
       this.RaisePropertyChanged("TotalPrice");
    }
  }

  public int Quantity 
  { 
    get { return this.quantity; }
    set 
    {
       this.quantity= value;
       this.RaisePropertyChanged("Quantity");
       this.RaisePropertyChanged("TotalPrice");
    }
  }

  public decimal TotalPrice
  {
    get { return this.ItemPrice * this.Quantity; }    
  }
}

This is nasty. We have had to modify our other two properties just because we have added this new one. It works, but as you add more and more dependent properties your code gets messy. Those properties shouldn't need to know that the TotalPrice property exists!

That pattern breaks down completely when you start using inheritance in your domain objects. Imagine if I now require a new type of domain object, SalesOrder, where I want to express the fact that there is a commission (expressed as a fraction) which needs to be paid to some salesperson on this order:

public class SalesOrder : Order
{
  public decimal SalesCommision
  { 
    get { return this.salesCommision}
    set 
    {
       this.salesCommisionPercentage = value;
       this.RaisePropertyChanged("SalesCommision");
       this.RaisePropertyChanged("TotalCommission");
    }
  }

  public decimal TotalCommission
  { 
    get { return this.TotalPrice * this.SalesCommission; }
  }
}

Uh-oh! It's come a bit unstuck here. If the price changes in the base class, my UI is not going to redisplay the total commission! This could be great for my sales person but not so great for my accountant!

So what do we do here to get around this? We clearly can't modify our base class, so how about we listen to our own property notifications, like thus:

public class SalesOrder : Order
{
  // Properties defined as previously //

  protected override void RaisePropertyChanged(string propertyName)
  {
     base.RaisePropertyChanged(propertyName);
     if (propertyName == "TotalPrice")
     {
        this.RaisePropertyChanged("TotalCommission");
     }
  }
}

Here we override the method which raises the event, check if the relevant dependent property is being raised, and if so we raise a changed event on our commission property. This works, but YUCK! Just imagine having to unit test all this! :-(

Note that we end up with the same problem if we use composition. Imagine that instead of storing the sales commission on our entity, it was actually stored on a related SalesPerson entity and we need to calculate it from there. Now we need to know that if the sales person's commission changes, the order's total commission has changed:

public class SalesOrder : Order
{
  public SalesPerson SalesPerson
  { 
    get { return this.salesPerson; }
    set 
    {
       if (this.salesPerson != null)
       {
          this.salesPerson.PropertyChanged -= HandleSalesPersonPropertyChanged;
       }

       this.salesPerson = value;
       this.RaisePropertyChanged("SalesPerson");
       this.RaisePropertyChanged("TotalCommission");

       this.salesPerson.PropertyChanged += HandleSalesPersonPropertyChanged;
    }
  }

  public decimal TotalCommission
  { 
    get { return this.TotalPrice * this.SalesPerson.Commission; }
  }

  protected virtual void HandleSalesPersonPropertyChanged(object sender, PropertyChangedEventArgs e)
  {
     if (e.PropertyName == "Commission")
     {
        this.RaisePropertyChanged("TotalCommission");
     }
  }
}

We subscribe to the PropertyChanged event on our sales person, and when its commision is changed, we act accordingly.

I think this is all a mess, and it just gets worse and worse as you build up your domain model and add more classes and more relations. It's easy to forget one of these dependencies. If you are building a fairly complex UI on top of this (e.g. one which allows you to drill down and navigate through the relationships and make changes to objects), I'm so sure you will introduce bugs due to not raising the event, I know it's happened to me!

On my next (real) WPF project this is definitely something I will be thinking about seriously.

Anyway I would be interested to know what people think about this. Is this a problem which other people have faced? How do you architect your applications to avoid this complexity?

Saturday, 19 July 2008

Refactoring Silverstone - Removing static container and cleaning up the Shell

Hey readers, hope all is good! Firstly to apologise on having been fairly quiet on the Silverstone / Silverlight blog postings, especially with regards to my series on architecting Silverlight applications using the MVC patterns (most recent article here).

So, Silverlight Beta 2 came out and I spent some time absorbing those changes and trying to work out how they affect what I was doing. I have also made some alterations to the Silverstone framework to remove some code smells I was experiencing when wiring the Views and ViewModels together in preparing part 4 of the series.

One thing that Beta 2 adds is much better support for bubbling of RoutedEvents. This is a great change, but it actually caused a problem for my CommandManager class! The CommandManager was relying on the mouse and keyboard events bubbling up from their target element to the application root in order to provide automatic invalidation of the CanExecuteChanged handler on registered commands. Now that Silverlight has more advanced handling of these events, they no longer bubble up to the application root (as the textbox/button/whatever marks them as e.Handled=true). This is the correct behaviour and mirrors WPF, but it means my technique no longer works, making the ViewModels slightly more complex as they need to manually raise the CanExecuteChanged event.

Once Silverlight gets event tunnelling, which I'm sure (hope!) will be incorporated into the next release, I will add this back in as we will be able to capture the events before they are actually handled by the target element (e.g. PreviewKeyDown / PreviewMouseDown).

So I now have a basic view working, and will be creating the other views soon and blogging the next part in the near future.

As I mentioned, whilst working on this, I made a few refactorings to Silverstone (and to the sample code):

The Ioc Container is no longer a static class. This always bothered me - why have a static class here? So I made it a non static and also made it implement an interface (IContainer). The added bonus of this (and the real reason I did it) is that other components can access the container without going through a static reference. So, the container now registers itself with itself, and you can get it passed to your class simply by adding a constructor parameter of type IContainer.

Once I did that, I refactored the Shell class, which was looking rather nasty from the client API side of things! If you remember in Part 2 of my series, I was writing a LoginViewModel but I was having to pass the other related views into the constructor in order that I could navigate to them upon certain actions (see the comments saying This is just an empty view interface for now *shudder*). I think having to do this makes iterative development much harder as you need to create fakes and register them with the Ioc container just to have your class be constructed!

So instead, the Shell now uses the IContainer to get the views from it and all I need to do is pass the type of the View interface to the Shell and it can do everything from there, like so:

this.shell.Navigate<IFriendListView>();

Finally, I moved the entire sample code into the actual Silverstone SVN repository, which makes it much easier for me to develop the two things side by side! So if you want to an early preview of the code, you can get it from svn

I will be posting the entire solution once it's finished, and hopefully uploading it to some hosting area in the cloud.

Wednesday, 9 July 2008

An unmanaged version of WPF coming?

This sounds incredibly interesting - it appears Microsoft are working on what looks like a native version of WPF!

Anyone heard about this or know any more about this - I would love to know some details! An unmanaged version would be great and would probably yield massive performance issues even for unmanaged WPF as a lot of the grunt work would presumably be able to be pushed to unmanaged code.

Could this be the return of the Microsoft's old Cairo project (which now seems to be being worked on by an external group of developers if I'm not mistaken - www.cairoshell.com)

Thoughts?

Sunday, 6 July 2008

Using Linq's Expression Trees to Enable Better Refactoring

How many times have you seen code like this:

public DateTime StartDate
{
  get { return this.startDate; }
  set
  {
    this.startDate = value;
    this.RaisePropertyChanged(this, "StartDate");
  }
}

I know I have! There are many areas of .NET development where you are required to specify the name of a property or method as a string. This is fine, but if you rename the property, there is a chance that you will forget to update the string too, which is definitely not good!

.NET 3.5 and Linq introduces a new feature called expression trees in the C#3 compiler. Compilers typically generate an AST (abstract syntax tree) from the code you write, which is then checked and transformed into machine code (or in .NET case, MSIL). By using an expression tree, you tell the C# compiler not to compile your code into MSIL, but instead to create a representation of the code in object form. This tree can then be navigated through methods on the Expression objects.

Using an expression tree, we can simply write a method which will return the name of whichever method or property is being called (I used an extension method):

public static class Extensions
{
    public static string GetPropertyName<T,S>(this T obj, Expression<Func<T,S>> expr)
    {
        return ((MemberExpression) expr.Body).Member.Name;
    }
}

To call this is fairly simple, we rewrite the previous code as:

public DateTime StartDate
{
  get { return this.startDate; }
  set
  {
    this.startDate = value;
    this.RaisePropertyChanged(this, this.GetPropertyName(p => p.StartDate));
  }
}

The code above creates a lambda which returns the value of StartDate method and passes it to the GetPropertyName() method. If this lamdba was to be executed, it would return the startDate, however the GetPropertyName() function never executes the lambda, it simply peeks into the code being called and returns the name of the property.

This technique is starting to be used everywhere and it's so useful. Code as strings is nasty!

Have a great day...