NVelocity template engine sample

Lately I've grown fond of the NVelocity template engine - useful for things like email templates, more complex user friendly error messages etc. Pretty much anywhere where String.Format and string concatenations seem like not the best way to complete the task at hand.

Due to some lack of samples and not a clear indication in the documentation on how to load and handle templates with NVelocity, I've put toghether this little sample application which coveres most of the methods how to load templates from various resources: embedded resources, files and in memory strings. You can, however, roll out your own implementation of the resource loader, but that is a subject for a future post. In the sample application, the different resource loading methods are implemented in the IMessageBuilder implementations.

NVelocity sample Visual Studio 2008 console application

Peace,
Mihkel

Progress timer

I know - it's been too long since my last post and i feel ashamed. So here goes.

I have put together a neat progress timer class for such occasions when you have a long running process looping over a bunch of items and doing its thing. The timer keeps track of the recent times and remaining time. Enough of the chit-chat - to the code...

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

public class ProgressTimer
{
 private readonly Queue _timeQueue;
 private int _itemsRemaining;
 private int _limit;
 private Stopwatch _stopWatch;

 public ProgressTimer(int historyLimit)
 {
  if(historyLimit <= 0)
   throw new ArgumentOutOfRangeException("historyLimit", "History limit must be greater than 0.");

  _timeQueue = new Queue();
  _stopWatch = new Stopwatch();
  _itemsRemaining = 0;
  _limit = historyLimit;
 }

 public void Initialize(int totalItems)
 {
  _itemsRemaining = totalItems;
  _timeQueue.Clear();
  
  if(_stopWatch.IsRunning)
   _stopWatch.Stop();

  _stopWatch.Reset();
 }

 public void BeginStep()
 {
  ThrowIfStopWatchRunning();

  _itemsRemaining--;
  _stopWatch.Reset();
  _stopWatch.Start();
 }

 public void EndStep()
 {
  _stopWatch.Stop();
  if (_timeQueue.Count >= _limit)
  {
   _timeQueue.Dequeue();
  }

  _timeQueue.Enqueue(TimeSpan.FromMilliseconds(_stopWatch.ElapsedMilliseconds));
 }

 public TimeSpan StepTime
 {
  get
  {
   ThrowIfStopWatchRunning();

   return TimeSpan.FromMilliseconds(_stopWatch.ElapsedMilliseconds);
  }
 }

 public TimeSpan RemainingTime
 {
  get
  {
   ThrowIfStopWatchRunning();

   if (_itemsRemaining <= 0)
    return new TimeSpan(0);

   var averageTimeMilliseconds = _timeQueue.Average(x => x.TotalMilliseconds);
   var totalRemainingMilliseconds = _itemsRemaining * averageTimeMilliseconds;
   return TimeSpan.FromMilliseconds(totalRemainingMilliseconds);
  }
 }

 public int QueuedTimesCount
 {
  get
  {
   return _timeQueue.Count;
  }
 }

 public int ItemsRemaining
 {
  get
  {
   return _itemsRemaining;
  }
 }

 private void ThrowIfStopWatchRunning()
 {
  if (_stopWatch.IsRunning)
   throw new InvalidOperationException("The step is still in progress. End the step by calling EndStep().");
 }
}

And here's a sample of how to put it all to good use...

var timer = new ProgressTimer(2);
timer.Initialize(2);

timer.BeginStep();
// As if real work is happening
Thread.Sleep(3000);
timer.EndStep();

var stepTime = timer.StepTime;
var remainingTime = timer.RemainingTime;

timer.BeginStep();
// As if real work is happening
Thread.Sleep(2000);
timer.EndStep();

stepTime = timer.StepTime;
remainingTime = timer.RemainingTime;

I hope someone out there benefits from this. And as always I'm open for comments to improve the above piece of code.

Peace,
Mihkel

Damerau–Levenshtein distance

Now you'd thing what the hell am I rambling about now, but here's the thing. Reading through my daily dose of programming news in Google Reader I stumbled upon this clever algorithm - the Damerau-Levenshtein distance algorithm. It is used to find the number of steps it would take to transform one string into another using the following operations: insertion, deletion, substitution and trasposition. Or put simply - Damerau-Levenshtein distance is a metric to defining the difference between two strings. The main areas of use are spell-checking (typos etc), DNA difference calculation etc. So I read up on the algorith at the Wiki page and decided to implement it just for the implementation's sake. Having fiddled around with the code for some time it dawned on me - I have this OCD when I perform the exact same operation in my head for two words that have a revelance to whichever situation I happen to be in at a given moment. I also provide a corresponding String extension method. Oh and if anyone hasn't picked it up yet, I mainly write code in C# 3.0 as is the case with this post. So without further ado, I present to you the implementation:

public static class DamerauLevenshtein
{
 public static int DamerauLevenshteinDistanceTo(this string @string, string targetString)
 {
  return DamerauLevenshteinDistance(@string, targetString);
 }

