Archive for the ‘User Controls’ Category

Localization and Globalization – Part 1 DateTime

December 27, 2011 Leave a comment

As the demand for applications that are “culture aware” becomes a much more frequent requirement, the implementation of it becomes more and more important. Globalization is more then just implementing the ability to change the language of the user interface, it’s many more details. It’s the way digit groupings are done, money displayed and date format to name a few.

Today I decided to dedicate this article to the various considerations that revolve around the DateTime class.

A few resources to have a look at if you’re not familiar with DateTime Class.


MSDN Library Entry for DateTime Struct

MSDN Entry for DateTime Picker Class

Code Sample

The Basics

DateTime is not a class, it is a struct. The challenge that most programmers have with this is what to initialize the struct as. For example, when initializing an int for the most part it’s initialized to 0 or –1. This is (of course) generally speaking, for DateTime I would recommend that when declared it should be initialized to DateTime.Min. DateTime.Min is equal to 00:00:00.0000000, January 1, 0001 which is a highly improbable date to ever use within a program.

The other consideration is current time. There are two methods for that DateTime.Now and DateTime.UtcNow. I would strongly recommend that UtcNow is used as often as possible. If the current DateTime is used frequently in a high speed environment (such as time stamps for packet sniffing) you must use DateTime.UtcNow. In the example program (see under resources) the differences between UtcNow and Now is below copied from the output of the program:

For 100000 iteration it took a total of 241 ms when Using DateTime.Now and 144 ms total when using DateTime.UtcNow

As you can see UtcNow is significantly faster then Now.

One last word of caution that most of the rest of the blog will be about, whenever possible (I’ve made it an unbreakable rule for me and my team) do not store dates and/or times as anything other then a DateTime (especially a string) and always verify and validate user input.


Verifying Validating Dates

The best way to make sure that the date that was entered is the right one is to restrict the user to a DateTime Picker. However, should that not be an options there’s a need to create a system of checks that both provide hints for the user on how to enter the date and once entered to verify that the date entered is the same as what the user intended. For example if the user enters 1/2/2011 did they mean January 2nd or February 1st? We’re going to take a detour and discuss localizing the date format first and then put the two topics together and create a user control that will cover both topics in one example.


Localizing DateTime Display

The screen shot below is intended to demonstrate the differenced between language (Culture Settings) and DateTime format. The screenshot is taken from the Sample that can be found here.

The first column is the description of the format. In the screen shot  I chose el-GR (Greek) as the culture. It’s important to note that if the only the format is applied it changes the date display (second column) to match what is the norm in Greece, however it doesn’t change the language (December is still shown as the month). However, on the third column where I apply the culture it changes both the date format and the language of the date.


Bringing it All Together

To bring it all together there’s a user control that provides a user a textbox to enter the date. When the control is loaded it changes the {0} in the “Enter Date” label such that it shows the format that is excepted for the current culture. Furthermore once the date is entered the the text box loses focus (meaning the user moved to the next field needing their input)the date is parsed and shown written out below the text box, that way the user can confirm it’s the right date.


Happy Codin’


Globalization and Controls in C#

December 24, 2011 Leave a comment

Over the last couple of years I have found myself seeing “globalization” being added as a requirement more and more frequently. Microsoft has done an amazing job making it easy to easily implement a display interface that is culture friends. The CultureInfo Class provides an easy to use way of displaying dates, currency, digit grouping and so on.

In an effort to show once again how easy and time saving it is to create your own controls I created a simple “globalized” phone number formatting (masked) text box.

The idea is to create two dictionaries, one with the phone number formatting with area code and one without. Overriding the OnCreateControl to select the appropriate Mask to apply. I couldn’t find a way to get the phone number formatting from the CultrueInfo, it doesn’t look like there’s a way. Basically I have the dictionary that you can add full codes, language code only or country code only. It will look for the full code first, if there’s no match it will look for the country code and lastly the language code. Finally if there is no matches on any of the above it will return the entry with the key “”. It’s the default for when globalization is off as well. The property Globalize is intended to be able to disable the globalization just in case.

As always you can download the sample  here.

Wiki article on the subject is here.

 1:  public class PhoneNumberMaskedTextBox : MaskedTextBox
 2:     {
 3:         /// <summary>
 4:         /// Indicates if the culture of the OS should be applied
 5:         /// </summary>
 6:         private bool globalize = true;
 7:         /// <summary>
 8:         /// Indicates if the formatting should include the areacode
 9:         /// </summary>
 10:         private AreaCode areaCode = AreaCode.WithAreaCode;
 13:         /// <summary>
 14:         /// Gets or Sets if the control should globalize according to the OS Culture
 15:         /// </summary>
 16:         public bool Globalize { get { return globalize; } set { globalize = value; } }
 17:         /// <summary>
 18:         /// Gets or Sets if the formatting should include areacode
 19:         /// </summary>
 20:         public AreaCode AreaCode { get { return areaCode; } set { areaCode = value; } }
 23:         private Dictionary<string, string> formatsWithAreaCode = new Dictionary<string, string>()
 24:         {
 25:             {"US","(000) 000-0000"},
 26:             {"es-VE","(0000) 000,00,00"},
 27:             {"CN","(00) 00000000"},
 28:             {"FR","00 00 00 00 00"},
 29:             {"","(000) 000-0000"}
 30:         };
 31:         private Dictionary<string, string> formatsWithoutAreaCode = new Dictionary<string, string>()
 32:         {
 33:             {"US","000-0000"},
 34:             {"es-VE","000,00,00"},
 35:             {"CN","00000000"},
 36:             {"FR","00 00 00"},
 37:             {"","000-0000"}
 38:         };
 39:         public PhoneNumberMaskedTextBox() : base()
 40:         {
 41:             if (globalize)
 42:                 Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
 43:         }
 44:         protected override void OnCreateControl()
 45:         {
 47:             this.Mask = getMask();
 48:             base.OnCreateControl();
 49:         }
 50:         protected string  getMask()
 51:         {
 52:             Dictionary<string, string> dictionaryToUse = new Dictionary<string, string>();
 53:             if (this.AreaCode == PNCControls.AreaCode.WithAreaCode)
 54:                 dictionaryToUse = formatsWithAreaCode;
 55:             else if (this.AreaCode == PNCControls.AreaCode.WithoutAreaCode)
 56:                 dictionaryToUse = formatsWithoutAreaCode;
 57:             if (dictionaryToUse.ContainsKey(Culture.Name))
 58:             {
 59:                 return dictionaryToUse[Culture.Name];
 60:             }
 61:             else if (dictionaryToUse.ContainsKey(Culture.Name.Replace(Culture.TwoLetterISOLanguageName + "-","")))
 62:                return  dictionaryToUse[Culture.Name.Replace(Culture.TwoLetterISOLanguageName + "-","")];
 63:             else if (dictionaryToUse.ContainsKey(Culture.TwoLetterISOLanguageName))
 64:             {
 65:                 return dictionaryToUse[Culture.TwoLetterISOLanguageName];
 66:             }
 67:             else return dictionaryToUse[""];
 68:         }
 69:     }

.csharpcode, .csharpcode pre
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }

Creating Custom User Controls in C#

December 23, 2011 Leave a comment

Wrote a Wiki article on TechNet describing how to create a custom control.