#.think.in
learn.create.enjoy

#.think.in infoDose #4 (20th Oct - 25th Oct)

October 27, 2008 09:22 by brodie

Notable Events

Silverlight

Architecture

ASP.NET AJAX

ASP.NET MVC

jQuery

Testing

Usability

Developer Skills

Singularity Watch

Other

Tips


DevSta {Challenge 2008} - 2nd Place!

October 23, 2008 13:40 by tarn

The winners for DevSta {Challenge 2008} have been announced: GPS Tag wins Microsoft Devsta Challenge. My Desktop Racer entry came 2nd. I'm naturally disappointed I didn't win, but definitely happy with 2nd. It was heaps of fun entering and I'm glad the stress is over ;-)

Congratulations to all the entrants, particularly the winners Jarred Sarge and Michael Minutillo for their GPS Tag Game. Hopefully we'll compete again next year.  Enjoy Vegas boys.


Tags:
Categories: Reviews
Comments (6)

Command Line Arguments

October 21, 2008 11:28 by tarn

I still write heaps of little console applications to do all sorts of things. Most of the console applications I write are tools for tasks like deployment, manipulating data and processing images. Usually they are for my own use, if I find one really useful I might pass it on to the rest of our development team or publish it on this blog. 

For these little tools, I prefer using console applications over windows application as I feel they are more useful. Even though its easier to use a tool that has a little GUI, its not more useful if you ever want to automate it.

Ideally I would prefer to write assemblies and use them from Powershell as it would provide the greatest usage flexibility. But it also requires competence scripting with Powershell. I was very excited about Windows Powershell when it was released, but a year on, I still haven't made it the integral part of my development toolset I thought it would be. This is an area I want to improve on, but this post is about command line arguments.

Generally these little non production, internal applications are quite light weight and fit for purpose. I find I often write simple logging and command line processing that is also fit for purpose. This is fine, its usually very simple, quick to write and works. The problem is that I write this same functionality over and over again for each little application.

I was toying with the idea of writing a generic command line parsing class. I figured I could use reflection on a settings class decorated with attributes describing the specific command line syntax. I figured I could even generate the help text using reflection too. While this seemed like a great idea, I am aware of time I've previously spent (wasted?) re-writing code where a perfectly good open source solution is available.

So I did a search and found a couple of existing command line solutions. Not surprisingly, given they were both written in .NET 2.0+, they both used reflection and attributes. I ended up using the Command Line Parser Library from CodePlex. I'm not sure if it does everything, but it does everything I need for 99% of the console applications I write that require command line processing.  

Anyway here is all the code from my test application:

public class Options
{
    [Option("r", "run", HelpText = "Run the export", Required = true)] 
    public bool Run;

    [Option("n", "Name", HelpText = "Use a specific name")]
    public string Name = String.Empty;

    [HelpOption(HelpText = "Dispaly this help screen.")]
    public string GetUsage()
    {
        HelpText help = new HelpText(new HeadingInfo("Hello World Example", "1.0.0"));
        help.Copyright = new CopyrightInfo("sharpthinking", 2008);
        help.AddPreOptionsLine("Usage: Hello --run");
        help.AddOptions(this);
        return help;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Options options = new Options();
        if (Parser.ParseArguments(args, options, Console.Error))
        {
            string name = string.IsNullOrEmpty(options.Name) ? "World" : options.Name;
            Console.WriteLine("Hello {0}!", name);
        }
    }
}

And we get the expected usage from the command line

image

Now I have to make sure I bundle the console applications with an external assembly, but it does make using command line arguments easy.  


Tags:
Categories: Reviews
Comments (0)

#.think.in infoDose #3 (13th Oct - 17th Oct)

October 20, 2008 08:15 by brodie

Notable Events

Management/Process

Architecture

ASP.NET

Silverlight

Other

Singularity Watch

Books to Read

Quotes

  • "An engineer will endlessly tinker with a project as long as it's sitting in front of them. Endlessly" - rands (twitter)
  • "There ain’t no rules around here. We’re trying to accomplish something." —Thomas Edison

Functional Programming

October 19, 2008 19:18 by tarn

The Problem, The Opportunity

 

Brodie and my initiatives in the area of search have been rewarded by management with a two week project to improve search on our sites. In the two weeks we also intend to fix one of the darkest corners of the code base, the Product/Site publishing logic, which is the main reason the search needs revisiting. We couldn't get the two weeks just to improve infrastructure, so we promised sub one second search results and better relevance as a carrot.

The web application powers multiple sites (>100) and has lots of products (>100,000). There needed to be some way of controlling what products belonged to what site. As products can appear on multiple sites and new sites are constantly being added, this is not trivial. The solution implemented is a site publishing rules system. Products can be excluded from a site by Classification, Product or Brand.

So far the logic is pretty simple, but another type of rule was also added. Products, Classifications and Brands can also be made specific to a site (they can actually be made specific to multiple sites). The logic is that a Product, Classification or Brand that is specific to a site will appear on that site, but not on other sites. In my opinion this is kind of crazy, but the thinking is; If you have a very specific product that should only be published on one or two sites, its easier to make it specific to those two sites rather than excluding it from every other site and new sites. Ok, fair enough.

