• About me
  • Archives
  • Categories
  • Web pages (specifically Google Maps) won’t load on Mac OS X

    2010 - 04.12

    I’ve been really happy with my iMac since I bought it 10 months ago, but one thing has been bothering immensely: the fact that periodically any browser under Mac OS X (Snow Leopard) would stop loading web pages and would just hang forever on trying to load all items on a page. In Google maps this was even happening almost always. And it drove me mad. Especially, since it was hard to find anyone with the same problem, let alone a solution. Until I found this thread. I thought I’d share the solution with you…

    What it comes down to is that apparently Mac OS X and “Stateful Package inspection (SPI)” or “Deep Package inspection (DPI)” on my router’s firewall did not play nice together. The simple solution to this was to turn the option “SPI and Anti-DoS firewall protection” off. However, it is a bit of a shame to turn off this enhanced feature entirely. The other option is to change the value of the criterium called “Maximum incomplete TCP/UDP sessions number from same host”. In my case this was set to 10. In the thread mentioned above a value of 20 was proposed. I set it to 30 (just to be sure ;) ) and sure enough: Google Maps worked instantly and very fast! I have yet to verify that the periodic refusals to load webpages have gone away as well, but so far I’m really hopeful!

    Kanban, pull and the need for backward story boards

    2010 - 03.01

    Introduction

    Last week I attended a meetup of Agile Holland, which was all about Kanban-style software development. An interesting presentation about the application of Kanban at a large Dutch insurance company got me thinking about the way they interpreted and visualized the concept of “pull” in their story boards. It has lead me to believe that the correct visualization of pull actually requires us to depict our story boards backward.

    Kanban

    Kanban is a Japanese word that is used in lean manufacturing to represent a signaling card. These are cards that are used in lean production systems, that indicate the need for an item. E.g. a customers buys the last monitor X from a store. The salesman takes the monitor from the stockroom and puts a Kanban in its place. This card is then picked up by the replenisher, who starts the ordering process for a new monitor at the central warehouse. The central warehouse delivers one or more new monitors X and if its own stock runs out, Kanbans are used to signal that and trigger the process to the manufacturer, etc. The whole idea behind this mechanism, is that items are only moved and produced, when there is actual demand for them in the supply chain. This creates a “pull” mechanism, instead of traditional “push” mechanism, which mass production is known for.

    Software development and story boards

    In software development, traditionally, a lot of features are thought up in the beginning of the process and are pushed in bulk into the software development process. The most extreme form of this is the waterfall software development approach. Luckily, agile principles have lead to much better software development life cycles, like Scrum. In Scrum, story boards, like the one depicted below, are used to track progress of individual items (features or user stories). Items move from left to right when they are being worked on. But there is actually nothing really stopping a Scrum team from moving the items in bulk from left to right, which is often considered to be a “push” mechanism.

    I say “often”, because the essence of this post is that it actually isn’t a “push” mechanism. But before I go into that, let me talk a little more about last week’s presentation. They presented an enhanced version of their story board: Kanban-style. The core idea is that you want to limit the team’s freedom to push everything through the process in bulk, but instead focus on creating flow, by limiting the number of items that can be simultaneously in one phase of the process, e.g. like so:

    This story board restricts the number of items allowed in the “planned” phase to 6 and in the “in progress” phase to 3. Now, only when one of the three items move from “in progress” to “done”, is a team member allowed to move one of the “planned” items to “in progress” and start working on it. If that means that a team member finds himself stuck because he can’t start working on a new item, he is forced to help other team members to get items to “done”. This focuses the whole team on getting things done.

    The visualization problem

    The problem I found in last week’s presentation was with the visualization of “pull” in the story board picture (side note: the actual story board presented had a few more phases, but that does not matter for this argument). Here’s the arrow that they drew to show how pull works:

    It was argued that a freed up space in one phase on the right side leads to the pull of an item from the phase to its left. This then leads to an overall pull from right to left. But if you go back to the parallel of lean manufacturing, then this is not the actual pull that this at the core of this process. The actual core pull is established by the fact that the development process is only triggered by customer feature requests instead of internal assumptions about what the customer needs. Note that this is also the core idea behind Scrum, and therefore a Scrum story board represents a pull system as much as a Kanban story board.

    Now, for almost all readers in the western world, push is most naturally depicted as something moving from left to right. Thus pull feels like it should be originated from the right side of a picture. In that case, the visualization of a pull-based software development process would actually need to look like this:

    So for software development professionals in the western world, I would argue that Kanban-style story boards would benefit from a backward visualization, if the characteristic of pull is to be emphasized explicitly.

    Mac OS X Home/End keybindings in Terminal

    2010 - 01.28

    I recently got an extended keyboard for my Mac (running Mac OS X 10.6, Snow Leopard). I just couldn’t do without the home, end, pgup and pgdown keys. It was fairly easy to find how to correctly bind these keys in all apps. But in the bash Terminal window is was not so straight forward. All the posts I could find suggested to open the Terminal>Preferences>Settings>Keyboard and set the the following bindings:

    • home \033[1~
    • end \033[4~

    However, these don’t work in the bash shell. Fortunately, after searching yet a bit more, I found the once that do:

    • home \033OH
    • end \033OF

    Wake up media server on when client resumes from standby

    2009 - 12.15

    Introduction

    A little bit more about my pet project: my media server and client (home theater) pc. One thing I struggled with the last couple of days was how I could wake my media server (running Windows XP) out of its standby sleep when I manually wake up a client pc (running Windows Vista). After all, all media is on the server, so there’s not much use in starting up the client if the server is still in a deep sleep.

    Wake on lan

    Waking up the server is a rather trivial task. The server motherboard supports “wake on lan”, so all I have to do is send a “wake up” signal to the server’s network card. There are several simple command line programs out there that can send that signal, like the one on Depicus and the one on Matcode. The latter program is the simplest and it works beautifully when you start it directly from your client pc.

    Timing it

    Now the trick is in timing the “wake on lan” right. There are several programs that allow you to run a program when a machine resumes. MP Standby Handler seemed to fit the bill perfectly. But it didn’t work! Well, it did: the log showed that the “wake on lan” program was executed, but the server did not wake up. So I tried a bunch of other programs I could find, but none of them worked. Aaarrrggghhh!!!

    Good old Windows task scheduler

    Then I found this post by Pixelated suggesting to use the Windows Task Scheduler. I never really paid attention to the Vista task scheduler, but I found that it is a far more advanced scheduler than the XP one. Pixelated suggested to add a task that would be triggered by a system event that fires when the machine resumes. This is the event with source Microsoft-Windows-Power-Troubleshooter and an event ID of 1. So I tried that. The program ran, but still the server didn’t wake up. I inspected the system event logs and I noticed the tcpip events in the same log at a later time. It then occurred to me: the network isn’t ready right after the resume event! I did have a feeling that might be a problem, so I tried to account for that in my experiments with MP Standby Handler, by adding a 10 second delay to the “wake on lan” execution after the resume event. But from the system logs I found that 10 seconds was too short. It takes my machine 19 seconds to re-establish its network connection. Even with a fixed IP address and a gigabit network. So I added a 25 second delay to the task execution and sure enough: everything worked like a charm. The server would wake up 25 seconds after the client woke up.

    Of course, 25 seconds is a bit of an arbitrary broad margin and an awkward construction: will it always take less than 25 seconds for the network to become available? Why not just send the “wake on lan” signal immediately after the network connection is established? Easy enough: all I had to do was change the task trigger to work on a system event from source tcpip with event ID 4201. I tested it and… it didn’t work! Apparently sending the “wake on lan” signal immediately on this event was a tad too soon. Adding a 1 second delay solved it all!

    Conclusion

    So there you go: you want to wake up a network device when your Vista (and presumable Windows 7) machine resumes from standby? Send a “wake on lan” signal to the device using the task scheduler, where the task is triggered 1 second after the system event from source tcpip with event ID 4201 occurs.

    I’m so glad this works now!

    So it was time!

    2009 - 12.01

    Time to migrate my http://thinkarchitecture.blogspot.com to my own domain. What took me so long? Well… the hassle of setting this stuff up, I guess. It’s like those creaking doors at the carpenter’s home.

    Anyway, I’m gonna update this slowly in the near future. Meanwhile, feel free to drop me a line or follow me on Twitter @plindelauf.

    That’s it! I’m going practical with my mediaserver

    2009 - 11.26

    I’ve been wanting to get a media- and backup server in place for quite some time now. So I finally decided to buy all components for a low-power, high capacity server: AMD Athlon X2 240, MSI 760GTM-P33, 3x Western Digital Caviar Green 1.5TB data drives, 1x Western Digital Caviar Green 640GB system drives, etc. All that for the following primary needs:

    1. to store all my media and other backups safely (=redundant)
    2. to it as a TV server, based on my FloppyDTV DVB-C card (with firewire connection)

    Deciding on the setup

    Redundant storage

    Ok. Problem 1: redundant storage. Well, this cries out for RAID: automatic redundancy, setup once, run forever. RAID-1 would be an option, but it’s a bit of wasted space, if you have RAID-5. And I don’t need blazing fast file access, since the network will always be the bottleneck in my setup. RAID-5 it is then.

    Now we have 2 options: hardware of software RAID. The problem with hardware RAID is that the RAID controller is your single-point-of-failure. If that fails, you can say bye bye to your data, no matter how much redundancy you baked in. So software RAID is my tool of choice. Also from a price point of view. And again: I don’t care for the slower disk access.

    What runs software RAID? Well, Linux-like systems do through mdadm. Windows Server does too. And you can hack Windows XP to do so, but I’m not to comfortable with using undocument features for this. So Windows Server or Linux it is. Great! On to the next requirement.

    TV Server

    I’ve been using MediaPortal on Windows of a while on a stand-alone pc. Great software, but not overly stable. This I large contribute to Windows Vista. So the thought of moving over to Linux with XBMC is very compelling. But, granted, MediaPortal has a very easy to setup TV Server, so that is a good option. What is there on the Linux side? In short: MythTV, VDR and TvHeadend. Enough choice. But I decided to try the MediaPortal route first anyway, since that would keep me in the Windows realm and I wasn’t all that proficient in Linux.

    Getting going

    Experiment 1: Windows Server 2003

    So, the MediaPortal route = Windows. Software RAID5 = Server. So the choice was Windows Server. 2003, to be exact, since I still had a license lying around. I installed everything and then the first test: would the Windows XP drivers for my FloppyDTV card work on Windows Server 2003. Answer: no! End of experiment 1.

    Experiment 2: Ubuntu

    So, experiment 1 killed the Windows route for that moment. On to the next experiment: Ubuntu with –what seemed to me the most mature TV server option- MythTV. So I installed MythBuntu 9.10. Quite smooth. Got RAID5 setup with some trouble, since one of my new drives appeared to be defective. That caused some headaches, but in the end, all ran well. So… the redundant storage part was filled in nicely. Now for the TV server…

    I started configuring the MythTV backend and… boy oh boy… exactly 1 channel was working out of the box. Well… it did show up double on my screen. All other channels I got a “partial lock” message and no video whatsoever. Furthermore, the channel switching was terribly slow. It was actually quite clear: MythTV wasn’t going to cut it for me.

    So what other options are there? VDR is proclaimed to be a good option. But I challenge you to try to find decent documentation for that! Probably the best source is years worth of forum posts on the German (!) VDR forum. Not my idea of fun. Really: I have better things to do than to guess how to configure all parameters by reading endless forum posts. And then the VDR website only lists VDR 1.6.0, whereas I found that the actual developers were already up to 1.7.9. What’s up? This was simply too painful an experience, and I wasn’t hopeful I was going to be happy with the whole solution if I’d get it running, given the partial integration with XBMC. End of VDR.

    Soooo… TVHeadend. What a breeze this app was at first sight. It has an actual decent user interface to configure it. And documentation too! Woohoo! How promising. Well, it’s been three nights now that I have tried to complete the scanning for TV channels. Three nights. And I still don’t have a working set of channels. Three nights. Again: not my idea of fun. And then there’s still the reports in the forum, that this is very promising, but still not really ready as a full TV server solution in combination with XBMC.

    This was the point where I started to think: my time’s too valuable. Not anymore. It ends here. If I were 15, I would probably still want to go on for weeks, but I got better things to do. STOP THIS NONSENSE!

    Idea 3: MediaPortal TV server in a Windows XP Pro VM on Ubuntu host

    No virtual machine supports firewire. Dead-end idea.

    Idea 4: Windows Pro XP host with Ubuntu VM

    Interesting. Some people seem to have been happy with this construct. The linked post got lead me to find that RAID-5 has some flaws and that choosing a ZFS file system under OpenSolaris (instead of Ubuntu) and going for RAID-Z, would actually be a more robust solution.

    But frankly… I don’t know. I probably want to power-up and power-down the server automatically quite a bit to save on the electric bill. And then having a host system decide for a “mission critical” guest system when that would be powering would be a good idea, doesn’t feel right and stable to me. And imagine stuff goes wrong here and the RAID-Z array gets screwed up: then everything is “RAID-Z encoded” and I can never get to my data just by accessing one drive.

    And I’d have to dive into OpenSolaris again. And in the configuration tools for RAID-Z. I was already fed up with these experiments after experiment 2, so isn’t this a route that I’m going to regret pretty soon anyway? I got a feeling it is. What remains?

    Final idea 5: Windows XP Pro with a soft-backup solution

    Ok, so RAID-5, RAID-Z all have their own magic way with the data and if they get screwed up, all data is screwed up. Maybe just a simple mirroring isn’t a terrible idea anyway. Ok, it’s a bit wasteful, but I’d rather spend an extra € 90 on a 1,5TB drive then many more nights of administrative headache.

    RAID-1 then seems cool, but I thought I’d read up a bit on the possible problems. And fairly soon, it turns out that RAID-1 can be a nasty sucker too. So forget it.

    I still have a license for the SyncBackSE file-backup solution. Why not go for that? Keep it simple! Simply have one explicit data drive and one explicit mirror and have SyncBack do all the copying. I considered the Pro version for its S.M.A.R.T. monitoring facility, but DiskCheckup gives me that for free. Another benefit of a file-based mirroring mechanism, is that I can do this on partition level instead of drive level.

    Here’s what I’m now thinking of doing:

    • 2 x 1,5TB drives: media and other data, each being a soft mirror of one another
    • 1 x 1TB partition on the 1,5TB drive: TimeMachine backup for my iMac. Not mirrored, since the iMac is essentially the mirror (yes, I know, I can loose history, but that’s not too relevant)
    • 1 x 0,5TB partition on the 1,5TB drive + 1 x 0,5 TB partition on the 640GB drive: more media and data, each being a soft mirror of one another

    This gets me:

    • roughly the same storage space as with RAID-5: 3TB
    • a non-mirrored TimeMachine backup of my iMac: not an issue
    • partitions that I can always access natively, without any RAID-like magic involved

    Conclusion

    That is it then. I’m getting rid of Ubuntu and stuff tonight. I’m done. Back to Windows and MediaPortal it is. I’m already looking forward to spending a night without server setup headaches to worry about!

    Starting on a cross-platform desktop application

    2009 - 07.30

    It’s been while since I wrote my last desktop application. Recent inspiration got me fired up again to try and write a new one. I have envisioned that cross platform should be a key feature. So what is there on the market today which would allow me to do that?

    Choosing a framework

    For starters, I want the application to have a “modern” user interface. So an up to par UI framework is mandatory. Immediately that brings choices down to:

    1. Microsoft Silverlight or WPF
    2. Adobe Flex
    3. JavaFX

    The first one is available cross-platform through the use of Mono. However, in that case I would be stuck with Silverlight, since WPF is not (yet) supported by Mono. This automatically limits the capabilities of the app in general, like limited (or no?) database support. And I need the app to have a local database. So that’s it for the Microsoft road.

    Flex looks like a very good UI framework, but I want my UI layer to be as thin as possible and have all my business logic written in a decent programming language and framework. Especially since I’m considering having some of this code running on a server as well, Flex is basically out the door.

    That leaves me with the latter: JavaFX. The UI framework is the newest of the bunch, but it seems nice enough to meet my needs. Now the big plus is that it directly ties into Java, which is obviously a very proven language and framework, that will satisfy all of my business-logic coding and integration needs.

    Object-relational mapping and dependency injection

    So JavaFX it is. Java classes (POJO-style) for my business logic. I’m a big fan of Domain Driven Design, so I’m gonna hook up a database with an ORM: Hibernate (I’ve been using NHibernate a lot in the recent past, so the shallow learning curve is a major plus). JavaDB is a lightweight database, which might just suit my needs.

    And then I need to modularize my application for (1) flexibility and (2) testability. I believe Spring is the de facto standard as an IOC container on the Java platform for some time now, but it is infamous for its XML-rich configuration style. That I don’t like at all. Google has been working on what seems a great alternative: Guice. Lightweight, fast, easy configurable (in code) and proven by extensive of Google themselves. Sounds like a winner to me!

    Here we go!

    Right. Those are the basics for now. I’ll try to post my findings on using this stack regularly. Any suggestions, feedback, pointers are always more than welcome. For now: wish me a safe journey! :)

    Querying with Castle ActiveRecord

    2008 - 10.07

    We recently started a project where I decided to use Castle’s ActiveRecord. On previous projects I had used NHibernate with a repository pattern, but for multiple reasons the active record pattern is more appropriate in this project.

    One of the lowest hanging fruits of ActiveRecord is its abstraction from the NHibernate mapping files. Combine that with inheriting your domain objects from the ActiveRecordBase class and in no time you’re good to go with an object-oriented domain model that can easily be persisted to a relational database.

    So far so good. But not too long into the project, you’ll find that need to start querying your domain model and then what do you do? Unfortunately, the query-side of Castle’s ActiveRecord is rather poorly documented. It’s kind of limited to this one page. For me that wasn’t enough to grasp the ideas behind it or give me a good feeling of what can be achieved with it. For example: there’s an ActiveRecordQuery class. What do I do with it? Do I inherit from it, like with ActiveRecordBase. And if so, what do I get? And what part is Castle specific and what part NHibernate specific?

    Some sniffing on the internet did not reveal a whole lot more and that’s why I decided to open up the source code itself and find out for myself. Here I my findings for the most recent framework version at the time of this writing: 1.0.3 (RC3).

    What does it add?

    The query-side of Castle is a bit different from the basic active record side of the framework. On the latter side, things mainly evolve around the benefits you get from the ActiveRecordBase class by inheriting from it. There is no such thing for the query-side, which is actually a rather thin wrapper around the default NHibernate query functionality. It’s almost so thin, that you wonder why you should actually bother with the query-side of ActiveRecord. And there seems to be only one real compelling reason: the fact that it abstracts away from the NHibernate session. After all, the ActiveRecordBase hides the session as well and you wouldn’t really want to have to worry about an NHibernate session just to get your queries to work.

    So what does the query-side of the framework offer? Well, actually a number of helper classes that aid in composing the right type of NHibernate query. It simply works as follows:

    1. instantiate a query helper object that suits the type of query you want to perform
    2. set all the necessary query properties on the query helper object
    3. get the query result by executing the query

    It’s in the latter case that we see that there are two generations of query helper classes in the framework:

    Generation 1 classes whose instances need to be passed into an ExecuteQuery() operation on an instance of an ActiveRecordBase child class; these are:

    • HQLBasedQuery
    • SimpleQuery
    • ScalarQuery
    • ActiveRecordCriteriaQuery
    • CountQuery

    Generation 2 classes that have their own public Execute() operation; these are:

    • SimpleQuery<T>
    • ScalarQuery<T>
    • ActiveRecordMultiQuery
    • ProjectionQuery<T,R>
    • ProjectionQuery<T>
    • ScalarProjectionQuery<T,R>

    I’m not sure why the two generations exist, but I’m guessing this is due to architectural evolution.

    The basics

    First a quick tour of the basics.

    ActiveRecordBaseQuery

    IActiveRecordQuery

    The mother of all query helper objects is the IActiveRecordQuery interface class. Primarily this establishes that each query can be executed as long as you pass in a NHibernate session object. This is done through the operation Execute(ISession).

    Additionally it offers the RootType property, which returns the target type of the query.

    IActiveRecordQuery<T>

    Inherits from IActiveRecordQuery and is identical, with the exception that the Execute operation returns type T instead of an anonymous object.

    ActiveRecordBaseQuery

    This abstract class reroutes the IActiveRecordQuery’s Execute(ISession) operation to an InternalExecute(ISession) operation, which only ActiveRecord classes can get at. Furthermore it offers the hook to a query logger. Anyway, there’s not so much interesting things going on in this class. Things start to get interesting with the first real query helper class you can actually use: the HQLBasedQuery.

    HQLBasedQuery

    HQLBasedQuery

    This is the helper class helps you to compose an NHibernate HQL query. Basically, an HQL query consists of a number of elements:

    • The root type
    • The actual query string
    • The list of parameters passed into the query string
    • A specification of the result range (start element and number of elements to be returned)

    The HQLBasedQuery offers several constructors to set up your query with one simple statement. Part of these constructors in a QueryLanguage parameter, which allows you to specify it a query is an HQL (default) or SQL query.

    The constructors allow to pass in parameters in a sequential fashion. However, NHibernate also supports named parameters. These name-value pairs need to be set separately with the SetParameter or SetParameterList operations.

    So what does this class offer you? Well, next to the abstraction from the ISession, it offers you a different query building syntax. Here’s a quick comparison.

    Using the HQLBasedQuery:

    HqlBasedQuery q = new HqlBasedQuery(typeof(Cat), "from Cat where Name like ?", "Fritz%");
    Object result = Cat.ExecuteQuery(q);
    

    Using NHibernate:

    ISession session = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession( typeof(Cat));
    Object result = session.CreateQuery("from Cat where Name like ?").SetParameter(0, "Fritz%").List();
    

    As you can see, the hardest part in the NHibernate example is getting to the session object. The actual query execution is actually not all that different.

    SimpleQuery and SimpleQuery<T>

    clip_image004

    The SimpleQuery class does exactly the same as the HQLBasedQuery, with the exception that the Execute(ISession) operation is now explicitly cast to a return type defined in the constructor or – if a return type is not specified – to root type.

    With SimpleQuery<T> the exact same thing can be established as with SimpleQuery, only the return type is now T. Firthermore, since this is a generation 2 class it offers its own public Execute() operation. Great! So from .NET 2.0 and up, I’d use this over the non-generic type anytime.

    ScalarQuery and ScalarQuery<T>

    clip_image006

    Just like SimpleQuery, this class does exactly the same as HQLBasedQuery, with the exception that it returns a single instance by applying the UniqueResult() operation on the query result. Strangely enough, there is no constructor that allows you to specify a return type, like we’ve seen for SimpleQuery. Then again these are .NET 2.0 and up days an so…

    … we’d probably rather like to use ScalarQuery<T>, since it does return a strongly typed result and offers its own Execute() operation.

    ActiveRecordCriteriaQuery

    clip_image008

    Strangely enough, this class inherits from HQLBasedQuery instead of ActiveRecordBaseQuery. It accepts a criteria array (each of type ICriterion) or a DetachedCriteria structure. No additional query modifiers (like parameters or result ranges) are supported in this class: if you need them, you should make them part of the passed in criteria.

    There is one benefit this class gains from inheriting form HQLBasedQuery: if no criteria are passed in at all, an empty HQL query is executed upon execution, thus retuning all objects of the target type.

    In essence this object gives you a slightly different syntax for defining and executing criteria-based queries. Here’s a syntax comparison.

    Using the ActiveRecordCriteriaQuery:

    ICriterion[] criteria = { Expression.Like("Name", "Fritz%") };
    ActiveRecordCriteriaQuery q = new ActiveRecordCriteriaQuery( typeof(Cat), criteria );
    Object result = Cat.ExecuteQuery(q);
    

    Using NHibernate:

    ISession session = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession( typeof(Cat));
    Object result = session.CreateCriteria(typeof(Cat)).Add( Expression.Like("Name", "Fritz%")).List();
    

    Hmmm… I’m not sure why I’d want to use the ActiveRecordCriteriaQuery instead of the NHibernate syntax. The latter seems less verbose.

    And then I guess I would have expected an ActiveRecordCriteriaQuery<T> (along with its own Execute() operation), but unfortunately this does not exists. I’m not sure why.

    CountQuery

    clip_image010

    This class creates a special HQLBasedQuery, namely one that executes a COUNT query. There are three constructors that allow us to specify the COUNT selection criteria:

    • One with a HQL string based filter and accompanying optional parameters. The filter string needs to be the part that you’ll find in the WHERE clause of the HQL query “SELECT COUNT(*) FROM TargetType WHERE <filter>“.
    • One with a set of NHibernate criteria of type ICriterion
    • One with a set of NHibernate criteria of type DetachedCritera
    • One without any selection criteria, which simply counts all the instances of the passed in target type.

    When executed, the query returns an int32.

    ActiveRecordMultiQuery

    clip_image012

    NHibernate offers MultiQuery functionality, which allows you to compile multiple queries and fire them off to the server in one call. The ActiveRecordMultiQuery is there to allow you to compose such a MultiQuery using ActiveRecodBaseQuery child classes. Note, however, that only non-criteria based queries are supported. If you use an ActiveRecordCriteriaQuery or a CountQuery, the ActiveRecordMultiQuery will throw an exception upon execution.

    This class is actually a bit shaky in this version of the Castle framework. As you can see the Execite and Enumerate operations expose an NHibernate session unlike all the other classes. Furthermore, the Enumerate operation is not implemented and will throw an exception if you try to execute it. Personally I think this class it the weakest link in the bunch.

    ProjectionQuery<ARType, TResultItem>

    clip_image014

    The projection query is the latest fashion in the framework and the result of great work by Ayende Rahien. He has taken some time to demonstrate the features of this query in a blog post or two.

    The “latest fashion” exposes itself by the fact that:

    • better use of generics: both he root type and the return type are specified as generics
    • the use of the pipes and filters pattern for the SetRange operation, which allows you to apply a SetRange to the ProjectionQuery without altering the return type
    • the public Execute operation

    Actually, with this new fashion, one could even consider this class to be the first of an even newer third generation of query helper classes in the framework. What does strike me as odd is the exposure of NHibernate’s session in the Enumerate operation.

    Upon execution of the query, an internal NHibernate criteria object is instantiated to which:

    1. the list of projections with which the class is initialized are applied using the SetProjection() operation
    2. the SetResultTransformer is applied to transform the result to the TRseultItem type
    3. the array of NHibernate Order expressions is applied, using the AddOrder for each entry. This allows you to indicate by which properties the result should be ordered.

    ProjectionQuery<ARType>

    Is exactly the same as ProjectionQuery, with the exception that the result is an object array instead of an IList<TResultItem>.

    ScalarProjectionQuery<ARType, TResult>

    Is identical to ProjectionQuery, with the exception that the result is a single TResultItem instead of an IList<TResultItem>, by applying the UniqueResult<TResult>() operation to the query result.

    Conclusion

    I think the exploration of the query-side of Castle’s ActiveRecord framework was well worth the effort to get a grasp of what its all about. I was a bit surprised to find that it is actually as thin as it is. Which leads me to question if it worth the hassle to learn the new query syntax imposed upon you by the classes’ API’s. This is especially bothersome, since:

    1. the API’s are poorly documented
    2. the API’s are inconsistent, not only across the generations, but also within the generations

    The first issue I hope to have solved somewhat with this blog post, by giving some insight of how these classes relate to the NHibernate constructs, that are far better documented. The latter is hard to solve. The most obvious reason for this being backward compatibility.

    These are all compelling reasons for me to consider sticking with basic NHibernate queries. I’m thinking it is worth the extra overhead of retrieving the right NHibernate session in order to execute a query. This could easily be established by creating an ActiveRecordHelper-like class with a GetSession(RootType) operation. Once this is implemented, the query is actually rather straightforward and uses regualr NHibernate syntax, e.g.:

    Object result = ActiveRecordHelper.GetSession(Cat).CreateCriteria( typeof(Cat)).Add(Expression.Like("Name", "Fritz%")).List();
    

    Anyway, I’m sure I’ve overlooked a thing or two, so your thoughts and comments on this are more than welcome!

    New money(.cs)

    2008 - 08.21

    Version 2

    So, right after my first post, I quickly discovered I had a bit of polishing up to do of my first money class. Thanks to a few pointers of “fellow inventor” Codekaizen, I read up on the theory of doing arithmetic with money and I made a few changes to the first implementations. Nothing drastic, but significant enough for me to publish this new version.

    Arithmetic

    On the arithmetic front, the follow I’ve reworked the division and multiplication operations. Outcomes are not rounded to the number of significant decimal digits anymore. The rounding is now left to the user. For this I’ve introduced the new Round() operation. When requesting a string representation of a money object, the amount is rounded automatically.

    Furthermore, I reconsidered the use of Decimal (being a floating point type) for the representation of the actual amount. I decided to stick with it. There are a couple of things to note in that context:

    1. A Decimal can hold up to (and even a bit more than) 28 digits => this is more than enough for 98% or more of the .NET applications.
    2. It maps cleanly to decimal types supported by most important databases, thus making table inspection a breeze.
    3. One should be aware of how the floating point behaviour of the Decimal type works. Simply put: a decimal value is a sign bit, 1 to 28 digits and a number indicating the position of the decimal separator.
    4. One should also be aware that doing arithmetic with numbers that are on the extreme ends of he scale can cause loss of precision. E.g. adding 10 to 10^-28 (the smallest positive number) would require 29 digits to represent the outcome correctly, but since we only have 28 to spare, the least significant digit will be left out of the result. In that case, the result is 10.
    5. The “simple alternative” to using a Decimal is using two Int64’s: one for the part in front of the decimal separator and one for the part behind it. However, that still gives us a maximum precision of 28 digits and it maps rather poorly to the database. I’d say that if one wants a real alternative to a Decimal, one should go all the way and support the extensive requirements specified in this article by IBM, which indicates a theoretical need for a precision of 2191 digits. We would need a .NET equivalent of Java’s BigDecimal for that.

    General refactoring

    There are three general refactorings I have done:

    1. The CurrencyRepository is now completely static
    2. I made the Money class a real “value object” by making the CurrencyCode and Amount properties read-only.
    3. I completed the list of type converters.

    Roundup

    That concludes version 2 of this Money class implementation. I’m planning on at least one more release, in which the currencies also contain the unicodes for the currency symbols. That should make displaying those “exotic” (excuse my blatant European perspective) currency symbols easier to display (e.g. in HTML).

    Download the C# Money implementation v2 here

    I hope this implementation is useful to some of you. I’m always delighted to hear your feedback.

    Making Money with C#

    2008 - 07.24

    Introduction

    So my next .NET project started and sure enough, there was the requirement again to support international customers. Now, most of the systems I work on have quite a bit of financial functionality in them and therefore the handling of money is an important aspect. I have found that most developers like to take the simple approach to handling money, supporting only a single currency by solely using decimal type to store an amount and not explicitly naming the currency. Instead the currency is first made explicit when it is presented on a user interface, adding a currency symbol as it is stored in the “active culture info” (which generally means: the server’s culture settings).

    I don’t know about you, but if some system administered some amount of my money, I would be very worried if it simply stored: 1,000,000. Especially if my money were in Euro and the system would be a web system running in the US. Chances are, the system’s implicit currency is USD and the current difference between USD 1,000,000 and EUR 1,000,000 is currently about USD 476,500, which is enough to give me quite big headache! ;)

    I think we can all agree that when there is a hint that our system might be confronted with cross-border business, it is a very good architectural practice to store money not simply as a number, but also with the appropriate unit. Martin Fowler has already suggested this long ago (1996) in his book Analysis Patterns, where he discussed the Money analysis pattern to be a specialized version of the Quantity analysis pattern. In his Patterns of Enterprise Application Architecture he revisits the Money pattern with several code samples. So the most ground breaking work has been done long ago already.

    What is there now?

    There are different angles to look at money representations:

    1. From an administrative point of view (as discussed above), recording and computing monetary amounts along with the correct currency;
    2. From a presentation point of view, describing the way a monetary value is displayed;
    3. From a geographical point of view, listing what currencies are used in what countries.

    In .NET, Microsoft has supplied us with facilities for the last two angles with the CultureInfo and NumberInfo classes. Amazingly, the first angle is completely ignored, even though that is what’s needed for solid financial business functionality.

    Despite of the work of people like Martin Fowler, it seems there are not too many people who care about the administration aspect of money in the .NET space. At least, that’s the feeling I get when I set out to search for C# Money implementations. That yields one fairly decent implementation by Jason Hunt. Unfortunately, Jason relies on the presentation-related CultureInfo class to store currency information. I think that it is unnecessarily complicated, since it forces me to instantiate “1,000 of that currency they use in the US” instead of instantiating “1,000 USD”.

    What do we need?

    As far as I can see now, we need to be able to do the following with a money representation:

    • Store monetary amounts as an amount together its currency code.
    • Get a string representation of the monetary amount, dependent on how the user is accustomed to see currencies and numbers. Note that this means that a even though USD is an American currency, a Dutch user would not expect to see the American formatting rules applied to a USD amount, but instead the Dutch formatting rules.

    The design

    Basic properties

    The basics of the Money class are straightforward: we need a property to hold the monetary amount and one to hold the currency of that amount.

    public sealed class Money : IEquatable<Money>, IComparable, IComparable<Money>
    {
        private CurrencyCodeKind _currencyCode;
    	private decimal _amount;
    

    The CurencyCodeKind type shown in the listing above is an enumeration. The names of the enumerated values are the ISO 4217 currency codes. This allows us to store any monetary amount, independent of culture or presentation standards. For the amount itself, we use a decimal type, generally regarded as best practice for storing monetary amounts. This can hold values from -10 Sextillion to 79 Sextillion (Sextillion = 10^15 Billion) (http://www.statman.info/conversions/number_scales.html), assuming we use a maximum of 3 significant decimal digits. In short: this is more than enough… even for Zimbabwe, that currently has bills up 100 Billion Zimbabwe Dollars!

    Here’s a snippet of the CurrencyCodeKind enumeration:

    public enum CurrencyCodeKind
    {
        AED = 784,
        AFN = 971,
        ALL = 8,
        AMD = 51,
        ANG = 532,
        ...
    }
    

    Note that for the indexing values, we use the related ISO 4217 numeric codes. The reason not to use the default incremental numbering scheme for this enumeration, is rather practical: when storing money objects to a relational database, the numeric value of the currency code will get stored. If we inspect a table with Money objects later, it is very convenient to have these ISO 4217 numeric codes show up instead of application-specific numbers.

    The same argument holds for the use of the decimal type to store the actual amount: Fowler has shown implementation examples just using (big) integers, which means that in order to know what the right amount is, you’ll always need the application to position the decimal separator correctly. I find that a little too brittle for information that’s that important, hence I choose to go with a decimal datatype that also has an exactly matching representation on database level.

    The inner workings

    When working with a Money object, we’ll eventually need to know more about its currency than just its ISO code. More specifically we’ll need to know:

    1. The number of significant decimal digits, needed for correct calculations and rounding
    2. The currency symbol for display purposes
    3. The rounding type, needed for rounding of calculation results (discussed later)
    4. The name of the currency (maybe not necessary, but still convenient

    I’ve created a Currency class to hold this information for a currency. Here are its properties:

    internal class Currency
    {
        public CurrencyCodeKind CurrencyCode { get; private set; }
        public string EnglishName { get; private set; }
        public string Symbol { get; private set; }
        public int SignificantDecimalDigits { get; private set; }
        public CurrencyRoundingKind RoundingType { get; private set; }
    

    These Currency class properties are vital for the logic in the Money class. Therefore it is convenient to have a Money object hold a reference to the Currency object that is represented by the Money object’s currency code. So let’s have some additional private properties on the Money class to achieve this:

    public sealed class Money : IEquatable<Money>, IComparable, IComparable<Money>
    {
        #region Properties
        public CurrencyCodeKind CurrencyCode { get; set; }
        public decimal Amount { get; set; }
        private Currency _currency;
        private CurrencyRepository _currencyRepository = new CurrencyRepository();
        private static int[] _cents = new int[] { 1, 10, 100, 1000 };
        #endregion
    

    In order to keep the CurrencyCode and _currency in sync, the currency object reference is set in all places where the currency code can be set, which is in de constructors:

    // Initialize a new money with an explicit currency code
    public Money(CurrencyCodeKind currencyCode, decimal amount)
    {
        if (_currencyRepository.Exists(currencyCode))
        {
            CurrencyCode = currencyCode;
            Amount = amount;
            _currency = _currencyRepository.Get(CurrencyCode);
        }
        else
        {
            throw new InvalidOperationException("Currency code unknown.");
        }
    }
    
    // Initialize a new money with the currency code
    // held in the passed in CultureInfo.
    public Money(CultureInfo cultureInfo, decimal amount)
    {
        CurrencyCodeKind currencyCode;
        try
        {
            currencyCode = (CurrencyCodeKind)Enum.Parse(typeof(CurrencyCodeKind), (new RegionInfo(cultureInfo.LCID)).ISOCurrencySymbol);
        }
        catch (Exception)
        {
            throw new InvalidOperationException("Currency code unknown.");
        }
        if (_currencyRepository.Exists(currencyCode))
        {
            CurrencyCode = currencyCode;
            Amount = amount;
            _currency = _currencyRepository.Get(CurrencyCode);
        }
        else
        {
            throw new InvalidOperationException("Currency code unknown.");
        }
    }
    
    	// Initialize a new money with the currency code of the
    // runtime enviroment's current regional settings.
    public Money(decimal amount)
    {
        CurrencyCodeKind currencyCode;
        try
        {
            currencyCode = (CurrencyCodeKind)Enum.Parse(typeof(CurrencyCodeKind), RegionInfo.CurrentRegion.ISOCurrencySymbol);
        }
        catch (Exception)
        {
            throw new InvalidOperationException("Currency code unknown.");
        }
        if (_currencyRepository.Exists(currencyCode))
        {
            CurrencyCode = currencyCode;
            Amount = amount;
            _currency = _currencyRepository.Get(CurrencyCode);
        }
        else
        {
            throw new InvalidOperationException("Currency code unknown.");
        }
    }
    

    As you can see, the constuctors use the _currencyRepository to find the currency object matching the current currency code. The currency repository is a singleton, being nothing more than a static in memory store of all possible currency objects. Here’s a snippet:

    internal class CurrencyRepository
    {
        // List of all currencies with their properties.
        static private Dictionary<CurrencyCodeKind, Currency> _currencyDictionary =
            new Dictionary<CurrencyCodeKind, Currency>()
            {
                {CurrencyCodeKind.AED, new Currency(CurrencyCodeKind.AED, "United Arab Emirates dirham", "¤", 2)},
                {CurrencyCodeKind.AFN, new Currency(CurrencyCodeKind.AFN, "Afghani", "¤", 2)},
                {CurrencyCodeKind.ALL, new Currency(CurrencyCodeKind.ALL, "Lek", "¤", 2)},
                {CurrencyCodeKind.AMD, new Currency(CurrencyCodeKind.AMD, "Armenian dram", "¤", 2)},
                {CurrencyCodeKind.ANG, new Currency(CurrencyCodeKind.ANG, "Netherlands Antillean guilder", "ƒ", 2)},
                ...
    

    The reasons all currency objects are hard coded are:

    1. the currency list hardly ever changes;
    2. when a new currency is introduced, it needs to be added to the CurrencyCodeKind enumeration anyway, thus requiring a new system build; it is only natural to then also update the hard coded currency object list;
    3. you don’t really want this core configuration of the way you handle money to be stored in an easy to corrupt/misuse configuration file.

    One additional thing to note is that I quickly found out that the default character set does not hold all currency symbols. Therefore a lot of currency symbols are represented by the generic currency sign. A future enhancement will be to add the Unicode of the symbol to the properties of the Currency class.

    Operators

    The implementation of most arithmetic operators are straightforward; here’s the >, >=, ==, <=, <, !=, +, and – operators:

    public static bool operator >(Money first, Money second)
    {
        AssertSameCurrency(first, second);
        return first.Amount > second.Amount;
    }
    
    public static bool operator >=(Money first, Money second)
    {
        AssertSameCurrency(first, second);
        return first.Amount >= second.Amount;
    }
    
    public static bool operator <=(Money first, Money second)
    {
        AssertSameCurrency(first, second);
        return first.Amount <= second.Amount;
    }
    
    public static bool operator <(Money first, Money second)
    {
        AssertSameCurrency(first, second);
        return first.Amount < second.Amount;
    }
    
    public static Money operator +(Money first, Money second)
    {
        AssertSameCurrency(first, second);
        return new Money(first.CurrencyCode, first.Amount + second.Amount);
    }
    
    public static Money operator -(Money first, Money second)
    {
        AssertSameCurrency(first, second);
        return new Money(first.CurrencyCode, first.Amount - second.Amount);
    }
    
    public static bool operator ==(Money first, Money second)
    {
        if (object.ReferenceEquals(first, second)) return true;
        if (object.ReferenceEquals(first, null) || object.ReferenceEquals(second, null)) return false;
        return (first.CurrencyCode == second.CurrencyCode && first.Amount == second.Amount);
    }
    
    public static bool operator !=(Money first, Money second)
    {
        return !first.Equals(second);
    }
    

    Where it starts getting tricky is with multiplication and division. This is because of the rounding that needs to take place when the result of the operation exceeds the number of significant decimal digits allowed for that currency. To tackle this, I’ve implemented the WithRoundedAmount() operation for both the * and / operators.

    public static Money operator *(Money money, decimal value)
    {
        if (money == null) throw new ArgumentNullException("money");
        return new Money(money.CurrencyCode, money.Amount * value).WithRoundedAmount();
    }
    
    public static Money operator /(Money money, decimal value)
    {
        if (money == null) throw new ArgumentNullException("money");
        return new Money(money.CurrencyCode, money.Amount / value).WithRoundedAmount();
    }
    
    internal Money WithRoundedAmount()
    {
        switch (_currency.RoundingType)
        {
            case CurrencyRoundingKind.Argentinian:
                decimal insignificantDecimals1 = Amount * CentFactor() - (long)Math.Truncate(Amount * CentFactor());
                if (insignificantDecimals1 < 0.3m)
                {
                    return this.WithTruncatedAmount();
                }
                else
                {
                    if (insignificantDecimals1 > 0.7m)
                    {
                        Amount = decimal.Round(Amount, _currency.SignificantDecimalDigits, MidpointRounding.AwayFromZero);
                        return this;
                    }
                    else
                    {
                        Amount = ((long)Math.Truncate(Amount * CentFactor()) + 0.5m) / CentFactor();
                        return this;
                    }
                }
            case CurrencyRoundingKind.Swiss:
                decimal insignificantDecimals2 = Amount * CentFactor() - (long)Math.Truncate(Amount * CentFactor());
                if (insignificantDecimals2 < 0.26m)
                {
                    return this.WithTruncatedAmount();
                }
                else
                {
                    if (insignificantDecimals2 > 0.75m)
                    {
                        Amount = decimal.Round(Amount, _currency.SignificantDecimalDigits, MidpointRounding.AwayFromZero);
                        return this;
                    }
                    else
                    {
                        Amount = ((long)Math.Truncate(Amount * CentFactor()) + 0.5m) / CentFactor();
                        return this;
                    }
                }
            default:
                Amount = decimal.Round(Amount, _currency.SignificantDecimalDigits, MidpointRounding.AwayFromZero);
                return this;
        }
    }
    

    As you can see, the WithRoundedAmount() is not as straightforward as expected, as is described in this source. The default (and much expected) behaviour for rounding is:

    • If the last digit is less than 5, drop it, otherwise,
    • If the last digit is equal to or above 5, add one to the previous digit and drop the last digit.

    Apparently, Argentina and Switzerland have alternate rounding schemes, as described in the above mentioned source. To accommodate for these, I have added a CurrencyRoundingKind enumeration to indicate when to use what rounding scheme.

    internal enum CurrencyRoundingKind
    {
        AwayFromZero,
        Swiss,
        Argentinian
    }
    

    For now, I’ve associated that scheme to the Argentinian and Swiss currencies, but I’m not sure if that’s entirely correct. In other words: do Argentina and Switzerland only apply these rounding schemes to their own currencies, or also to all foreign currencies they perform calculations on? For now, I choose to leave this alone, since I currently don’t need to accommodate for this in my projects. But if someone can enlighten me… by all means!

    Allocation

    With rounding comes loss of information. If you use the division operator to calculate how to divide $0.05 amongst 3 people, you’ll have $0.01 to give to each person. $0.02 is lost due to rounding. Everyone knows about those exploit stories of programmers in the early days who took advantage of this loss due to rounding. We’ve wizened up since then, and Fowler introduced an Allocate algorithm to take care of situations like this. It’s a simple algorithm that actually plays the “rings on a sticks” game:

    Say you have 5 rings and 3 sticks to divide them eenly over, you’ll get the following:

    MoneyAllocate

    With the Allocate algorithm, you’ll ask to Allocate $0.05 over 3 parts: (new Money(CurrencyCodeKind.USD, 0.05m)).Allocate(3). The result is an array with 3 elements, two of which contain $0.02 and one that contains $0.01.

    public Money[] Allocate(int n)
    {
        Money lowResult = new Money(CurrencyCode, Amount / n).WithTruncatedAmount();
        Money highResult = lowResult.Amount + new Money(this.CurrencyCode, 1.0m/CentFactor());
        Money[] results = new Money[n];
        int remainder = (int)((Amount * CentFactor()) % n);
        for (int i = 0; i < remainder; i++) results[i] = highResult;
        for (int i = remainder; i < n; i++) results[i] = lowResult;
        return results;
    }
    

    I’ve also included Fowler’s enhanced version of the Allocate algorithm, which allows to user to specify an array of allocation ratios, e.g. allocating $1 with a ratio of {2, 3, 3}, can result in an array with $0.25, $0.37 and $0.38. Note that I said can, because the algorithm does not assert how the division takes place exactly. It only asserts that:

    1. the remainder is evenly distributed over the parts
    2. the sum of the resulting amounts is equal to the divided amount.
    public Money[] Allocate(int[] ratios)
    {
        decimal total = 0m;
        for (int i = 0; i < ratios.Length; i++) total += ratios[i];
        Money remainder = this.Copy();
        Money[] results = new Money[ratios.Length];
        // First distribute the truncated amounts over all parts
        for (int i = 0; i < results.Length; i++) {
            results[i] = new Money(CurrencyCode, (this.Amount * ratios[i]) / total).WithTruncatedAmount();
            remainder.Subtract(results[i]);
        }
        // Now determine how many cents are left
        long centsLeftToDivide = (long)(remainder.Amount / (1.0m / CentFactor()));
        // Distribute those remaining cents over the different parts
        for (int i = 0; i < centsLeftToDivide; i++) {
            results[i].Add(new Money(this.CurrencyCode, 1.0m / CentFactor()));
        }
        return results;
    }
    

    So in order to apply “rounding safe divisions”, be sure to use the Allocate operation.

    Formatting for displaying

    Lastly, we’ll need some formatting on a Money object for it to present itself neatly to a user. This formatting is included in the 3 variants of the ToString() operation:

    1. with no parameters (generally not recommended); the number formatting rules are taken from the OS’ current culture info and the three letter currency code is used as the currency indicator;
    2. with a CultureInfo object as parameter (recommended); the number formatting rules are derived from the passed in CultureInfo object and the three letter currency code is used as the currency indicator;
    3. with a CultureInfo object as parameter and an indicator whether or not to use the currency symbol instead of the three letter currency code as currency indicator (equally recommended); the number formatting rules are derived from the passed in CultureInfo object.
    public string ToString()
    {
        return Amount.ToString("C", GetCurrencyFormatter(CultureInfo.CurrentCulture, false));
    }
    
    public string ToString(CultureInfo cultureInfo)
    {
        return Amount.ToString("C", GetCurrencyFormatter(cultureInfo, false));
    }
    
    public string ToString(CultureInfo cultureInfo, bool useSymbol)
    {
        return Amount.ToString("C", GetCurrencyFormatter(cultureInfo, useSymbol));
    }
    

    A central role is played by the GetCurrencyFormatter operation, which returns a NumberFormatInfo object that contains the desired currency indicator as well as an adapter currency formatting pattern that always makes sure there is a space between the currency indicator and the amount, if the currency indicator is a three letter currency code.

    private NumberFormatInfo GetCurrencyFormatter(CultureInfo cultureInfo, bool useSymbol)
    {
        // Get all the basics from the passed in culture info (not before it is
        // guaranteed to use global settings)
        NumberFormatInfo LocalNumberFormatter = (NumberFormatInfo)this.GetGlobalCultureInfo(cultureInfo).NumberFormat.Clone();
        // Overwrite the culture settings with the specifics of the current currency
        Currency currency = _currencyRepository.Get(CurrencyCode);
        LocalNumberFormatter.CurrencyDecimalDigits = currency.SignificantDecimalDigits;
        if (useSymbol)
        {
            LocalNumberFormatter.CurrencySymbol = currency.Symbol;
        }
        else
        {
            LocalNumberFormatter.CurrencySymbol = Enum.GetName(typeof(CurrencyCodeKind), CurrencyCode);
            // If we use the ISO code, then we need to make sure the patterns always include
            // a space between the ISO code and the amount.
            if (LocalNumberFormatter.CurrencyPositivePattern <= 1)
            {
                LocalNumberFormatter.CurrencyPositivePattern = LocalNumberFormatter.CurrencyPositivePattern + 2;
            }
            switch (LocalNumberFormatter.CurrencyNegativePattern)
            {
                case 0: // ($n)
                    LocalNumberFormatter.CurrencyNegativePattern = 14;
                    break;
                case 1: // -$n
                    LocalNumberFormatter.CurrencyNegativePattern = 9;
                    break;
                case 2: // $-n
                    LocalNumberFormatter.CurrencyNegativePattern = 12;
                    break;
                case 3: // $n-
                    LocalNumberFormatter.CurrencyNegativePattern = 11;
                    break;
                case 4: // (n$)
                    LocalNumberFormatter.CurrencyNegativePattern = 15;
                    break;
                case 5: // -n$
                    LocalNumberFormatter.CurrencyNegativePattern = 8;
                    break;
                case 6: // n-$
                    LocalNumberFormatter.CurrencyNegativePattern = 13;
                    break;
                case 7: // n$-
                    LocalNumberFormatter.CurrencyNegativePattern = 10;
                    break;
                default:
                    break;
            }
        }
        return LocalNumberFormatter;
    }
    
    private CultureInfo GetGlobalCultureInfo(CultureInfo cultureInfo)
    {
        if (!cultureInfo.UseUserOverride)
        {
            //The passed in culture info is already in "global mode"
            return cultureInfo;
        }
        else
        {
            // The passed in culture info is set to use OS specific
            // culture settings; this should be changed.
            return new CultureInfo(cultureInfo.Name, false);
        }
    }
    

    Wrapping it up

    Jee wizz… that’s a lot of explainin’, Batman! Yeah, well… there’s still a bit more in the actual code that I have not covered in detail, but this story should have you covered for regular use. If -after this whole epistle- you’re still interested in the actual code, you can get your copy here:

    Download the C# Money implementation

    Oh yeah… do note that this all is built in Visual Studio 2008 Professional, so you might run into some problems if you try to use it directly in an older version of Visual Studio. Sorry for that!

    Gimme feedback!

    This is only my first go at a decent Money implementation. The unit test set can use some extension and cleaning up; I’m aware of that. Furthermore, the implementation will certainly get updated based on requirements within projects I use it in. But also, I hope to get feedback from you with suggestions, new insights, updates of rules (e.g. the rounding schemes), updates of code, etc. Especially I’d like feedback from foreign readers who find that this implementation needs adaptation to work correctly in their country, with their currency. Use this implementation freely and let me know it can be improved!