 public static int DamerauLevenshteinDistance(string string1, string string2)
 {
  if (String.IsNullOrEmpty(string1))
  {
   if (!String.IsNullOrEmpty(string2))
    return string2.Length;

   return 0;
  }

  if (String.IsNullOrEmpty(string2))
  {
   if (!String.IsNullOrEmpty(string1))
    return string1.Length;

   return 0;
  }

  int length1 = string1.Length;
  int length2 = string2.Length;

  int[,] d = new int[length1 + 1, length2 + 1];

  int cost, del, ins, sub;

  for (int i = 0; i <= d.GetUpperBound(0); i++)
   d[i, 0] = i;

  for (int i = 0; i <= d.GetUpperBound(1); i++)
   d[0, i] = i;

  for (int i = 1; i <= d.GetUpperBound(0); i++)
  {
   for (int j = 1; j <= d.GetUpperBound(1); j++)
   {
    if (string1[i - 1] == string2[j - 1])
     cost = 0;
    else
     cost = 1;

    del = d[i - 1, j] + 1;
    ins = d[i, j - 1] + 1;
    sub = d[i - 1, j - 1] + cost;

    d[i, j] = Math.Min(del, Math.Min(ins, sub));

    if (i > 1 && j > 1 && string1[i - 1] == string2[j - 2] && string1[i - 2] == string2[j - 1])
     d[i, j] = Math.Min(d[i, j], d[i - 2, j - 2] + cost);
   }
  }

  return d[d.GetUpperBound(0), d.GetUpperBound(1)];
 }
}

What do you guys think, should the presentation of interesting algorithm finds in my blog become a recurring subject? I think it wouldn't hurt.

Peace out,
Mihkel

The weirdest clouds I've ever seen

Today we had the weirdest type of clouds in the skies above Tallinn. I've never seen anything even remotely resembling something like this. The whole circus lasted for about an hour and was definitely a spectacular display of atmospheric art. If anyone out there knows the type of these clouds please leave a note in the comments section. Here are some quick snaps i took ...


And a panorama
Keeping eyes open towards the sky,
Mihkel

Cloudy Saab photos

On the same awesomely-cloudy day i decided to take some photos of my beloved Saab. Here are the results ...

Saab photographs darn well, doesn't it? :)
Mihkel

Debugging made easy

I know that debugging and how it's done is a very personal thing. Still - I'd like to share some of my experiences and tips I've gathered during my years of programming. Here goes...

The situation: I know a specific line that I'd like to debug to in a file. The solution before: navigate to the line, add a breakpoint, press F5. It's pretty simple in essence but still a bit cumbersome. And what if this breakpoint is a one-timer - you'd have to remove it afterwards. Furthermore, if you forget to remove it, the next time the debugger breaks at the line it ever so rudly interupts your already mentally challenging debugging session. It just so happens to be there's a solution for all this - a command called Run to cursor. I've set it under the F8 key so it's close to all the rest of the debugging keys. What it does is runs the code and breaks the debugger at the line where the caret is positioned - no need for temporary breakpoints etc. Cool, huh? :)

Next on the list - the Debugger.Break() method in the System.Diagnostics namespace. This method signals a breakpoint to an attached debugger. One might wonder - what's the point - I could have just as easily defined a breakpoint myself, why the fuss about defining it in code. A very valid point. Now imagine a case when there is no debugger yet attached or there is no simple way to attach one. If this is the case then calling this method asks the user to select a debugger. This method comes in handy when debugging e.g. windows services and processes than cannot be started out of Visual Studio. Awesome - I know.

Last but not least - DebuggerStepThroughAttribute in the System.Diagnostics namespace. This attribute can be used to decorate a class, struct, method and constructor and tells the debugger to ignore the decorated piece of code and not step into it, although a breakpoint can still be set an be breaked to. The step through attribute can also be defined on a property but has to be declared on the setter and getter individually. Common uses would be e.g. .net base class library extension methods, simple field accessor properties on domain objects etc. Here's a nuisance this attribute helps to overcome: some object properties are passed into a method as parameters and you want the debugger to step into the method withouth having to initially step through all the properties. Once the getters on the properties have the step through attribute on them the debugger can step right into the desired method ignoring the properties.

I sincerely hope any of this is helpful to some of the fellow programmers out there and once again - it wouldn't hurt to hear you, the reade's, handy tips about code debugging in Visual Studio in the comments section.


Debug away...
Mihkel

Some handy String extension methods

Extension methods - don't we all just love them. If you've been out of the .Net 3.5 loop, here's some catching up - Extension Methods (C# Programming Guide). I thought i'd share some handy string extension methods i've come to love during my experience with C# 3.0. I've never been quite fond of the static String.IsNullOrEmpty method, but thanks to extension methods i can now turn it into an instance method as extension methods can be called on null values as well.

public static class StringExtensions
{
 public static string GetValueOrEmpty(this string @string)
 {
  return @string.IsNullOrEmpty() ? String.Empty : @string;
 }

 public static string ToSingleLine(this string @string)
 {
  if(@string.IsNullOrEmpty())
   return String.Empty;

  string singleLineString = @string.Replace(Environment.NewLine, " ");
  return singleLineString;
 }

 public static bool IsNullOrEmpty(this string @string)
 {
  return String.IsNullOrEmpty(@string);
 }
}