The problem is that this logic is scattered through all our layers down to the database. There is duplication of logic over separate layers causing maintenance problems and it has been identified as a clear performance bottle-neck of any product list retrieval operation.

The scope of this prototype is a quick, robust, maintainable and fully unit tested solution that implements the product site publish logic.

Database

 

These rules are held in 6 SQL joining tables, which I think is interesting itself. The primary keys are not unique across products, brands and classifications meaning to enforce referential integrity and not allow nulls you do need a few tables. While I think this is a very good argument to have primary keys unique across all your database objects, its not always an option.

We could also have used 3 tables by combining the excluded and specific tables and adding a flag or lookup id. I think less is better, less tables means we can be more flexible with how we manipulate the data in code. Even in T-SQL I think I'd prefer less tables, less joins and more where statements - de-normalized. But that just my opinion in this scenario. 

As I move this logic out of the database and into managed code I'll end up abstracting the data to one table anyway, for this prototype it doesn't matter how the rules are created or persisted.

Functional Languages

 

Now back to the title of this post, I think this problem is really suited to functional programming. I've become more interested in functional programming after listening to a Heading Code pod cast with Matt Podwysocki. My experience with functional programming is limited and I've never found it very exciting. I learnt a bit of Haskel to help a mate with a computer science subject he was doing, but I was never really going to get to into it. At that time I believed all languages were inferior to C++.

As I've become more involved in software development I think its more important to use other languages. There is an inevitability that your language of choice will be relegated to legacy tasks as newer languages emerge better suited modern computing and user experience. C# code making heavy use of generics, extension methods, anonymous delegates and LINQ is just not the same language as the C# that rolled out with .Net 1.0. Dynamic and functional languages are becoming first class citizens.

I'm not actually going to write this in F# for now, but I think the way I've implemented my solution in C# is very functional although I leverage some OO concepts I might not be able to use in a strictly functional language.

 

Solution Overview

 

Instead of having all these separate lists of rules I've just created one list which can be queried. It makes heavy use of what Rob Conery described as a Pipes and Filters pattern in the ASP.NET MVC Storefront series. The pipes and filters are implemented as extension methods that add filters and data transformations. A collection of these small and easily testable extension methods can be used to build very powerful data retrieval and processing constructs to clearly describe business logic.

The scope of the prototype is really just a single function that implements the site publishing logic described earlier. It takes a Product, Site and List of Rules as parameters and returns the publish rule.

As soon as I started thinking about a solution to the problem I knew there was one thing I didn't want to do. I could see there was potentially a lot of repeated code for calling logic for products, classifications and brands individually. There is no need as it is the same logic that needs to be applied to each. I wanted to find a more elegant solution. I used an object orientated solution; the Rule class itself is abstract and is inherited by ProductRule, ClassificationRule and BrandRule.

public abstract class Rule
{
    public int SiteId { get; set; }
    public RuleType Type { get; set; }
    public int Value;
    public abstract bool Compare(Product product);
}

 

The only thing implemented by the specific rule classes is how to bind the Value to a property on the Product class.

public class ClassificationRule : Rule
{
    public override bool Compare(Product product)
    {
        return (Value == product.ClassificationId);
    }
}


public class ProductRule : Rule
{
    public override bool Compare(Product product)
    {
        return (Value == product.ProductId);
    }
}

..

 

I could have implemented this in a more functional way, but it does seem like a clean solution given I am using C#. 

Testing the Bits and Pieces

Testing the extension methods is easy with such simple domain objects. For most of the extension methods I only wrote a couple of small tests like this:

[TestMethod]
public void FromSite_ReturnsSiteRule()
{
    List<Rule> rules = new List<Rule>() { { new ProductRule() { SiteId = 1 } } };
    Assert.AreEqual(1, rules.FromSite(1).Count());
}

[TestMethod]
public void FromSite_FiltersSiteRule()
{
    List<Rule> rules = new List<Rule>() { { new ProductRule() { SiteId = 1 } } };
    Assert.AreEqual(0, rules.FromSite(2).Count());
}

 

I used LINQ constructs rather than the trusty delegates I use everywhere else for the extension methods. I like it, its clear and easy to read. And this is my point, its changed the language dramatically.

public static IEnumerable<Rule> FromSite(this IEnumerable<Rule> rules, int SiteId)
{
    return from rule in rules
           where rule.SiteId == SiteId
           select rule;
}

 

Generic Test Classes

 

I'm going to start using the the Microsoft Visual Studios Unit Test Framework. It means people who don't use the same testing framework flavour don't get build errors when they download code download and try to build it. As the attributes work with NUnit GUI and TestDriven.NET I'm happy to use it for now. I not sure if there is any mock testing support, but it does allow inheriting templated test methods.

For the same reason I didn't want to write code that called product rules, classification rules and brand rules individually, I don't want to write tests for them individually either.

