Pierre Greborio.NET

Talking about .NET world

March 2005 - Posts

Browser security
For many years I've heard people talking about IE security flaws and suggesting to move to other browser (Mozilla based). I quite sure that the security isn't a Microsoft's products only problem, it's for all software vendors and developers (open source and free software too). Today, we can say that Firefox (I like that browser) has some issues to resolve.
Posted: Mar 22 2005, 10:58 AM by PierreG | with no comments
Filed under:
Indigo Watcher
There are several interesting blogs talking about Indigo (some of these here, herehere and here) in english but not too much in italian. Then I started a new series called "Indigo Watcher" in italian. Any feedback is welcome :-)
Enterprise Architect User Group

Here it is :-)

Posted: Mar 18 2005, 06:58 AM by PierreG | with no comments
Filed under:
[Money Pattern] Formatting

Calling ToString method will shows the amount value without any currency symbol/name/ISO code. In order to show the correct money formatting we have two choices:

  1. Define a static formatting rule
  2. Create a custom formatter

Personally I prefer the second option so that the user (of the Money class) can decide which formatting to use in any context. Consider to build a custom formatter:

public class CurrencyFormatInfo : IFormatProvider, ICustomFormatter
{
 private const string FORMAT_NAME = "mn";
 private const string FORMAT_SYMBOL = "ms";
 private const string FORMAT_ISO = "mi";

 public object GetFormat(Type formatType)
 {
  if (formatType != typeof(ICustomFormatter))
   return null;
  else
   return this;
 }

 public string Format(string format, object arg, IFormatProvider formatProvider)
 {
  if (arg == null) throw new ArgumentNullException("arg");

  if((!string.IsNullOrEmpty(format)) && (arg is Money))
  {
   string s = format.Trim().ToLower();
   if (s.StartsWith("m"))
    return FormatMoney(arg as Money, format, formatProvider);
  }

  if (arg is IFormattable)
   return ((IFormattable)arg).ToString(format, formatProvider);
  else return arg.ToString();
 }

 private string FormatMoney(Money m, string format, IFormatProvider formatProvider)
 {
  switch (format)
  {
   case FORMAT_NAME:
    return string.Concat(m.Amount.ToString(formatProvider), " ", m.Currency.Name);
   case FORMAT_ISO:
    return string.Concat(m.Amount.ToString(formatProvider), " ", m.Currency.ISOCode);
   case FORMAT_SYMBOL:
    return string.Concat(m.Amount.ToString(formatProvider), " ", m.Currency.Symbol);
   default:
    return m.Amount.ToString(formatProvider);
  }
 }
}

In the above sample I defined three basic format strings, it is clear that in real-world situations you could decide to create more (and complex) choices. Once the format provider is defined we can then create all our ToString overrides:

public override string ToString()
{
 return (new CurrencyFormatInfo()).Format("m", this, null);
}

public string ToString(string format)
{
 return (new CurrencyFormatInfo()).Format(format, this, null);
}

public string ToString(string format, IFormatProvider formatProvider)
{
 if (string.IsNullOrEmpty(format))
  format = "m";

 return (new CurrencyFormatInfo()).Format(format, this, formatProvider);
}

Notification pattern