If you have any nifty extension methods that you'd be willing to share, let the readers know through the comments.


Peace,
Mihkel

Discovering ReSharper live templates

Let me start this off by saying - ReSharper live templates are what Visual Studio's code snippets should have been all along. Namely ReSharper's live templates allow the programmer to create powerful custom templates for multiple situations - regular, surround and file templates. It's also possible to use variables (%variable_name%) and make them either user editable or assign a macro to it. The word "macro" here is a bit deceiving. The macros used inside live templates aren't regular Visual Studio macros, rather ReSharper's own .Net macro classes implementing the JetBrains.ReSharper.Feature.Services.LiveTemplates.Macros.IMacro interface. To think about it - this allows for much greated capabilities within macros and better packaging.

One might not recognise his or her bad habbits until someone specifically points it out to them. Something like this happened to me regarding the use of a TODO snipper i've been using. The bad habbit - having to type my name and current date every time the snippet is inserted and being completely oblivious to the fact that there are better ways of doing this. As a coworker pointed out that he's using ReSharper's live templates, i started looking into them and it didn't take long to find out there were powerful ways to extend the templates. Long story short - here's my implementation of the TODO snippet - download the template XML.

This template demonstrates quite well how to use three different types of variables: ones which are user editable, ones which have a constant value assigned to them and ones which retrieve their value from a macro. To use this template save the XML above in a .xml file, open the live templates editor from the ReSharper menu and import the XML file.

P.S. - this post was written in Visual Studio 2008 on a Lenovo IdeaPad S10e running Windows 7 (all visual effects enabled) - combined memory consumption - 800 Mb. Let me end this post by saying - Windows 7 is what Vista should have been all along.


Helping a brother out,
Mihkel

3D - a thing of wizardry and black magic

How many times have I had to explain to someone how to create and render 3D imagery? Well - a lot. Luckily I'm not the only one having to do all the explaining. So these guys came up with an ingenious idea of creating a website which gives all the info about taking the first steps in 3D. And this is all done in a very general fashion so that the techiques learned from the videos could be applied to whichever major 3D application (Cinema 4D, Maya, 3D Studio Max, Lightwave, Softimage, Blender etc). Here's the site itself - The Guerrilla CG Project - Computer Graphics Fundamentals. Now, whenever someone asks how this 3D stuff works, I simply send them this link. There - one less thing to worry about :)

kthnxbai,
Mihkel

Modeling a car - a quick run-through

I wrote this little instructional how-to at CGSociety on the topic of modeling a car in a poly-modeling fashion and thought it might be a good idea to make it a blog post. This question get's asked quite ofter - what is your modeling workflow like, so here's how I do it.

First step is to create a splinecage. This consists of setting up the blueprints and getting them aligned on all four planes - side, top, front and back. Then it's just a matter of creating splines where the edges run on the car. For the body panels I draw the spline e.g. for the hood in the top view, then go into side and front view to get the splineS bent exactly how it should be in all three dimensions. But take great care at this step as it is NOT a no-brainer to change splinecage once you start building the mesh on top of it.

Second step is not always that straight forward. I now have a spline cage in place which I can use for points snapping when creating plygons. Sometimes to understand the mesh flow better, I do some wireframe paintovers on some reference photos in photoshop with my wacom. But do remember that this step cannot be taught in my opinion, this can only be learned through practice. Then I create a single polygon which basically covers the particular area in the most simplistic fashion. e.g. for the door panel I just create a simple quad which stretches out into all the corners of the door panel. Then comes the cutting and finetuning. I then do the cuts in the polygon where they're necessary e.g. the crease in the door, more edges to achieve the curvature etc. Never manually place the points on the edges of panels, only use snapping to the splinecage!!!

At this point you should have the main body panels created, but without the bevel on the edges, which gives a nice thick feel to the body panels. This totally boils down to the tools that your particular applican offers. The end result for the panel edges and corners should look something like this:

There's one row of polygons going inwards and there are two rows of polygons on the surface edge of the body plate. The two polygon rows have a total width of about 2,5-3,5 mm. To produce the edge bevels in Cinema 4D I use the following steps:

  • select all polygons
  • clone
  • extrude inward or do a negative smooth shift of about 1,5mm
  • delete the cloned polygons
  • optimize to weld overlaping points at the newly created crease
  • the outer facing polygons I extrude inner for two steps, 1-1,5mm each
  • add the necessary cuts at the corners to crea a sharp corner

As for all the rest of the points on the bodyplate that aren't exactly on the splinecage, there I use the brush tool in smear mode with very low strength to give minute adjustments where necessary. This is the most time consuming part of the whole process as one change needs to be view at and adjusted from all the angles. It's also possible to use the iron tool or the brush tool in the smooth mode to achieve some inital smoothing from which to work onwards.

I hope this gives a little more insight into the way I model. Look forward for more modeling tutorials covering some very specific subjects like proper edge beveling, sharp corner modeling etc. And don't think this tutorial applies to only cars - the described process can be used to produce almost any hard surface(non-organic) object.

kthnxbai,
Mihkel