Thoughts on Technology, Methodology and Programming.

Archive for the ‘Software’ Category

Databind a Combobox to an Enum Property – Version 2.0

Posted by Marcus Wyatt on 18 April 2008

I’ve first posted this tip on the 14 of May 2005 and I still get good traffic to the post. So I decided to update the post and code samples to use Framework 2.0 (I’m still not using 3.5) and improve the code somewhat.

The problem:

How do I databind my combo box to my domain object that has a property of some enum type?

The solution:

Quite simple, firstly we will create an object (EnumComboBoxItem) that would encapsulate and represent each item in the combo list data source. EnumComboBoxItem is a pure fabrication class that has two properties we’ll use when databinding to the combo. We have a Value property which is used by the ValueMember property on the combo box and EscapedValue that is used by the DisplayMember property of the combo box. Note that when we construct a new EnumComboBoxItem instance that we call the AsciiEscape method in the constructor when populating the escapedValue field.

Here is the code:

1 using System;

2 using System.Collections.Generic;

3 using System.Text.RegularExpressions;


5 namespace BindComboToEnum

6 {

7 ///

8 /// The enum combo box item

9 ///

10 public class EnumComboBoxItem

11 {

12 #region Constants


14 public const string DisplayMember = “EscapedValue”;

15 public const string ValueMember = “Value”;


17 #endregion


19 #region Readonly & Static Fields


21 private readonly string escapedValue;

22 private readonly object value;


24 #endregion


26 #region C’tors


28 ///

29 /// Initializes a new instance of the class.

30 ///

31 ///

The original value.

32 public EnumComboBoxItem(object originalValue)

33 {

34 value = originalValue;

35 escapedValue = EscapeAsciiValues(originalValue.ToString());

36 }


38 #endregion


40 #region Instance Properties


42 ///

43 /// Gets the escaped value.

44 ///

45 /// The escaped value.

46 public string EscapedValue

47 {

48 get { return escapedValue; }

49 }


51 ///

52 /// Gets the value.

53 ///

54 /// The value.

55 public object Value

56 {

57 get { return value; }

58 }


60 #endregion


62 #region Instance Methods


64 ///

65 /// Returns a that represents the current .

66 ///

67 ///

68 /// A that represents the current .

69 ///

70 public override string ToString()

71 {

72 return escapedValue;

73 }


75 #endregion


77 #region Class Methods


79 ///

80 /// Creates the data source for the enum type.

81 ///

82 ///

Type of the enum.

83 /// When the type passed is not an enum the exception is raised.

84 ///

85 /// Returns a generic list to be used as the combo datasource.

86 ///

87 public static List<object> CreateDataSourceFor(Type enumType)

88 {

89 if (!enumType.IsEnum)

90 throw new ApplicationException(“When using the Enum combo data source you are only allowed to use enum types.”);


92 Array enumValues = Enum.GetValues(enumType);


94 List<object> result = new List<object>();


96 for (int index = 0; index < enumValues.Length; index++)

97 {

98 result.Add(new EnumComboBoxItem(enumValues.GetValue(index)));

99 }


101 return result;

102 }


104 private static string ConvertAsciiValueToStringRepresentation(string currentRegexMatchValue)

105 {

106 string result = string.Empty;

107 const int BaseValue = 16;


109 if (currentRegexMatchValue.StartsWith(“0x”))

110 {

111 // grab the remainder string after the 0x

112 string asciiCodeValue = currentRegexMatchValue.Substring(2);

113 // convert the remainder string to a byte

114 byte byteValue = Convert.ToByte(asciiCodeValue, BaseValue);

115 // now we can convert to a character and find the string of the character

116 result = Convert.ToChar(byteValue).ToString();

117 }

118 return result;

119 }


121 private static string EscapeAsciiValues(string rawValue)

122 {

123 string result = string.Empty;


125 if (rawValue == null)

126 return result;


128 // Find 0x with any four alpha-numeric characters

129 Regex regex = new Regex(“0x[0-9A-Z]{4}”);


131 MatchCollection matchCollection = regex.Matches(rawValue);

132 Match matchPrevious = null;


134 for (int i = 0; i < matchCollection.Count; i++)

135 {

136 // if no match (ie. null) set to 0, else the current index + length

137 int startIndex = (matchPrevious == null ? 0 : matchPrevious.Index + matchPrevious.Length);


139 // add the part of the string that is not the ascii expression

140 result += rawValue.Substring(startIndex, matchCollection[i].IndexstartIndex);


142 // convert the ascii expression to a normal string

143 result += ConvertAsciiValueToStringRepresentation(matchCollection[i].Value);


145 matchPrevious = matchCollection[i];

146 }


148 if (matchPrevious == null)

149 result += rawValue;

150 else

151 result += rawValue.Substring(matchPrevious.Index + matchPrevious.Length);


153 return result;

154 }


156 #endregion

157 }

158 }

