Thursday, June 28, 2007

Code Challenge: "John the courier"

Yet another brillian idea popped into my mind today: Why not celebrate the rainy summer with a nice indoor competition - a Code Challenge!


Through the next couple of weeks I intend to publish a couple of challenges like the one below.

Think fast, solve the problem and post it as a comment!

The various challenges will have different winning criterias. These could be: "First valid solution posted", "Valid solution with fewest code-lines", "Funniest approach", "Best Performance", etc.

The Winner will win ... well... the honour along with mocking rights over all other coders in the world (at least those who read this blog and who didn't win).

We'll start off with an easy one...



Challenge #1 "John the courier"

In John's little world there is n cities, named by numbers starting at 0. In every city there is a parcel that's supposed to go to another city in John's world.

John live in City no. 0 and starts by picking up a package there. Then, whenever he delivers a package in a city he takes the package from that city and takes it to where it should go.

The distance between the cities is oddly enough the same as the difference in their names (e.g. the distance between city 10 and city 7 is 10-7=3).

John starts off his day with receiving a list of where the parcels in each city should be delivered. Now, John wonders: How far will I have to travel before I get back to my home (City 0).

Suggest a method that takes an int-array where the city is the index and the value is the destination of the package in the city (like this: int CalculateDistanceToHome(int[] CityPackages);) that returns the distance John must travel before he gets home. You can assume that the packages are distributed in such a way that John will always eventually get home.
First valid solution posted is the winner. Bonus points for recursive solutions.
Let the games begin!

Thursday, June 21, 2007

Making cross-thread calls / events

Many developers first introduction to multithreaded programming is the classic challenge of using one or more "background-worker" threads to do some work thats expected to take longer than the average user wants to wait for his windows application to become responsive again.
Making a worker-method and starting up a thread to run it - or asking the ThreadPool to assign the method to a thread from the pool (QueueUserWorkItem) is quite simple - but soon after the coding starts to get interesting (and fun!).

Now you have to worry about using Mutex and Monitor, etc. to ensure that there's no sharing violation between ressource that the threads share. This in itself is a worthy topics of several books and many blogposts (a lot better than my humble abilities allow me to write).
In a simple scenario as described above you might be able to avoid many of these problems if you contain all the necessary data within each worker thread - but judging on the number of times I've been asked about this, you still encounter yet another issue: cross-thread communication.
Imagine that you've started up your worker-thread and it works happily, enjoying as many cpu-cycles as your operating system allows it, while still letting the main application thread provide a responsive UI. Then you'll at some point start to wonder "Okay....so now my fingamaboob is doing some work...thats nice...I wonder how far it's gotten".
- "No problem", I hear you say. "I'll just have my worker thread output it's status to the window running in the main thread."
This approach will often lead to one of two scenarios:


  1. InvalidOperationException, Cross-thread operation not valid

  2. Some weird construction with a shared status variable, that the UI is polling every X seconds

The correct solution to this problem is to use a proper cross-thread call. For instance you can use Invoke (or BeginInvoke if you're the asynchroneous type). All Windows Forms controls has an Invoke method that you can call and provide with a delegate and a set of parameters. That way you are instructing the thread that "owns" the control to run the call the delegate with the specified parameters.

As you can see below it can be done quite elegantly using anonymous methods and a custom delegate.


public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}



private delegate void ReportStatusHandler(string status);



private void DoBoringWork(object param)

{

for (int i = 0; i < 10000; i++)

{

//Simulate boring work

Thread.Sleep(10);

if (0 == (i % 100))

{

//Output status for every 100



//WRONG:

//listBox1.Items.Add(i.ToString()+" items processed");



//Right:

ReportStatusHandler rsh = new ReportStatusHandler(

delegate(string s) {

listBox1.Items.Add(s);

});

listBox1.Invoke(rsh,

i.ToString() + " items processed");

}

}

}



private void button1_Click(object sender, EventArgs e)

{

//Put work in Queue to be done by ThreadPool

ThreadPool.QueueUserWorkItem(

new WaitCallback(DoBoringWork), null);

}

}

EPiGirl leads the way

I just came across Rachel Goldthorpes newly started Blog on EPiServer development.
She definetly seems to be off to a good start with her post on getting started with EPiServer 5 CMS - it looks very helpful and I'll definetly keep it in mind when I get the chance to try out the new RC.
Welcome to the blogging sphere EPiGirl and keep up the good work!

Wednesday, June 20, 2007

Warning: TortoiseSVN Rename

