Author Archive

Getting A List of All Special Directories in VB.NET

August 27, 2013 Leave a comment

Code below is just a quick blurb on how to get a list of all the Special Directories in VB.NET:

Module SpecialFolderAccess

Sub Main()

For Each tVar As Environment.SpecialFolder In [Enum].GetValues(GetType(Environment.SpecialFolder))


End Sub

End Module

Categories: Uncategorized

Nibbles and Bits–A discussion of Binary Operations in C#

January 8, 2012 Leave a comment

Before we start our discussion on Binary operations we should first discuss the different numerical systems. In general the most commonly used numbering systems (especially in programming) are Binary, Hexadecimal and Decimal.

Since all systems overlap some digits, in order to distinguish between the different numbering system we’ll use subscripts. For example 010 is 0 in decimal. 112 is binary 11 and 1016 hexadecimal.

The binary system is the easiest one to start with. There are 2 possible values for each digit 0 and 1. 02 = 010 , 112 = 310 . How does that work? It’s very simple. In the table below we have 8 positions, this is the same size as a byte. For each bit in the byte there is a binary value, meaning a 1 or 0. On the first row of the table it shows the value assigned to that bit. Because this system allow only two values (0,1) it’s called a Base2. In the table below you’ll notice that it’s value is an exponent of 2. This is very important and the basis of all numbering systems.

128 (27) 64 (26) 32 (25) 16 (24) 8 (23) 4 (22) 2 (21) 1 (20)
0 1 0 0 0 1 0 1

In order to convert a binary number to decimal simply multiply the values in the top row with the values in the bottom row. So the value of 010001012 = (1 * 64) + (4 * 1) + ( 1 * 1) = 6910. Surprisingly this is the same method used for all numbering systems. For example, in the table below is the same representation in decimal for the number 2012610:

100000 (105) 10000 (104) 1000 (103) 100 (102) 10 (101) 1 (100)
0 2 0 1 2 6

Lastly, using the same pattern we can show 12710 in hexadecimal.

256  (162) 16 (161) 1 (160)
7 F

As per the table 7F = (7 * 16) + (15 * 1) = 12710 .

That’s the quick recap on the concept of numbering systems. Now on to bit wise operations.

OR ( | ) and  AND ( & )

OR operations in C# are accomplished by using the | operator. The logic behind the OR operations is frequently used in if statements so all programmers are familiar with it, however, when writing out a bitwise OR it appears confusing simply because it’s in decimal notation.

 byte result = (17 | 5);
The output for the above operation will be 21. How do we apply a binary operator to byte values? You actually don’t, in the situation above the 17 is broken down to it’s binary equivalent and the 5 is broken down to it’s binary equivalent and each bit is “ORed”. Applying an OR operation to a binary  bit is easy to follow when you consider that a bit set to 0 is considered false and if a bit is set to 1 is considered true. With the OR operator if either side is set to true the result is always true. If both sides are false the result is always false. Below is a table that shows the example above’:
17 1 0 0 0 1
5 0 0 1 0 1
Result (21) 1 0 1 0 1
Once broken down to binary values, it demystifies the whole process of applying an OR operation to two bytes.
The AND operation when applied to bits only returns true (1) if both bits are true.
17 1 0 0 0 1
5 0 0 1 0 1
Result (1) 0 0 0 0 1

Putting it all together

What is the point of using these operations? There are quite a few operations that require and OR operation, however, the most common use is for storing Boolean values in a byte or integer value. Let’s say you need to keep track of 5 settings, New, Archive, Done, Hidden, Valid. You could create 5 Boolean variables to track them or just store them as bits in a byte. There are a lot of advantage to it, mostly because you can combine two sets of result just by conducting an OR operation. As demonstrated above you can combine the settings from two bytes easily into one.

To be Continued

Categories: Binary, C# Tags:

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; }

Serial Port Programming – Part 3 Final Touches and sending data

December 23, 2011 6 comments

As always the full program (after the modification discussed here) is in the MSDN Sample Library

There’s a few final touches left and we’ll complete our serial class. Depending on the cabling and the device your serial port is attached to you may require to let it know that your serial port is available for data. We do this by altering our Open method as shown below. Notice lines 18 and 20. DtrEnable is short for Data Terminal Ready and RTS is short for Ready To Send. These settings can (and frequently do) cause an exception depending on if they are supported or not. In my experience those two properties only fail when they’re not needed or if the serial port is not properly initialized. In the example below if the serial port throws an exception it will return false on line 16 and never try to enable DTR/RTS. This is also the reason why nothing is done with the exception.



 1:         public bool Open()
 2:         {
 3:             try
 4:             {
 5:                 this.serialPort.BaudRate = this.baudRate;
 6:                 this.serialPort.DataBits = this.dataBits;
 7:                 this.serialPort.Handshake = this.handshake;
 8:                 this.serialPort.Parity = this.parity;
 9:                 this.serialPort.PortName = this.portName;
 10:                 this.serialPort.StopBits = this.stopBits;
 11:                 this.serialPort.DataReceived += new SerialDataReceivedEventHandler(this._serialPort_DataReceived);
 13:             }
 14:             catch
 15:             { 
 16:                 return false;
 17:             }
 18:             try { serialPort.DtrEnable = true; }
 19:             catch { }
 20:             try { serialPort.RtsEnable = true; }
 21:             catch { }
 23:             return true;
 24:         }