The EscapeAsciiValues method is used to Replace the Ascii characters in our Enum with the character representation. We do the Ascii characters because we want our combo to display “Bi- Annual” instead of “BiAnnual”. Look at the following enum as an example:

1 namespace BindComboToEnum

2 {

3 public enum PaymentFrequencies

4 {

5 Annual = 1,

6 Bi0x00A00x002D0x00A0Annual = 2, // Bi – Annual

7 Quarterly = 4,

8 Monthly = 12,

9 Fortnightly = 26,

10 Weekly = 52

11 }

12 }

Now, all that we need is the following code behind the form to bind our Combo box and we are away:

22 private void InitDataBindings()

23 {

24 PaymentFrequencyComboBox.DataSource = EnumComboBoxItem.CreateDataSourceFor(typeof(PaymentFrequencies));

25 PaymentFrequencyComboBox.DisplayMember = EnumComboBoxItem.DisplayMember;

26 PaymentFrequencyComboBox.ValueMember = EnumComboBoxItem.ValueMember;

27 PaymentFrequencyComboBox.DataBindings.Add(“SelectedValue”, new Loan(), “PaymentFrequency”);

28 }

The EnumComboBoxItem.CreateDataSourceFor method creates an List<object> for us to use as a data source for the combo box.

And there you have it, a Combobox bound to an Enum!

Posted in Software | Tagged: , , | Leave a Comment »

Run gem install behind a firewall in Windows

Posted by Marcus Wyatt on 18 March 2008

I’m contracting at a client running a Novell network and wanted to create some small little ruby scripts to automate some tasks for me. But I ran into problems using gem install behind their firewall. I’m getting the following error:

ERROR: While executing gem … (Gem::RemoteSourceException) HTTP Response 407

Here is the steps I followed to get gem install working on my windows xp machine in painstaking detail: 🙂

Firstly we need to set the HTTP_PROXY environment variable. I’ve played around with different options, using uid and pwd and other suggestions, but all I needed was the following:

  1. On the desktop right click the ‘My Computer’ icon and select properties.
  2. Now you can either add the HTTP_PROXY variable to the ‘User’ or the ‘System’ variables by clicking the ‘New’ button.
  3. Within the new system variable dialog, specify ’HTTP_PROXY’ as the variable name and in the value area a url in the following format – http://%5Bproxy_ip%5D:%5Bproxy_port%5D – i.e.

Next we install the Ruby Win32 SSPI which gives ruby the ability to authenticate with ISA natively. We need this library because as far as I understand, it patches the Open-uri library because of some incompatibilities with windows. Anyways, follow the following steps to get it working:

  1. Download rubysspi from the Ruby Win32 SSPI project page(also available as gem install rubysspi but that doesn’t help much, does it?)
  2. Install the gem locally using the following command: gem install [local_path_to_gem]\rubysspi-1.2.3.gem i.e. C:\gems\rubysspi-1.2.3.gem
  3. Now copy the spa.rb file from the gem install directory and paste it in the site-ruby directory. i.e. If ruby is installed in C:\ruby, then the paths should be:
    • origin path – C:\ruby\lib\ruby\gems\1.8\gems\rubysspi-1.2.3\spa.rb
    • destination path – C:\ruby\lib\ruby\site_ruby\spa.rb
  4. Find gem.bat in your ruby bin directory (C:\ruby\bin) and replace the last line (i.e. "%~d0%~p0ruby" -x "%~f0" %*) with the following line – @"ruby" -rspa "c:\ruby\bin\gem" %1 %2 %3 %4 %5 %6 %7 %8 %9
  5. Test you can access the remote ruby gems by executing the following command: gem list rails -r
  6. You should see similar output as shown above.

