Thursday, July 28, 2005

      Template vs Strategy Patterns

The Template pattern is similar to the Strategy pattern. These two patterns differ in scope and in methodology.

Strategy is used to allow callers to vary an entire algorithm, like how to calculate different types of tax, while Template Method is used to vary steps in an algorithm. Because of this, Strategy is more coarsely grained. The Template allows finer-grained controls in the sequent of operations, and yet allows the implementations of these details to vary.

The other main difference is that Strategy uses delegation while Template Method uses inheritance. In Strategy, the algorithm is delegated to the another xxxStrategy class that the subject will have a reference to, but with Template you subclass the base and override methods to make changes.

Strategy pattern example:

Class MainSubject

ITaxStrategy taxCalculator = GetStrategy(taxType);
//strategy is member class.

private GetStrategy(string taxType)

if (taxType == "incometax")
return new IncomeTaxStrategy();
else if (taxType == "propertytax")
return new PropertyTaxStrategy();

Class IncomeTaxStrategy : ITaxStrategy

public Calculate()
//calculate based on income tax rates.


Class PropertyTaxStrategy : ITaxStrategy

public Calculate()
//calculate based on property tax


Template pattern example:

abstract Class TaxCalculator
public CalculateTax()
tax =+ CalculateTax();
tax =+ CalculateRelief();

abstract CalculateTax();
abstract CalculateRelief();


Class IncomeTaxCalculator : TaxCalculator

