[System.Text] MessageFormatter

using System;
using System.Text;
using System.Globalization;
using System.Collections;
using System.Text.RegularExpressions;
namespace MarcoBarzaghi.Common.Utils.Text
{
 public class MessageFormatter
 {
  Hashtable _placeholders = new Hashtable();
  public void Set(string name, object value)
  {
   _placeholders[name] = value;
  }
  private string OnMapAndFormatValue(Match match)
  {
   //la regex cattura anche "{@placeholderName}", comprendendo anche "@" e 
   //parantesi graffe inziali e di chiusura: devo quindi pulire la stringa catturata.
   string matchedValue = match.Value;
   string placeholder  = new string(matchedValue.ToCharArray(2, matchedValue.Length  -3));
   
   //recupero il valore e le eventuali specifiche per la sua formattazione.
   string[] args = placeholder.Split(new char[]{':'}, 2);
   object value = _placeholders[args[0]];
   string format = args.Length > 1 ? args[1] : string.Empty;
   if(format != string.Empty  && value is IFormattable)
   {
    //se il dato è formattabile ed è stata richiesta la formattazione torno
    //una stringa opportunamente formattata ...
    return ((IFormattable)value).ToString(format, CultureInfo.CurrentCulture);
   }
   else
   {
    //...else chiedo all'oggetto la sua raprresentazione in stringa
    return value.ToString();
   }
  }
  public string Format(string s)
  {
   Regex regex = new Regex(BuildReplacePattern());
   return regex.Replace(s, new MatchEvaluator(this.OnMapAndFormatValue));
  }
  private string BuildReplacePattern()
  {
   StringBuilder sb = new StringBuilder("{(?:");
   int count = 0;
   foreach(string placeholder in _placeholders.Keys)
   {
    if(count++ > 0) sb.Append("|");
    sb.Append("@");
    sb.Append(placeholder);    
   }
   sb.Append(")(?:[^}]*|)}");
   string pattern = sb.ToString();
   return pattern;
  }
 }
}

Facciamo qualche prova per testarne le potenzialità!

MessageFormatter message = new MessageFormatter();
message.Set("date", DateTime.Now);
message.Set("name", "Pippo"); 
Console.WriteLine(message.Format("{@date} - {@name}"));
Console.WriteLine(message.Format("{@date:dd/MM/yyyy} - I'm {@name}!"));
Console.WriteLine(message.Format("{@date:dd-MMM-yyyy} - I'm {@name}!"));
Console.WriteLine(message.Format("{@date:dd/MM/yyyy hh:mm} - I'm {@name}!"));
message.Set("amount", 10000);
Console.WriteLine(message.Format("{@date:dd-MMM-yyyy} - I'm {@name}! {@amount:#,##0.00;-#,##0.00;+0})"));
message.Set("amount", -10000);
Console.WriteLine(message.Format("{@date:dd-MMM-yyyy} - I'm {@name}! ({@amount:#,##0.00;-#,##0.00;+0})"));
message.Set("amount", 0);
Console.WriteLine(message.Format("{@date:dd-MMM-yyyy} - I'm {@name}! ({@amount:#,##0.00;-#,##0.00;+0})")); 

A me sembra interressante, che dite?

posted @ sabato 28 maggio 2005 01:49

Print
Comments have been closed on this topic.
«aprile»
domlunmarmergiovensab
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011