Now, here's a little lesson I just learned the hard (!) way... When you are using the "Rename" functionality on a folder in TortoiseSVN it doesn't do what you might expect, that is - rename the folder. No, in fact it deletes the f0lder and creates a new one with the contents thats commited to the Subversion repository. And it doesn't just do a "move-to-recycle-bin" kind of deletion, no it makes a "oh-no-daamn-sh*t-aaaargh" deletion of the entire folder along with any uncommitted files you might have in there (yes, even those added to subversion that hasn't been commited yet).
But on the bright side...I suppose this is the kind of mistake you only make once.

Now I'll go back to recreating my lost files from scratch :-(

Friday, June 15, 2007

Generic Type Conversion in C#

I have now several times found myself in the peculiar situation of having two classes, that mostly have the same properties and fields, but doesn't implement the same interface or inherit from the same ancestor, which makes it rather tedious to convert between them.
The problem is typically seen when dynamically loading 3rd party libraries and trying to get them to interact with other 3rd party libraries, or when doing some advanced kinds of communication (like WCF) with complex types.
True, in some cases the problems can be avoided totally by considering your data, assembly and communication structure - but still there's those hopeless cases where you find yourself writing yet another "Create an object of this type based on that type"-code piece. Not a difficult task, but boring.
So, as always I've tried to come up with a stupid solution to a stupid problem: A Generic Type Converter. It uses Generics to "convert" type A to type B. By Converting it simply matches up the public properties and fields and copies the ones that match and that it's allowed to.
Sure, it might be slow (and some might even find it ugly) - but for tasks where the development time is more critical than a few miliseconds of execution time (like for POC's) it might be a nice thing to have in your toolbox.

Keep in mind that this is just a draft version 0.0.0.01.

P.S. Sorry about the formatting, but I'm having a small war with my blogspot and some CSS :-)




using System.Reflection;

public static class GenericTypeConverter
{

public static DestType ConvertType<SrcType, DestType>(SrcType Source) where DestType:class,new()
{
return ConvertType<SrcType,DestType>(Source, null, null);
}

public static DestType ConvertType<SrcType, DestType>(SrcType Source, Dictionary<string, string> SrcDestMapping) where DestType : class,new()
{
return ConvertType<SrcType,DestType>(Source, SrcDestMapping,null);
}

private static string GetMappedName(Dictionary<string, string> Map, string OrigName)
{
if((Map!=null)&&(Map.ContainsKey(OrigName))) return Map[OrigName];
return OrigName;
}

/// <summary>
/// Uses reflection to convert an object to a destination type, e.g. transfers all the properties and members they have in common
/// </summary>
/// <typeparam name="SrcType">Source Type</typeparam>
/// <typeparam name="DestType">Destination Type</typeparam>
/// <param name="Source">Object to convert</param>
/// <param name="SrcDestMap">Mapping between source and destination property names. Null if no mapping exist.</param>
/// <param name="Dest">Destination object or null if it should be created</param>
/// <returns>An object where as many properties and fields as possible have been transferred from Source.</returns>
private static DestType ConvertType<SrcType, DestType>(SrcType Source, Dictionary<string, string> SrcDestMap, DestType Dest) where DestType : class
{
//Create object if it doesn't exist.
DestType dstVar = Dest;
if (dstVar == null) dstVar = Activator.CreateInstance<DestType>();

//Loop through Source' public properties
Type srcTp = typeof(SrcType);
PropertyInfo[] props=srcTp.GetProperties(System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.Static
| System.Reflection.BindingFlags.GetProperty);
foreach (PropertyInfo p in props)
{
//Check if destination type has a settable property of the same type
PropertyInfo pDest = typeof(DestType).GetProperty(GetMappedName(SrcDestMap,p.Name), p.PropertyType);
if ((pDest != null) && (pDest.CanWrite)) pDest.SetValue(dstVar, p.GetValue(Source, null), null);
}

//Loop through Source' public fields
FieldInfo[] mems=srcTp.GetFields();
foreach (FieldInfo fi in mems)
{
FieldInfo mDest = typeof(DestType).GetField(GetMappedName(SrcDestMap,fi.Name));
if ((mDest != null) && (fi.FieldType == mDest.FieldType))
{
mDest.SetValue(dstVar, fi.GetValue(Source));
}
}

return dstVar;
}
}

Blog War: EPiServer vs Sitecore vs Reddot


Some months ago I came across Blogpulse.com (by Nielsen Buzzmetrics) which is a cool service that monitors how popular certain topics arein the Blog-sphere. Just for fun I ran this comparison between 3 of the major european CMS vendors: Sitecore, EPiServer and Reddot.
It would seem that all of the vendors have huge variations in their blog-popularity.

I also couldn't resist trying out battle-of-the-giants BlogPulse and this is what I came(Google vs. Microsoft vs. Apple) on the up with. It would seem that Google is in the lead Blog-wise, but both Microsoft and Apple are gaining (naturally you'd have to take into consideration that all blogs about the fruit that goes by the same name as a major soft/hardware company is also part of the graph).