The next step is to add a send method, as show below. You’ll notice that there are two methods, one for string and one for byte[], that just provides flexibility of data input.

 1: public bool Send(byte[] data)
 2:         {
 3:             try
 4:             {
 5:                 serialPort.Write(data, 0, data.Length);
 6:             }
 7:             catch { return false; }
 8:             return true;
 9:         }
 10:         public bool Send(string data)
 11:         {
 12:             try
 13:             {
 14:                 serialPort.Write(data);
 15:             }
 16:             catch { return false; }
 17:             return true;
 18:         }


Next we add an Event for our class to be fired when we have the completed string and if you recall when we received our data we were just writing it out to the console, we instead fire an event with the data. There will be more on creating your own events at a later date. For now here’s the relevent lines of code:

 1:     public delegate void dataReceived(object sender, SerialPortEventArgs arg);
 2:     public class SerialPortEventArgs : EventArgs
 3:     { 
 4:         public string ReceivedData { get; private set; }
 5:         public SerialPortEventArgs(string data)
 6:         {
 7:             ReceivedData = data;
 8:         }
 9:     }

.csharpcode .lnum { color: #606060; }

 51:  // Do something with workingString
 52:    if (this.DataReceived != null)
 53:    {
 54:          SerialPortEventArgs args = new SerialPortEventArgs(workingString);
 55:          this.DataReceived(this, args);
 56:    }

Lastly we add two new textboxes to the form so that we can send and received messages from our serial port and it’s done. It’s that simple to create a serial communicator.

 1:         public Form1()
 2:         {
 3:             InitializeComponent();
 4:             serialPortSettingsControl1.WorkingObject = _workingObject;
 5:             _workingObject.DataReceived += new dataReceived(_workingObject_DataReceived);
 8:         }
 10:         void _workingObject_DataReceived(object sender, SerialPortEventArgs arg)
 11:         {
 12:             this.ReceivedText.Text += arg.ReceivedData;
 13:         }
 14:         private void button3_Click(object sender, EventArgs e)
 15:         {
 16:             _workingObject.Send(this.SendText.Text);
 17:         }


This class can now be pulled into any project along with the control to update the settings and you can quickly implement serial port communications in any project.


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.

Serial Port Programming Part 2 – Developing a GUI to set the Port Settings and validating the data

December 22, 2011 1 comment

As promised the next instalment is on how to build the GUI elements needed to manage the settings for your serial port. The updated code for this entry is here.

Validating data for ComPort settings is a fairly easy process but slightly different depending on the setting you’re working with.  There are many different ways, the two most commonly used are to validate at the class level and the other is to validate at the user interaction level. There are many arguments for both, for validating at the GUI level it’s simple, it’s easier to prevent the user from entering anything they want rather then checking every setting many different ways. For validating at the class level there’s the argument that if you re-use your code you have to keep re-entering the validation for the settings every time you design a new program. Both arguments are equally valid.

What I decided to do in this example is to create highly restrictive controls and place them in the same library as my serial port class. That way I don’t have to re-do the validation every time I draw a new GUI and it’s easier to restrict the user then to validating any data they enter.

Before we continue a few comments about creating your own controls. In many cases it’s not as hard as most people assume it is to create your own controls and it saves you a tonne of time. I only have two criteria to create a new control class; a) am I going to re-use it more then once in this project or b) do I think I’ll need it in the future. In the case of the serial port class, I think I’ll use it in the future again and it’ll take about as long to create a re-usable control as it would to just add it to the form now and set up the restrictions.

