How to get a simple but good form validation

I used to get the form validation by hand, with some ugly checks, message boxes, several boolean variables to combine with a lot of operators && and ||. A TOTAL mess.

My target was to provide a simple validation tool that I can spread (by inheritance) to all the forms in a project.
So if your project needs only a simple check for mandatory fields, the solution I found maybe can interest you. If you need something more sofisticated, you can imagine an extension of this solution to suite your needs.

How to get it

In a base form class, the parent of all my forms in the project, get an instance of an ErrorProvider, by putting it into the form. Be sure to have “Modifier” property set to “Protected”.
By default, the form property AutoValidate is set to EnablePreventFocusChange. This way, all the controls fire up Validating Event when it’s time to, and the focus will remain on the control when the validation fails.
In this base form we have to add two methods: ValidateControl and SetValidationHandlerOnControl.
The first one is the method that will handle the validation on the control we need to check.
The second one will add the validation handler to the control.

namespace ValidationTest{
  public partial class MyBaseForm 
  {
    ... 
    protected void ValidateControlHandler(object sender, CancelEventArgs e)
    {
      // this string will be the tooltip shown when an error appears
      String error = null;
      String textToCheck = String.Empty;
  
      // we need to be sure that the sender control is 
      // of the type System.TextBox
      Type senderType = sender.GetType();
      if (senderType == typeof(TextBox))
        textToCheck = ((TextBox)sender).Text;
      else 
        throw new ArgumentException(
  	    "The sender is not a TextBox, but a " + senderType.Name);
  
      // Mandatory field: if the textToCheck is null or empty, fire up the error 
      if (String.IsNullOrEmpty(textToCheck))
      {
        error = "Mandatory field"; 
        // this CancelEventArgs property locks the pointer over the control 
        // until the error disappears
        e.Cancel = true;
      }
  
      // if there isn't any error, the SetError get a 
      // null string and it will not shown.
      // otherwise the SetError will show an icon and a tooltip 
      // next to the control that fails the validation
      errorProvider.SetError((Control)sender, error);
    }
  
    protected void SetValidationHandlerOnControl(Control ctrl) 
    { 
      // we need to be sure that the sender control 
      // is of the type System.TextBox
      Type ctrlType = ctrl.GetType();
      if (ctrlType == typeof(TextBox))
        ctrl.Validating += new CancelEventHandler(this.ValidateControlHandler);
    }
  }
}

Ok, that’s almost done.
Now, if we had a form that inherits from MyBaseForm, we can add the controls we need to validate with a simple call to SetValidationHandlerOnControl.
Let’s consider that we have three TextBoxes: by default they all have property CausesValidation set to true. And let’s have a button that is the default AcceptButton for the form, with the TabIndex property value set to be greater than the TabIndex value of the textboxes.
So we need to call

namespace ValidationTest{
  public partial class MyChildForm : MyBaseForm
  {
    public MyChildForm(){
      InitializeComponent();
      SetValidationHandlerOnControl(this.textBox1);
      SetValidationHandlerOnControl(this.textBox2);
      SetValidationHandlerOnControl(this.textBox3);
    ...
    }
  }
}

that’s it!
Now if we don’t provide any string in one of the textBox, the ErrorProvider will show a little (!) icon near to the textBox, the focus will remain on until the string is null or empty. (See image below)
validation
Get the solution with this example here (18Kb). Hope you’ll find it interesting…
Comment out the article if you like it!

EDIT: corrected a typo. Sorry!

Programmi “de menare”

Ascolto sempre 610 dove c’è un personaggio, Ernest del Montecastagna, che fa le recensioni del “cinema di menare”.
da oggi io propongo anche i “programmi de menare”:
mi telefona un tipo di roma, per assistenza su un nostro programma.
“me s’è ‘ncantato tutto, nun riesco a ‘ffà gniente, al colega mio je funziona, a ‘mme no!”
rispondo: “ho ucciso il processo che era in esecuzione, insomma gliel’ho buttato giù…”
e lui: “ah, gliele hai date?… bisogna menaje a ‘sti conpiuter!

Anche i SAP sbagliano

quando si timbra il cartellino elettronico, i dati sono raccolti dalla “macchinetta” e spediti a SAP, noto ERP. Bene, secondo voi, se sbagliate “verso di strisciatura” tra ingresso e uscita, cosa può succedere? si scombinano le ore di ingresso e uscita, e vengono fuori le cose più incredibili.
tipo questa: (clicca sull’immagine)
errori sap
risulta che merc. 21 ho lavorato dalle 17:59 alle 08:56 e poi dalle 32:56 (SIC!) alle 12:42, per un totale di 4 minuti di flessibilità, 4 ore di extra-orario e 14:42 ore di notturno!!!
In compenso giovedì mattina devo giustificare perché dopo la nottolata non sono venuto al lavoro…

Rails, Capistrano, Dreamhost All-In-One Guide

Hi all, I wrote this post in english because I think a lot of people will look at it.
Dreamhost is a very good web hosting company, that support Ruby On Rails application through Apache FastCGI module.
I choosed Dreamhost because the good reviews I see everywere, and I’m pretty happy to have it done. They offer a LOT of disk space, terabytes of monthly bandwidth, unlimited databases and unlimited subdomains, ssh login, svn repository, all that you will need. Truly!
So I wanted to deploy two Rails application I’m working on, in two subdomains, using the “automagic” Capistrano way of deploying.
When I setup Capistrano for the first time, it was version 1.X and I found all the info I need on Dreamhost Wiki and Rails manual, and it worked like a charm.
But the new application I wrote has been “capified” with Capistrano 2.0 (current release) and some little difference in configuration has getting me mad… Because of this I’m writing this little document, for helping other people and even for helping my memory 😀
So give this guide a look, I think it is very interesting!
It comprehends ssh password free login, svn repository, capistrano and ruby on rails!
And if you want to signup an account to Dreamhost now you can get a 50% discount by entering this DREAMHOST PROMO CODE: DVWV50

Aiméc!

ciao a tutti! ho una novità: l’altra settimana ho comperato un iMac 24″, vecchio modello, non il nuovo che aveva uno schermo impossibile da usare.
dopo il lavoraccio di importare nel nuovo iMac documenti/video/musica sparsi sui tre hd e sui due sistemi operativi del precedente pc, adesso ho un computer fantastico.
sono pure riuscito a fare pulizia della scrivania, e di ciò mia moglie è contenta. e in parte anch’io.
come diceva qualcuno, “la differenza tra un uomo e un bambino sta nel prezzo dei giocattoli che si comprano…”