.comment-link {margin-left:.6em;}

Friday, July 29, 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.
taxCalculator.Calculate();

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
policies.
}

}

Template pattern example:


abstract Class TaxCalculator
{
public CalculateTax()
{
CalculateIncome();
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. }

}


Thursday, July 28, 2005

.Net Tier 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 basic CRUD: UPDATE, DELETE, INSERT, SELECT ALL, PAGED SELECT, FIND

- 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.


Monday, July 25, 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.


Sunday, July 24, 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.


Sunday, July 17, 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.


Friday, July 01, 2005

Unit Testing with NUnit and Configuration Files

"When you are using NUnit and configuration files, the name of the configuration file must be the same as the name of the assembly with the .config suffix appended. For example, the assembly that contains the tests is named DataAccessLayer.dll. The name of the configuration file must be named DataAccessLayer.dll.config and it must be placed in the same directory as the assembly itself for the NUnit executable to find it."
- Test-Driven Development in Microsoft .NET