The first settings (and easiest) is Port Name. On every computer there’s a different number of ports and with differed names. When possible you want to limit the user to what they could enter. The best way to display a series of values and have a user select one is the ComboBox Class. I want to create a combo box and load in the available port settings. I also want to make sure that I select one, if there’ isn’t one select the user may just type one themselves. The first step is to inherit from the ComboBox class.  You may note in the class below I didn’t implement a constructor and I decided to put the load statements in the OnCreateControl method (lines 3 – 13). The reason for that is that the Constructor of a control also gets called during design time. In order to avoid effecting my design environment I added the methods I needed when the Control is created. When inheriting from a control, instead of tying into a particular event it’s best to override the OnEvent methods. These methods are what triggers the events, for example when the Button Click event is fired it’s actually the OnClick method that’s firing the event. The other line to note is 6. I’m not sure what methods are called when creating the control in design time, so in order to avoid any problems I enclose the functional parts of the method in an if statement. Finally it’s just a matter of loading the resulting strings from SerialPort.GetPortNames() into the combo box items and selecting the first one.

 1: public class ComPortComboBox : ComboBox
 2:     {
 3:         protected override void OnCreateControl()
 4:         {
 5:             this.Items.Clear();
 6:             if (!this.DesignMode)
 7:             {
 8:                 this.Items.AddRange(SerialPort.GetPortNames());
 9:                 this.SelectedIndex = 0;
 10:             }
 12:             base.OnCreateControl();
 13:         }
 14:     }

Then next step is to have a look at the BaudRate. BaudRate setting expects an integer, but it can’t be any integer. For example if the user enters 0 or 2 it will not be a valid baud rate. The other setting that fits that criteria is the DataBits. Since there are two settings that fit this criteria I will first create an abstract class that manages the user interaction then create one specific to BaudRate and DataBits.

For the abstract class I decided to inherit from the NumericUpDown Class. This control allows only numbers and has a convenient and familiar look to it. Since we’re looking for a discreet set of numbers I created an int[] variable called baudrates (line 3). This will contain all the permissible entries for our control. Following that I set the minimum and maximum values in the OnCreateControl() method (lines 8 – 9). Notice I don’t discreetly enter any values, I simply refer back to the array for that. Then I simply override the OnValueChanged  method (lines 12 – 21) and if the value increases (line 16) I use the next highest value in the array and if it decreases (line 18) I use the next lowest value. I use the private variable oldValue (line 4,21) to track the value before it was incremented or decremented.

 1:     public abstract class RestrictedUpDown : NumericUpDown
 2:     {
 3:         protected int[] baudRates = new int[2]{1,2};
 4:         private int oldValue = 0;
 6:         protected override void OnCreateControl()
 7:         {
 8:             base.Minimum = baudRates[0];
 9:             base.Maximum = baudRates[baudRates.Length - 1];
 10:             base.OnCreateControl();
 11:         }
 12:         protected override void OnValueChanged(EventArgs e)
 13:         {
 14:             if (!baudRates.Contains((int)this.Value) )
 15:             {
 16:                 if ((int)this.Value > oldValue)
 17:                     this.Value = baudRates.First(p => p > this.Value);
 18:                 else this.Value = baudRates.Last(p => p < this.Value);
 19:             }
 20:             base.OnValueChanged(e);
 21:             oldValue = (int) this.Value;
 22:         }
 24:     }

Once that’s done creating the controls for the BaudRate and Databits take a few seconds:

 1:  public class BaudRateUpDown : RestrictedUpDown
 2:     {
 3:         public BaudRateUpDown()
 4:         {
 5:             baudRates= new int[]{1200,1800,2400,4800,7200,9600,14400,19200,38400,57600,115200,128000};
 6:         }
 7:     }
 8:     public class DataBits : RestrictedUpDown
 9:     {
 10:         public DataBits() :base()
 11:         {
 12:             baudRates = new int[] { 4, 5, 6, 7, 8 };
 13:         }
 14:     }

The rest of the properties are all enumerators. Once again we start with an abstract class. This time notice the <T> that simply denotes that we can add a specific type when inheriting. Following that it’s similar to the PortNames combo box however we enumerate through the <T> and get all the possible values and enter them into the combo box (lines 10 – 14) and automatically select the first one.

 1: public abstract class EnumComboBox<T> : ComboBox
 2:     {
 4:         protected override void OnCreateControl()
 5:         {
 6:             Type enumType = typeof(T);
 7:             if (!this.DesignMode)
 8:             {
 9:                 base.Items.Clear();
 10:                 foreach (var item in Enum.GetValues(enumType))
 11:                 {
 12:                     base.Items.Add(item);
 13:                 }
 14:                 this.SelectedIndex = 0;
 15:             }
 16:             base.OnCreateControl();
 17:         }
 19:     }

Creating the actual combo boxes from there is only a few lines of code (3 to be exact) as follows:

 1:     public class ParityComboBox : EnumComboBox<Parity> { }
 2:     public class StopBitsComboBox : EnumComboBox<StopBits> { }
 3:     public class HandShakeComboBox : EnumComboBox<Handshake> { }

Now what we have is a few controls that we can drag and drop and without any coding be able to create a simple user control that looks like this:


Following that we drag this user control into a form and set up the saving and loading of the settings and we’re done. Please see the complete source code here.

As you can see in this case creating validated controls to manager are settings is simply the quickest and most efficient route.