public class GenericSiteRulesTests<T>
    where T : Rule
{

    [TestMethod]
    public void ProductWithNoRules_ProductIsReturned()
    {
        Assert.IsTrue(RuleLogic.ProcessRules(new Product(), new List<Rule>(), 1));
    }

    [TestMethod]
    public void ProductIdCanBeExcluded_ExcludedProductIsNotReturned()
    {
        List<Rule> rules = new List<Rule>() {{ CreateRule(1, RuleType.Excluded, 0 )}};
        Assert.IsFalse(RuleLogic.ProcessRules(new Product(), rules, 1));
    }

    ..

}

 

The way this is done I think is pretty cool, I did something similar when I was looking at testing Text Search algorithms recently. All the generic rule tests are written in a generic test class which must be templated to a type the derives from Rule.  The class doesn't have a test class attribute. This is because the test classes we want to run are actually classes that inherit from the generic test class.

[TestClass]
public class ClassificationSiteRulesTests 
    : GenericSiteRulesTests<ClassificationRule>
{
}

[TestClass]
public class ProductSiteRulesTest 
    : GenericSiteRulesTests<ProductRule>
{
}

[TestClass]
public class BrandSiteRulesTest 
    : GenericSiteRulesTests<BrandRule>
{
}
 

These classes do have the test class attributes. Although they are empty, they expose all the templated methods inherited from the generic test class. These methods can be executed by a test runner.

 

  image

NUnit GUI has running all the tests.

The Logic

 

Ok, so its not really "clear and easy to read", but it is very compact and concise.

public class RuleLogic
{
    public static bool ProcessRules(Product product,  IEnumerable<Rule> rules, int siteId)
    {
        // return false if there is any exclusion rule that applies to this product
        if (rules.FromSite(siteId)
                 .WithType(RuleType.Excluded)
                 .AppliesTo(product)
                 .Count() > 0) return false;

        // every rule type (ie ProductRule) that any site has a specific rule relating too
        foreach (Type type in rules.WithType(RuleType.Specific)
                                   .AppliesTo(product)
                                   .RuleTypes())
        {
            // this product requires a specific rule of this type
            if (rules.WithType(RuleType.Specific)
                     .WithTarget(type)
                     .FromSite(siteId)
                     .AppliesTo(product)
                     .Count() == 0) return false;
        }

        return true;
    }
}

 

Conclusion

 

It all seems fine, all the 33 tests are running and passing, coverage is at 100%.. still I have some strange feeling there is still a critical bug in there, somewhere. 

image

We'll wait and see Monday morning if the project will go ahead and this prototype can be extended into part of a production quality product publishing rules engine. Oh, and the sub 1 second product searching..


VIC.NET Meeting Overview 14th Oct 2008

October 15, 2008 16:34 by brodie

This was probably one of the better VDNUG meetings I had been to ... I'm glad I got there early enough for some pizza as more than the usual amount of geeks rocked up tonight ;-)

I was also happy to hear that they are going to start a Silverlight Users Group with the first meeting to be held on 27th November - WOOT!  After getting into Silverlight a bit more during the Devsta 08 competition I'm pretty keen to continue to develop my skills further.

Silverlight 2 for Developers

Jonas Folleso gave a great presentation about Silverlight, demonstrating his DiveLog application. What was so good about the presentation besides the great slides and flawless code demos was the fact that this was a very well thought out and well designed "real world" application which dealt with Designer collaboration issues (which he does well considering his girlfriend is a designer), Unit testing, and browser issues (navigation, printing, SOA, etc), converting Silverlight to WPF application.

In summary he covered the following;

  • using forms authentication and custom membership providers to implement secure web services.
  • using Expression Blend and how a developer can be more helpful to the designer - using Mocking to provide dummy data to the design surface.
  • showed examples of data binding, using INotifyPropertyChanged, ObservableCollections, IValueConvertors and DataContexts.
  • showed a great example of design implementing Command pattern to minimize the amount of code in the code behind file
  • demonstrated the built in Silverlight unit testing capabilities which run in the browser

It was the best end to end Silverlight presentation I've seen and we look forward to more from Jonas.  Download the source code from his site check it out for yourself.

NOTE: The presentation was streamed, but i'm not sure if it was recorded. Will post link when it becomes available.

 

Multi-point touch user interface

John Li brought in his custom built surface computer to demonstrate some multi-touch applications and discuss possibilities of other useful applications. His surface computer was put together after several prototypes and end up costing him (or his employer) around $6000 - not bad, but not great if you wanted to knock one together yourself - although John reckons he could put one together in a week ... he might have a good little business there.

He demonstrated the usual applications;

  • Photo manipulation - resizing, rotating, etc (although he realised he needed a close all button ;-)
  • Map Navigation - including data from Virtual Earth and Google Maps. What was impressive here was the overlaying functionality
  • High density multi-scale images (read Deep Zoom-able images) - with some cool architectural drawings and demonstrated the overlaying technology again - showing drawings from different levels intersecting with each other.
  • Video manipulation - similar to the photo app - but showed how you could have multiple users working together on the same surface to put together a film clip.
  • Piano

His general point was  how 'natural' multi-touch applications translate well to surface technology.  Overall very interesting as always - I was kind of hoping to see some code but I guess the Surface SDK will be coming out soon after the PDC (Professional Developers Conference).