override CalculateTax() { //calculate income tax. }
override CalculateRelief() { //calculate personal relief }


Class PropertyTaxCalculator : TaxCalculator

override CalculateTax() { //calculate property tax. }
override CalculateRelief() { //do nothing; no relief. }


Wednesday, July 27, 2005

      .NetTier Beta 1 is Released !

Finally, after much anticipation and waiting, the version 1.0 of .NetTier is out in Beta 1.

What is .NetTier? Well, it's a set of open source CodeSmith templates that is used to generate a data access layer, based on the database schema. It takes the load out of repeatitive data access coding for common CRUD functions. In addition, it also translates the database schema into a ready-to-use object model in the form of Entities and EntityCollections. With this, developers can almost start focusing on the business domain issues immediately.

To quote .NetTier's site:
" .NetTiers are CodeSmith templates for object-relational mapping that takes an existing SQLServer database and automatically generates a personnalized Data Tiers application block to use in your .Net applications. "
Some of its features include:

- Fully integrate with entreprise library application blocks architecture. Shipped with it's own plugin, so you can configure your application directly from the entlib configuration console.

- Generate the business objects (called entities) with a 1:1 mapping ( an entity for each table, with a property for each column).

- Generate Data Access Layer Components (DALC) for tables and views , with following database operations :


  • Support for queries using primary key
  • Support for queries using foreign key
  • Support for queries using keys that are part of an index
  • Support for queries using keys that are part of a junction table
  • Support for user defined Methods, generated from queries that are detected throught a very simple naming rule (_TableName_MyMethodName)
  • Support for Deep loading and saving, with children type selection and optional recursivity.
  • Support for find methods, with paging and sorting. (builded with the datagrid in mind :-)
  • NEW: Support for SqlView.
  • NEW: Select between stored procedure or xml embedded queries.

- Generate strongly-typed collections for entities and repositories.

- Create the stored procedures script and can automatically install them on the server. The current beta includes dynamic sql as well.

- Generates a complete nAnt build file, to compile, test and generate chm/html API documentation.

- A full set of nUnit tests.

Sunday, July 24, 2005

      Asynchronous Logging using MSMQ in EL

The Logging and Instrumentation App Block in EL has a cool feature that harnesses MSMQ for asynchronous logging.

The advantages of asynchronous messaging based on MSMQ are multiple; Most importantly, I feel it is the decoupling of the message (event) source and the message handler that results in a higher system stability and reliability. In most solutions, the message source and the message handling logic usually resides in the same process, and the message handling logic will include some form of persistence like writing the messages to a database. Now, the problem comes when the database is down. The system can still receive the message, but cannot persist the message, and the messages are lost... With MSMQ, we add a layer of indirection by having MSMQ as an interim storage when the message is received. Then the permanent persistance will retrieve messages from MSMQ and write them to the database. So when the database is down, the messages are not lost as they can still be persisted to MSMQ when the database is back in operation.

Hence in my current project, I was intenting to use MSMQ to log SNMP traps and have another custom listener service to check (and subsequently process) the MSMQ for incoming traps. Stumbling upon this cool feature was like a great bonus, and I wasted no time in getting my hands dirty with this finding.

Digging into the details, I realised some finer caveats of this implementation that needs attention:

1. MSMQ Distributor Service is NOT installed by default. The MSMQ Distributor Service is a windows service that comes built into the app block. Its purpose is to check the MSMQ periodically for new messages. Then based on its configuration, the service will call the appropriate LogSink classes to persist the messages. However, note that the MSMQ Distributor Service is NOT installed by default when installing the EL. "Installutil.exe" that comes with .NET Framework SDK must be ran to install this service.

2. The MSMQ Distributor Service requires additional application-specific configuration. Even after the installing of the service, it must be configured to enable it to run. Example includes the queue in MSMQ that this service will check.

3. MSMQ's Custom Queue must be created manually. The custom queue in MSMQ must be created manually by the developer and deployment team. The EL installation process does not create the required queue in MSMQ.

4. Authentication for Custom Queue must be matching with Service's credentials. Permissions must be given to the account under which the service is running to access the custom queue. E.g. if the MSMQ Distributor Service is running under account 'NT Authority\Local Service', under the custom queue's security setting, the same account must be given 'Peek Message' and 'Receive Message' permissions. Otherwise the service will failed and stop.

5. MSMQ Distributor Service only supports ONE queue at a time. This limitation may mean that the service can only supports one application. My thoughts on working around this is to have this service use a generic queue, so that more than one application can use this same queue. The app block allows application-specific LogSinks to handle the messages in the applications context.

Well, most of these are mainly about design and deployment issues. If we are mindful about these and factored them into the deployment plan and installation setup projects, the benefits of a readily available asynchronous logging mechanism should outweight the above finer issues.

Saturday, July 23, 2005

      Enterprise Library has Built-in Dependency on WMI Instrumentation Schema

As my team was deploying his solution based on Enterprise Library v1.0, we discovered something that was not stated clearly in the documentations; EL has a set of instrumentation support built-in, and this introduces dependency on an instrumentation schema. This schema must exist on the executing machine, otherwise the following error is generated:

Failed to fire the WMI event 'DataConnectionOpenedEvent'.
Exception: System.Exception: This schema for this assembly has not been registered with WMI.
at System.Management.Instrumentation.Instrumentation.Initialize(Assembly assembly)

For developers, the schema would have being installed during the installation of EL by a batch file, "InstallService.bat". Hence, this issue will not be discovered on the development platforms until the time comes for deployment on production machines. Details of this instrumentation schema can be found at MSDN: Monitoring in .NET Distributed Application Design, and Registering the Schema for an Instrumented Application.

To resolve this issue on deployment platform, simply execute the batch file "InstallService.bat" on the deployment machine again, and the required schema will be installed. Note that this must be run under 'Local Administrator' rights for the registration to be successful (no more simple xcopy deployment?).
In addition, the release notes for EL v1.1 (June 2005) does highlight this issue.

From experience, the needs for instrumentation (post-deployment) is very vital. Building instrumentation into a solution, on top of the functional requirements, can make the difference between hell or ease for application support.

However, the EL's dependency on the schema is far from ideal, IMHO. Why didn't they provide flexibility to plug-in different Providers like they have done for other application blocks? Isn't this binding the EL to the implementation specifics on MS's platform features like WMI? A coincidence, or conceived move? You tell me.

Tuesday, July 19, 2005

      The Passing of a Friend

My friend Wei Loon collapsed during a run last Sunday; he never recovered from it. He was pronounced dead the same night.

I attended his wake this evening. It was surreal, like a deja vu; as I looked at his picture at the wake, then at him lying in the coffin, motionless. I could still remember the last time we met, we were talking about his latest 3G phone. He was so young, there must have been so much things he wanted to achieve. I wondered if he knew that all his friends were there at his wake. I wondered if he felt his body lying there. I wondered what goes on after life, or was that the end.

Life is short, it is unpredictable. Life has once again proven how vulnerable we are, yet at the same time, we think the world of ourselves. As years passed, I have encountered many experiences that highlights how little we are capable of, how limited we can achieve, despite how hard we tried sometimes.


Yet ironically, God gave us something that kept us going on. A hope? For what? But then, if we just give in, what do we make of the years before our turn to lie there motionless? So, many of us must have question at one point or another; what is the meaning of this life?

Wei Loon, rest in peace. I wish you happiness and peace, wherever you are.

Saturday, July 16, 2005

      MS Enterprise Library v1.1 (June 2005) Released

Enterprise Library v1.1 (June 2005) is released. It can be found here.

Based on the description writeup, there no major changes in the version. If you're looking forward to new App blocks, you will be disappointed. v1.1 still maintains the 7 existing app blocks. Well, I was hoping they include the User Interface Process App Block. I sure need an MVC framework for my next project. Maybe have to play with Maverick.NET, no choice.

The memory leak issue with the configuration app block was patched up; and some minor touch up for threading, some file paths issue etc. Maybe the most interesting enhancement is the new Providers for Configuration App block allowing us to save configurations to the register, and SQL Servers. Ha, no more XML configuration files for me. Oh yes, the 2 versions supports side-by-side executions.

I have downloaded it. Gonna dig into it over the weekend.

Sunday, July 10, 2005

      Steve Jobs: "Stay Hungry, Stay Foolish"

I read one article in the Sunday Times today, titled "Stay Hungry, Stay Foolish". It's a verbatim of Steve Job's speech at Stanford's 114th Commencement. Truly an inspiring and stirring article, citing some of the watersheds and pivotal moments in this great man's life.

Surprisingly, Steve is another one of those great achiever who did not even finish college. He dropped out at a young age, to focus on calligraphy that was seemingly impractical then; yet ironically, this contributed largely to the success of Macintosh as the first computer with beautiful typography 10 years later.

As I had stated in a previous article, every watershed and momentous decision is never without its element of uncertainty and fear. There will be doubt as to the "correctness" of the judgment; I remember my decision to leave the military a year back. I guess that will definitely be one of my pivotal moments of my life. Leaving behind a stable and relatively well paying job as an SAF Officer, I plunged into the unknown, with a major salary cut. Is it for the better? Well I believe that the answer is actually is in our hands, that the answer is ours to create. To make it or break it, it is manifestation of our efforts following the decision. Well, I'm still working on it. haha...

As so aptly highlighted by Steve in the same speech, the love for work is one of the utmost influential factors behind his success. The efforts required cannot come about without the firm belief, the love and passion for the work. Looking around, the many people I see lamenting about their jobs; many in fact, have no idea about what they want to do. Yes, bringing the bread home at the end of the month is important, but it's not everything. It's sad that there are so many aimless souls wandering about, not knowing where to head.

It is important that we find the destination. Find it, find that destination, call it a vision, a goal, mandate, whatever; and then journey towards it; along the way, as Steve Jobs had put it, "stay hungry, stay foolish".

Thursday, July 07, 2005

      Price Hike Madness

Comfort, CityCab and Yellow-Top revise taxi fares

Alright, so the government is encouraging us to take public transport.

But with ever-increasing public transport fees, there's really little incentive for us to do so. It seems the ever demand and supply issues are simply "resolved" by increasing prices for the supply, in hope of easing the demand. Too little taxis during peak hour? Simple; just increase price, and lesser people will demand. Too many cars on the roads? Simple, let's put in COE and increase the ERP.

I mean, come on. Who's the gain from this at the end? Does this solve the problem? Look at crowds in Golden Village cinemas on weekends, I suppose the raise in price really doesn't matter much to them. So who's the happy people with the fatter pockets at the end of the day.

Everything's price is increasing. Oil price hike at new historical high, ERP, COE, GV tickets (maybe I can make a rep out of this). Madness...

Sunday, July 03, 2005

      Profits, Not Jobs, on the Rebound in Silicon Valley

Jobs will continue to flow into countries like India and China.

I am currently reading the book
"The World is Flat" by Thomas Friedman. What I have read so far points largely to the out flow of lower-level job opportunities to countries like India and China, where human resource cost is dramatically lower. I quote a passage from the book here: "Japanese firms can hire three Chinese software engineers for the price of one in Japan and still have change to pay a roomful of call center operators (at $90 a month starting salary)."

Well given the simple equation where profit = revenue - cost, it's quite a no-brainer to arrive at the conclusion that outsourcing to lower cost resources is the way to go. So where does that leave us?

My friend recently lamented about his job; He's in customer service, and his friends were insinuating that a career in customer service is not bright (at least in Singapore maybe). This seems to perturb him.

Ironically, in India today, it is the exact opposite. 600 job applications are received each day at a outsourcing call center. This call center performs out-sourced customer service for established American names like Dell, Microsoft, Intel. Young indian graduates flocked to take up a job in these call centers cause their monthly income is many times that of their parents retirement both add up. The job also allows them to work in the night (to suit daylight hours in America), and hence they can take up part-time studies in the day. It's shit job, some interviewed Indians said; but it pays well, and they can advance their studies at the same time, so what the hack.

The article
"Profits, Not Jobs, on the Rebound in Silicon Valley" is definitely no surprise to me then. It only serves to validate the observations that Thomas Friedman has so succinctly pointed out in his book.

Being an IT professional myself, this leaves me wondering where does this leave me. Also, more importantly, what does it take to ensure that as an IT professional, we can continue to stay relevant and continue to command a premium that our counterparts in India/China can't offer? Or more simplistically, how can I value-add?

The government has also done much in educating Singaporeans about these behemoth trends that cannot be ignored. We MUST move up the value-chain, they said. Sure, I think. So I will learn to design and architect software. Things that India/China software engineers cannot do; for now, that is... ... But what about 5-10 years from now. By then, the current pool of India/China software engineers would have learnt and experienced enough to venture up the value-chain themselves. Existing engineers would learn what it takes to design and architect software. So what then? Is there a next step up the chain that we can try to move ahead?

In a matter of time, what may happen is that the global playing field will be "leveled", and the world will no longer be one that is led by western powers. Due to advances in technology, the East will catch up with the West, forming a balance in the forces that driving the world today. Forces like technology, political, and economical powers will no longer be held sway by the West. Its a world where the "Ang Mo" is no longer deemed as being superior. Being a Singaporean, is it for the better or worse? Beats me, but I better find the way to up myself, before that happens to ensure that I am ahead of the rest