When I have to propagate errors from the domain object to the presentation I usually use exceptions. All errors bubble from bottom to up and then are ready to be published to the UI (managing the catch section). The Notification pattern can be a good alternative. Consider a notification class which contains a list of possible errors (for simplicity I don't consider information messages):

public class Notification
{
 private List<Error> _errors;

 public Notification()
 {
  _errors = new List<Error>(); 
 }

 public List<Error> Errors
 {
  get
  {
   return _errors;
  }
 }

 public bool HasErrors
 {
  get
  {
   return (0 != _errors.Count);
  }
 }

 public void Clear()
 {
  _errors.Clear();
 }

 public class Error
 {
  private string _message;

  public string Message
  {
   get { return _message; }
   set { _message = value; }
  }

  public Error() { }

  public Error(string message)
  {
   _message = message;
  }
 }
}

Then, I could create an interface for all of my domain objects:

public interface IDomainObject
{
 Notification Notification { get; }
 void Validate();
}

The Validate method is used to validate the domain object depending its constrain rules. For example the Customer class could have two constrains:

public void Validate()
{
 if (string.IsNullOrEmpty(_code) || _code.Length != 4)
  _notification.Errors.Add(new Notification.Error("The Customer code is not well formatted."));
 
 if (string.IsNullOrEmpty(_lastName))
  _notification.Errors.Add(new Notification.Error("The last name must be defined"));
}

Once the validate has collected the list of errors to communicate to the presentation view, I have to find a way to show them in the web page (ASP.NET). I then created a custom validator class containing my error message:

public class NotificationMessageValidator : IValidator
{
 private string _errorMessage;

 public NotificationMessageValidator()
 {
 }

 public NotificationMessageValidator(string errorMessage)
 {
  _errorMessage = errorMessage;
 }

 public string ErrorMessage
 {
  get
  {
   return _errorMessage;
  }
  set
  {
   _errorMessage = value;
  }
 }

 public bool IsValid
 {
  get
  {
   return false;
  }
  set
  {
  }
 }

 public void Validate()
 {
 }
}

Then, the presenter class can fill the page validator collection:

Customer customer = new Customer(_view.Code, _view.FirstName, _view.LastName);
customer.Validate();

if (customer.Notification.HasErrors)
{
 foreach (Notification.Error error in customer.Notification.Errors)
  _view.Page.Validators.Add(new NotificationMessageValidator(error.Message));
}

With a simple SummaryValidator inside the page I'll see all error messages shown in my web page. I can see two main advantage vs exceptions:

  1. I can manage/show more than one error message at a time
  2. It consumes less system resources
[Money Pattern] Currencies

In the past blog I introduced the concept of Currency. It was really poor in terms of functionality since I have to set all its characteristics (symbol. name and ISO 4217 code) every time. It would be useful to have an internal table containing all currencies of the world:

internal sealed class CurrencyTable : Dictionary<string, Currency>
{
 private static volatile CurrencyTable _table;
 private static object syncRoot = new Object();

 private CurrencyTable()
 {
  this.Add("EUR", new Currency("EUR", "Euro", "\u20AC"));
  this.Add("USD", new Currency("USD", "Dollars", "\u0024"));
  this.Add("CAD", new Currency("CAD", "Dollars", "\u0024"));
  this.Add("GBP", new Currency("GBP", "Pounds", "\u00A3"));
 }

 private static CurrencyTable Table
 {
  get
  {
   if (_table == null)
   {
    lock (syncRoot)
    {
     if (_table == null)
      _table = new CurrencyTable();
    }
   }

   return _table;
  }
 }

 public static Currency GetCurrency(string isoCurrencyCode)
 {
  string key = isoCurrencyCode.ToUpper();
  if (Table.ContainsKey(key))
   return Table[key];
  else
   return new Currency();
 }
}

The the above code I made two choices:

  1. If the currency doesn't exists in the table then get the default (eur) instead of raising an KeyNotFoundException
  2. I fill the currency table from the code. I could use a resource file (better) instead. 

Now, I can add a new Currency constructor which lookups the currency from its ISO code:

public Currency(string isoCode)
{
 ISOCode = isoCode;

 Currency lookup = CurrencyTable.GetCurrency(isoCode);
 if (lookup != null)
 {
  Name = lookup.Name;
  Symbol = lookup.Symbol;
 }
}

And set two new Money constructors:

public Money(decimal amount, string isoCurrencyCode)
{
 _amount = amount;
 _currency = CurrencyTable.GetCurrency(isoCurrencyCode);
}

public Money(decimal amount, Currency currency)
{
 _amount = amount;
 _currency = currency;
}

With the last constructor I can refactor the arithmetic operators so that they consider also the currency:

public static Money operator +(Money a, Money b)
{
 CheckCurrency(a, b);
 return new Money(a._amount + b._amount, a.Currency);
}

[Money Pattern] Arithmetic operations

The Money class I implemented is really primitive. I can't imagine a Money class without arithmetic operators. So, the first step is to implement all base operators:

public static Money operator +(Money a, Money b)
{
 return new Money(a._amount + b._amount);
}

Even if the implementation is simple it presents at least one issue. I can't add amount of different currency. Then I could check the currencies and eventually raise an exception if the currency aren't equals:

public static Money operator +(Money a, Money b)
{
 CheckCurrency(a, b);
 return new Money(a._amount + b._amount);
}

private static void CheckCurrency(Money a, Money b)
{
 if (a.Currency != b.Currency)
  throw new ArgumentException("The currencies are not equals.");
}

[Money Pattern] First step implementing money

Well, how much cash do I have in my pocket ? I can say 52.24 ! What ? Euro, US Dollars, Yen or whatever ? It's clear that indicate the money just as an amount isn't enought. But to indicate money like a combination of an amount and a symbol is too simplicistic. Just to start from somewhere I can create a Currency class which contains some info about the currency:

public class Currency
{
 public string Country;
 public string Name;
 public string ISOCode;
 public string Symbol;

 public Currency()
 {
  Country = "";
  Name = "Euro";
  ISOCode = "EUR";
  Symbol = "\u20AC";
 }

 public Currency(string isoCode)
 {
  ISOCode = isoCode;
 }

 public override string ToString()
 {
  return ISOCode;
 }

 public override int GetHashCode()
 {
  return ISOCode.GetHashCode();
 }

 public override bool Equals(object obj)
 {
  if (!(obj is Currency))
   return false;

  return (obj as Currency).ISOCode.Equals(this.ISOCode);
 }

 public static bool operator ==(Currency a, Currency b)
 {
  return a.Equals(b);
 }

 public static bool operator !=(Currency a, Currency b)
 {
  return !a.Equals(b);
 }
}

[I live in Euroland, then my default is Euro :-)]

Note that each currency is identified by their ISO 4217 currency codes. Now that we have the Currency we can create our Money:

public class Money
{
 private decimal _amount;
 private Currency _currency;

 public decimal Amount
 {
  get { return _amount; }
  set { _amount = value; }
 }

 public Currency Currency
 {
  get { return _currency; }
 }

 public Money()
 {
  _currency = new Currency();
 }

 public Money(decimal amount) : this()
 {
  _amount = amount;
 }

 // Continues here

Ok, we have a Money class, which contains all info we need. Then the instance of my money (on my pocket) is

Money money = new Money(52.24m);

That isn't enought, trust me. Next time I'll implement all other features...

More Posts