Now we can work again without any issues when trying to install or update gems.


Technorati Tags: , ,

Posted in Development, Rails, Ruby, Software, Tools, XP | 36 Comments »

TextMate command to annotate your current ActiveRecord Model with the DB Schema

Posted by Marcus Wyatt on 18 March 2008

Edit: If you can’t wait until the end, here is the download link.

Who hasn’t used the Annotate Models plugin written by Dave Thomas, of Rails Pragmatic Studio fame? If you haven’t don’t fret… The plugin basically adds a comment block to the top of all of your model classes documenting the current database schema for the given model. I like to have the info in my model files to make it a little easier to work with models.

Annotated Models Plugin

The rails bundle within TextMate gives you a ‘Show DB Schema for current class’ command you can press to show a tool tip with the database schema (Control + Shift + Command + S). This works great, but I find the command sequence to long and the slight wait to see the schema info breaks my rhythm.

Show DB Schema for Current Class

To solve the problem I made a copy of the source files used by the command and modified it slightly to output the info as comments at the top of the file. Now I have nicely annotated model files. This is a real time saver.

Annotated Models Bundles

The bundle also contain the the Beautify command. This command adds automatic code formatting capability for your ruby code. I found the beautify command from Tim Burks. Cheers Tim…

You can download the bundle here.

Technorati Tags: , , , ,

Blogged from TextMate

Posted in Mac, OS X, Rails, Ruby, Software, TextMate | Leave a Comment »

Quick note: Ubuntu(gutsy) C compiler install and setup (glibc-devel)

Posted by Marcus Wyatt on 11 March 2008

UPDATE: Tim Haines notified me that you can install all the necessary tools with one command:

apt-get install build-essential

Thanks Tim, I’ve tried it on a clean VPS and it works a charm…

If you are busy setting up a new Ubuntu Linux server and you get the following error:

configure: error: no acceptable C compiler found in $PATH

when trying to run ./configure, then you need to install the gcc compiler (Yeah, I know… this is like a no brainer for you *nix guru’s).

Here is the command to install the gcc compiler on Ubuntu:

sudo apt-get install gcc

But now you get the following error:

error: checking for C compiler default output file name

Most results on on google search point you glibc-devel as the solution. But, alas… apt-get will report the following message when you try to install glibc-devel:

Couldn’t find package glibc-devel

So what to do? The correct Ubuntu package that is similar to the glibc-devel is libc6-dev. Below is the command to install the Ubuntu package:

sudo apt-get install libc6-dev

Happy compiling and installing…

Technorati Tags:

Posted in Software, Tools, Ubuntu | 1 Comment »

You can now build the source code in either VS2k5 or VS2k8

Posted by Marcus Wyatt on 11 March 2008

I’ve updated the source code to include some conditional compilation directives to support different Visual Studio IDE versions. So if you are still stuck in VS2005 land, you can now build the source and be able to take advantage of the new features that Owen Evans added.

These include the new attributes (Context, BeforeAll, BeforeEach, AfterAll, AfterEach) and new functionality like Collection.Contains#WithProperty. If you lucky to be using VS2008 you’ll have new functionality that allows you to pass lambda’s. For more information look at http://bgeek.net/2008/02/14/nspecify-rspec-well-closer-anyway/

Owen also added a new library called NSpecify.Framework.Extensions. This gives you some extension methods that you can use to specify your expectations directly on the object under test.

i.e. newDeveloper.Surname.Must().Equal(“Evans”);

Nice hey!

Posted in BDD, Development, OO, Software, TDD, Tools | Tagged: , , | Leave a Comment »

Ruby, Rails, TextMate, JavaScript, Mac OSX, Subversion

Posted by Marcus Wyatt on 15 February 2008







Technorati Tags: , , , , ,

Posted in JavaScript, Mac, OS X, Rails, Ruby, Software, Subversion, TextMate | Leave a Comment »

