Author Archives: admin

Get the command line

There are two ways to get the command line.

string commandLine = System.Environment.CommandLine;

This property contains the entire (full) command line.

or use:

string[] commandLine = System.Environment.GetCommandLineArgs();

The first array element contains the executable (may include the path)
The other array elements the arguments. They are separated by spaces.

Generate a random number (or byte array)

To generate a random number use the System.Random.Random class

The numbers generated are pseudo random. Typically, using the same seed generates the same value sequences.

The seed can be set in the constructor. If none is set, a time dependent seed is used which should generate more or less random values.

To get a value call the method Next

int value = rand.Next();

or within range 0 – 255

int value = rand.Next(255);

or between 100 and 200

int value = rand.Next(100, 200);

a double between 0.0 and 1.0

double value = rand.NextDouble();

Or a byte buffer

Byte data = new Byte[100];

rand.NextBytes(data);

Getting a value of a ToolStripTextBox on a lost focus

Using the Leave event does not work unless you press Tab key (which presumably takes the focus of the entire ToolStrip).

To detect the lost focus of the ToolStripTextBox use the LostFocus event. It is not in the designer and needs to be added manually, typically from the forms constructor.

public Form1()
{
   toolStripTextBox1.LostFcus += new EventHandler(toolStripTextBox1_LostFocus);
}

void toolStripTextBox1_LostFocus(object sender, EventArgs e)
{
   //Access the text property
   string value = toolStripTextBox1.Text;
}

Serialize an object to / from XML

Serializing  allows you to simply store or load an object’s contents to a XML file.

Classes can be serialized to XML. All public fields will be serialized automatically

Use the [XmlIgnoreAttribute] to prevent serialization.

Example

[XmlIgnoreAttribute]

int notToBeSerialized;

Sample:

Save or load an object to an XML file.

These functions can throw exceptions which must be handled !

class XMLSerializer
{
   public static T read<T>(string path)
   {
      T data = default(T);
      System.IO.TextReader reader = new System.IO.StreamReader(path);
      System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
      data = (T)ser.Deserialize(reader);
      reader.Close();
      reader.Dispose();
      return (data);
   }

   public static void write<T>(string path, string filename, T data)
   {
      if (!Directory.Exists(path)) Directory.CreateDirectory(path);
      path += "\" + filename;
      System.IO.TextWriter writer = new System.IO.StreamWriter(path);
      System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
      ser.Serialize(writer, data);
      writer.Close();
      writer.Dispose();
      return (true);
   }
}