Wednesday, June 13, 2007

Awesome Public/Free SVN Repository

Several months ago my friend and colleague Jesper (aka Graffen) got the idea to make a free public SVN hosting service.
I know, I know - several of those exist already, but this is awesome because it's so simplistic, easy to use - and without any rules about having to do OpenSource, etc. bothering you.
You just go to the website, create users and repositories and you are ready to go.
I've already started using it on a lot of my pet projects. It's so much nicer to have even your crazy-idea-personal-projects under source control. And Subversion (SVN) source control have been one of my favorites for a long time.
All you need to be running with SVN and this awesome service is just a SVN client and access.

Great job, Jesper!

Spring cleaning

Although spring has passed and summer is here, I thought it might be a good idea to begin doing some spring cleaning in my draft posts.
Typically I get a gazillion ideas for posts I want to make and I instantly begin writing them, but pretty quickly I get another new idea that I'd rather post, resulting in a lot of half-finished draft-posts.
Through the next couple of days I'm going to do some cleanup - probably post some drafts and delete some others - so have patience if you thing it's old-news I'm posting.

Surfing Linkedin

I just had a brief surf through my linkedin contacts and I saw that my good friend Mats Hellström from EPiServer has joined the blogging sphere way back in march.
Welcome, Mats - I hope to see more postings soon!

Check out Mats' blog here.

Friday, June 8, 2007

ShotCode - Let's reinvent barcodes!


About a year and a half ago I was amazed at some of the new java applications for cameraphones I saw at the NeXT conference, among others were a reinvention of barcodes where the idea was that if a special 2d barcode was put on a poster, everybody with a cameraphone could scan it and get someinformation contained in the barcode, typically an ID number which an online service could translate to a URL or something else meaningful.
Of course I hurried home, downloaded the software and tried, but it almost never worked as it should so I gave up.

Today I found another similar service that actually seems to work quite well. And on top of storing your urls in a smart looking circular barcode they even offer to convert the webpage to a format more suitable for the phone that requests it (admitted, that specific part of their service doesn't seem to work too well, but anyway).

I saw the service in use at getjar.com - my favourity source for java apps for my nokia 6380 and there it worked quite impressive...Just start the shotcode application on the phone, take a picture of the barcode on the screen and begin downloading the java-application. Then I checked out Shotcode.com and after a quick registration I found it quite easy to create my own shotcodes....Now I suppose I'll just sit back and wait until this becomes an industry standard so everybody has it on their phones!

Sunday, June 3, 2007

The Meaning of Life

If I were a religious man I might believe that there's one truth in this world, known only to God (and perhaps Knuth also figured it out, but I digress).
If there really was such a one single truth, it should be possible (although perhaps not economical) to let a computer figure out what it is.
Someone once said that if you fill a room with monkey's and typewriters and give it enough time (and bananas!), eventually they will have written the collected works of shakespeare - I suppose this is the idea behind any brute force algorithm (although some might argue that given enough time the monkeys will have evolved into Shakespeare, but again I digress).
But it must be possible to speed up such a process....What if I custom-built the typewriters so they could only write real words that shakespeare used? And what if I had the almighty inspire the monkeys to which words should come in sequence? Perhaps I could shorten down the production time of my shakespeare - or the meaning of life...
So, eager to learn the true meaning of life (okay, who said "42" ?? shut up!) I devised the following plan:

  1. Gather a collection of quotes from some of the most clever men I can think of (e.g. Einstein, Decartes, Voltaire, Vonnegut & Twain).
  2. Calculate a Markov Chain over the bigrams in their sentences
  3. Fill in Divine interaction (in the shape of a random generator)
  4. Start to generate the meaning of life as random quotes

Now, the only problem I face is to determine when my generator actually comes across the meaning of life.... Good proposals can be posted here!



My "Meaning of Life" Random Quote Generator.

If you want to have a "quote of the day" on your website, feel free to use this javascript:

<SCRIPT TYPE="text/javascript"
SRC="http://www.mizar.dk/QuoteGenerator/Javascript.aspx">
</
SCRIPT>