Friendly url’s in my rails application within minutes

Posted by Marcus Wyatt on 3 November 2007

To get search engine friendly urls in my rails application, all I had to do is the following 5 steps:

  1. Install the acts_as_urlnameable plugin using one of the following command:
    script/plugin install http://code.helicoid.net/svn/rails/plugins/acts_as_urlnameable/

    or if you’re using svn for your project, install with -x:

    script/plugin install -x http://code.helicoid.net/svn/rails/plugins/acts_as_urlnameable/

    or alternatively you could use piston.

  2. Next you need to add the call to acts_as_urlnameable to your model class:
    class Advert < ActiveRecord::Base
    acts_as_urlnameable :title
  3. Now we need to add the migration for the urlnames table where we’ll store our new url names:
    class Urlnames < ActiveRecord::Migration  def self.up
    create_table :urlnames do |t|
    t.string  :nameable_type
    t.integer :nameable_id
    t.string  :name
    enddef self.down
    drop_table :urlnames
  4. Next we need to override the to_param method in the model class, this will allow us to control what rails use in the urls:
    def to_param
  5. Lastly, we need to update the ActiveRecord.find(params[:id]) calls to use the acts_as_urlnameable find_by_url method:
    # GET /adverts/1
    # GET /adverts/1.xml
    def show
    @advert = Advert.find_by_urlname(params[:id])
    respond_to do |format|

And there you have it, friendly urls…

Normally your show url for your model would look as follows (if you’re using RESTfull design)


but now the url looks pretty….


There is much more you can do with the acts_as_urlnameable plugin, but I’d suggest you read the README file that does a good job of explaining how to use the plugin.

There are also other plugins you can use for friendly urls, here is a list of other plugins:

Powered by ScribeFire.

Posted in Rails, Rails Plugins, Software | 1 Comment »

Links for 1 November 2007 (Rails, JavaScript, HTML, Photoshop, CSS, Microformats, Macs, Freelancing)

Posted by Marcus Wyatt on 1 November 2007









Technorati Tags: , , , , , , ,

Powered by ScribeFire.

Posted in CSS, Development, JavaScript, RoR, Software | 2 Comments »

SourceForge 2007 Community Choice Awards

Posted by Marcus Wyatt on 21 June 2007

The 2007 Community Choice Awards is open for voting, so if you like the NSpecify framework then please vote for the project.

Thanks in advance for anyone voting.

Posted in Software | Leave a Comment »

Ruby in Steel Goodness

Posted by Marcus Wyatt on 20 June 2007

I’ve had a play with Ruby in Steel for Visual Studio 2005 when Sapphire Steel released the first Developer edition about a year ago. The first version on my system was clunky and painfully slow. The Ruby intellisense was slow and overall the experience was not great.

Well, why would you tell this to me know?

Because, earlier this week my eye caught a post about Visual Ruby in my aggregator. So I browsed over to the post and then got reminded about Ruby in Steel. So I decided to give it another try. Wow, what an improvement.

The debugging features are just brilliant. So seamless, you would think you’re working within a language like C#.

The intellisense is crisp and rdoc information is displayed where available:


The following Intellisense features for Ruby source files are implemented:

  • Member Completion Lists
  • Keyword Completion Lists
  • Variable Completion Lists
  • Quick Info Tooltips
  • Parameter Info Tooltips

You also have the Snippets features of visual studio for template functionality.


Another cool feature is the Ruby Explorer which is a class browsing tool which can be used to view an alphabetical outline of Ruby classes and methods.


All in all I’m really impressed by the progress the tool made since the version 1.0 release a couple of months ago. I’m seriously considering maybe to invest in a license for the tool. But I think they should seriously consider the freelance developer out there. When ReSharper announced their personal license I was really excited about the move and yes, I did buy a personal license. Hopefully the Sapphire Steel guys would consider something similar…

If you are a  .NET developer for food and a budding RoR developer for fun and don’t have that flash MacBook Pro yet. Then maybe Ruby in Steel is just what you’d need.

del.icio.us Tags: , , ,

Posted in Development, RoR, Software | Leave a Comment »