Wednesday, June 30, 2010

Change Cursor Position

With the class Cursor you can set the mouse position in C#. The corresponding property has the name Position, it saves the position of the cursor as a Point.
The position is global (so not only relative to the application), so for example (0, 0) describes the very upper left corner of the screen.
Setting the cursor position then can be done by:
Cursor.Position = new Point(X, Y);

Tuesday, June 29, 2010

List Partitions / Devices

With C# easily all available hard drives can be listed. Logical partitions on a physical hard drive are treated as independant devices.
The following console application shows the use of the class DriveInfo (System.IO has to be included) to get the names of all available devices on the computer:
            DriveInfo[] Drives = DriveInfo.GetDrives();

            foreach (DriveInfo drive in Drives)
On my computer the program outputs "C:\, D:\, E:\". First ones are partitions on my hard disk, the last one is the CD ROM drive.

Monday, June 28, 2010

Determine Physical Address (MAC address)

In today's post I want to show, how to readout the MAC address or physical address of the computer in C#.
The MAC address is the physical hardware address of the network adapter, by which this can be uniquely identified all over the world as it is only given once (theoretically though, in fact it is the cased that it gets reused and can also easily be faked).
So if your computer has a LAN card and connects to the internet using this, it can be identified by the MAC address of this.
With C# the MAC address can either be determined with the help of the class System.Management.ManagementClass, but the code for this is quite complicated.
There is a much more easier call to get the same result.
The following code is a C# console application, which iterates over all network adapters of the computer and outputs the corresponding description (name) and MAC address (using System.Net.NetworkInformation; has to be included):

            NetworkInterface[] NetworkAdapters = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface adapter in NetworkAdapters)
                Console.WriteLine("MAC Address: " + adapter.GetPhysicalAddress().ToString());

Saturday, June 26, 2010

Do Not Exit Console Applications Automatically

If you start a console application in the .Net environment with the usual command Debug - Start Debugging (F5), the console application will end automatically after running. Often this is annoying, as you mostly miss the output then on the screen, the windows just flashes up briefly.
But if you start the application with Ctrl + F5 (Start without Debugging), the message Press any key ... is shown, the application stays open until you do so.
Alternatively, you can also append a Console.ReadKey(); in the end, now the program also waits for a user input before closing.

Find Prime Numbers Using the Sieve of Eratosthenes

Today I want to show you how to implement the Sieve of Eratosthenes in C#, which outputs all primes starting from 2 to an upper border.
As the name of the algorithm stems from the Greek mathematician Eratosthenes of Cyrene, it is called "Sieve of Eratosthenes".
Let N be the upper bound, then the algorithm can be described as follows:
All numbers from 2 to N are written down. The smallest not crossed out number at all times is a prime number. At start this is the 2.
From then on, all multiples of this number are crossed out, it suffices to start with the square of the number.
Now here the code of a C# - console application doing exactly that:

    class SiebDesEratosthenes
        static void Main(string[] args)
            Console.WriteLine("Geben Sie die obere Grenze ein:");
            int UpperBound = int.Parse(Console.ReadLine()); // input upper bound
            bool[] Tagged = new bool[UpperBound + 1]; // array describing which numbers are crossed out

            // initialise arrays
            for (int i = 0; i < Tagged.Length; i++)
                Tagged[i] = false;

            // iterate over all numbers up to the square root of the upper bound
            for (int i = 2; i < Math.Ceiling(Math.Sqrt(UpperBound)); i++)
                if (!Tagged[i])
                    int j = i;
                    // cross out all multiples 
                    while (j * i <= UpperBound)
                        Tagged[j * i] = true;

            // alle nicht durchgestrichenen Zahlen ausgeben
            for (int i = 2; i < Tagged.Length; i++)
                if (!Tagged[i])
                    Console.Write(i.ToString() + " ");

Thursday, June 24, 2010

If Statement Using Questionmark (?) and Colon (:)

Here a quick post describing a short notation for if - else statements in C# .Net, which I used for example in the previous post.
A standard if statement assigning a value to a variable will look as follows:
if (Condition)
Variable = "Condition satisfied";
Variable = "Condition not satisfied";
One can shorten this code though using questionmark (?) and colon (:):
Variable = (Condition) ? "Condition satisfied" : "Condition not satisfied";

Here Variable gets assigned "Condition satisfied", if the condition is true, otherwise "Condition not satisfied".

Caesar Cipher in C#

The Caesar cipher was one of the first encryption methods of the world, as the name alreadys says, it was used already by Julius Caesar to send private information. In this method, alle letters are shifted circularly
by a fixed number.
Computer scientists call this a monoalphabetical substitution, meaning the same fixed alphabet is used for plain- and ciphertext and all letters of the plaintext are replaced by different letters.
An example for the Caesar cipher: Let the plaintext be "zum" and the shift key be "b" (2). Now every letter of the plaintext is shifted by 2 positions, after "z" we start again at "a".
So "z" becomes "b", "u" becomes "w" and "m" becomes "o". The ciphertext then is "bwo".
I implemented the Caesar cipher in C#, what I want to present you now.
I hope the sourcecode is well documented, so I will just post it (System.Text.RegularExpressions has to be included):
class CaesarCiphering
bool EliminateBlanks; // true if blanks shall be deleted
char Offset; // the shift key

public CaesarCiphering(bool eliminateBlanks, char offset)
EliminateBlanks = eliminateBlanks;
Offset = offset;

/// <summary>
/// in this function the given string is cleaned, meaning all letters not from the
/// encryption alphabet (only the letters a - z in lower case are allowed)
/// and if wanted blanks are eliminated
/// </summary>
private string CleanString(string text)
text = text.ToLower(); // convert text to lower case

if (EliminateBlanks) // eliminate blanks
text = text.Replace(" """);

// the following regular expression describes all strings which
// do not contain entirely out of a-z and blanks
Regex NoValidCharacters = new Regex("[^a-z\\s]*");
// delete all matching textparts
text = NoValidCharacters.Replace(text, "");

return text;

/// <summary>
/// decrypts the given string
/// </summary>
public string Encode(string plainText)
string CipherText = "";

// clean plainText
plainText = CleanString(plainText);

// Replace every letter in plainText by the corresponding cipher letter.
// The following checks whether the current letter is a blank, if yes it is kept,
// otherwise the cipher character is calculated.
foreach (char c in plainText)
CipherText += (c == ' ') ? ' ' : (char)(((c - 96) + (Offset - 96) + 25) % 26 + 97);

return CipherText;

public string Decode(string cipherText)
string PlainText = "";

// clean cipherText
cipherText = CleanString(cipherText);

// Replace every letter from cipherText by its corresponding plaintext letter.
// Again the following keeps blanks and calculates the plaintext letter otherwise.
foreach (char c in cipherText)
PlainText += (c == ' ') ? ' ' : (char)(((c - 96) - (Offset - 96) + 25) % 26 + 97);

return PlainText;


An exemplary call of the Caesar encryption could look as follows:

CaesarCiphering Caesar = new CaesarCiphering(false, 'b');
string CipherText = Caesar.Encode("zum");
string PlainText = Caesar.Decode(CipherText);

Tuesday, June 22, 2010

Determine Online (WAN) IP - Address

In the previous post I showed, how to determine the IP - address of the computer in the local network (in the LAN - Local Area Network).
In this post now I want to explain, how to get the online IP address of the computer. In the internet every connection node has its own IP - address, by which it is identified.
For the communication this one is important and not the local IP - address. This online IP is also called WAN (Wide Area Network) IP - address.
The connection nodes can be anything, computers, mobile phones or routers. Probably at home for you it is a router, since you probably are connected by a router to the internet, to which again multiple computers are connected.
Note that there is only one online IP per router, the computers behind it thus have all the same online IP and are identified by the router through their local IPs.

Also after an extended search I did unfortunately not find a .Net function determining this online IP -
so we have to use some tricks to get it.
There are websites, as for example, which can show the online IP.
We now simply read-out such a website with our C# application.
The following example uses a Webclient control, which downloads the sourcecode of the page.
In the source code of the page mentioned above the IP - address is saved in the following context:
<h1 class="ip"></h1>.
So the program scans the source code for appearances of the string <h1 class="ip"> and from there one for appearances of </h1>.
The string between this positions then is the WAN IP-address:
System.Net.WebClient IPGetter = new System.Net.WebClient();
// download source code of the page and save in variable SourceCode
string SourceCode = IPGetter.DownloadString(@"");

// look for the right starting position
int IPStartPosition = SourceCode.IndexOf("class=\"ip\">");
// look for the right ending position
int IPEndPosition = SourceCode.IndexOf(@"</h1>", IPStartPosition);
// read-out the ip - address between the markers
string IP = SourceCode.Substring(IPStartPosition + ("class=\"ip\">").Length, IPEndPosition - (IPStartPosition + ("class=\"ip\">").Length));

Monday, June 21, 2010

Determine Local Network IP-Address

To readout the IP-addresses the computer is using in the local networks, we first have to include System.Net via using:
using System.Net;
Then we create an instance of the class IPHostEntry, which saves address information for internethosts and set our own computer as host:
IPHostEntry Host = Dns.GetHostEntry(Dns.GetHostName());
In the property AddressList now all available IP-addresses of the host are listed. The local LAN IP then can easily be determined via:
string IPAddress = Host.AddressList[0].ToString();
If there exist multiple network adapters or connections on the cmoputer, the list contains multiple IP-addresses (for example there is nowadays IP6 next to the traditional IP4, a WLAN - connection uses also its own IP - address etc.).
To determine all these IPs, one can simply iterate through the list:

IPHostEntry Host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress IP in Host.AddressList)

Sunday, June 20, 2010

Show Icon in Taskbar (Trayicon)

If one adds the control NotifyIcon to a Windows Forms-Application, then while running the program a symbol is shown in the info area in the right part of the taskbar, a so called TrayIcon.
The icon can be determined via the property Icon of the control, the tooltip via the property Text.
If one further adds a control of type ContextMenuStrip, this menu can be added to the icon by setting the property ContextMenuStrip of the NotifiyIcon.
If the user then right clicks on the icon, the previously created menu from the connected control is then shown.

Saturday, June 19, 2010

Determine Groups of a User

In C# one can read-out the groups, which the currently logged in user belongs to, via the WindowsIdentity class, which was introduced in the previous post:
foreach (System.Security.Principal.IdentityReference group in System.Security.Principal.WindowsIdentity.GetCurrent().Groups)
This example outputs only cryptical names though, like {S-1-1-0}.
These numbers are the so called SIDs (Security Identifiers) of the group.
Luckily they can be translated in a different type via the function Translate(), possible types have to stem from the class System.Security.Principal.
If we take the type NTAccount, the groups are shown in a readable format:
foreach (System.Security.Principal.IdentityReference group in System.Security.Principal.WindowsIdentity.GetCurrent().Groups)

Now {S-1-1-0} becomes EVERYONE.

Determine Logged-In User

To determine, which user is currently logged in, is also no problem with the extensive .Net library.
The easiest way is via the class Environment:
string UserName = Environment.UserName;
The following command also reaches this goal, the containing class accesses the system a little more deeply and has interesting other uses, one of which I will show in the next post:
string UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

Thursday, June 17, 2010

Keyboard Shortcuts in the .Net Developer Environment

Today's post is easy, but probably very helpful.
I want to show you some keyboard shortcuts, which can be used in the .Net developer environment and with whom using it may become a bit faster.
Take a look:
  • Ctrl + Tab: Switches between the active open document (e.g. Form.cs and Form.cs [Designer)
  • F4: Hides the currently shown dropbox list (for code completion)
  • Ctrl + Shift + V: Same function as Ctrl + V (insert), but marks the inserted element
  • Ctrl + G: Jump to a line of code
  • Ctrl + Shift + S: Saves the complete project
  • Ctrl + S: Saves the current element
  • F7: Switches to the code view
  • Shift + F7: Switches to the designer view
  • Arrowkeys during marking a control in the designer: Moves the selected control in 1-pixel-steps
  • Ctrl + Arrowkeys during marking a control in the designer: Moves the selected control to the border of the form
  • Ctrl + Arrowkeys during marking a control in the designer: Resizes the selected control in 1-pixel-steps
  • F5: Runs the current project
  • F11: Runs the current project step-by-step
  • Ctrl + F5: Stops the running
  • F9: Set or delete breakpoint
  • F3: Searches the next occurence of a word
  • Ctrl + H: Open dialog "Hide & Replace"
Of course this list is not complete, if someone knows other useful hotkeys, feel free to post them in the comments

Wednesday, June 16, 2010

AntMe! - The Interactive Programming Game by Microsoft

Today I want to present you a very cool project by Microsoft: The game AntMe!.
In this game the player controls a ant colony, which has to hold its ground against other colonies and mean bugs on the search for food.
Special about this game is, that it is open source and that the player does not control its ants live during the game but has to program their behaviour before the game starts.
The game is suitable for beginner and experts, the basic commands are really easy but of course experts can use all their creativity to implement complex tactics.
For this there are a lot of possibilities, one can create different ant castes, the ants have to collect food and fight enemies, they can communicate with each other ...
For everybody who has gotten interested, here the link to the AntMe! - Homepage and finally a little screenshot of the game:

Tuesday, June 15, 2010

Readout Battery Charge Level, Battery Service Life etc.

From .Net framework version 2.0 upwards a new, very interesting class is available.
What was earlier only possible with API - calls is now pretty easy with .Net means.
I speak of the class PowerStatus, which is able to get information about the battery contained in the notebook.
The following example demonstrates the possibilites of this class, for example how to read the battery service life or the charge level:
            /* BatteryChargeStatus describes the current battery charge level, the result is an enumeration containing the following values:
            - High
            - Low
            - Critical
            - Charging
            - No SystemBattery
            - Unknown */

            string ChargeStatus = SystemInformation.PowerStatus.BatteryChargeStatus.ToString();

            // BatteryFullLifetime saves the maximal lifespan of the battery, meaning how long the battery can hold according to the manufacturer
            float FullLifeTime = SystemInformation.PowerStatus.BatteryFullLifetime;
            // reads the remaining capacity of the battery in percent
            float RemainingPercent = SystemInformation.PowerStatus.BatteryLifePercent;

            // reads the reamaining capacity of the battery in seconds
            float RemainingSeconds = SystemInformation.PowerStatus.BatteryLifeRemaining;

            // Determines, whether the notebook is connected to the power (Online) or running via battery (offline).
            string OnBattery = System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus.ToString();

Saturday, June 12, 2010

Platform Independent Path Descriptions

Yes, I have to admit, also I program not very cleanly. When describing paths I use the Backslash "\" out of comfort and readability reasons to separate folders. In C# though this has to be escaped by another Backslah or a prefixed "@", so I describe paths as follows:
string Pfad = @"C:\Dokumente und Einstellungen\Oliver";
But .Net is running also on other platforms (for Linux for example there exists the Mono - Project) and "\" does not work on all operating systems as a separator, the above path description could lead to an error there.
To guarantee platform independency the function Path.Combine() should better be used.
This combines the given strings to a path with valid separators.
So one could express above path as follows:
string Pfad = System.IO.Path.Combine("C:""Dokumente und Einstellungen""Oliver");
Pfad will then contain the following value on a Windows system:
"C:Dokumente und Einstellungen\\Oliver".
Alternatively one can also use directly Path.DirectorySeparatorChar to get the current separator character (System.IO has to be included via using).
string Pfad = "C:" + Path.DirectorySeparatorChar + "Dokumente und Einstellungen" + Path.DirectorySeparatorChar + "Oliver";
This also gives on Windows: "C:\\Dokumente und Einstellungen\\Oliver"

Thursday, June 10, 2010

Playing MP3 - Files

In the post Playing Wave Files I described, how to play Wave - Files with C#. Now I want to show how to play MP3 - files.
Due to the compressed format this is a bit more complicated, there is no direct "easy" command to play an MP3 - file, but still there are many possibilites.
On the one hand MP3 - files can be played via the API - function MCISendString(), but in my opinion the code is cumbersome and not easy to understand.
A very easy naive variant is to give System.Diagnostics.ProcessStart() the MP3 - file as parameter, the operating system then will open and play the file with the standard player:

System.Diagnostics.Process.Start(@"C:\Dokumente und Einstellungen\Oliver\Eigene Dateien\Eigene Musik\101-darius_and_finlay_and_shaun_baker_-_show_me_10_(dj_gollum_edit).mp3");
 Allowedly, this method is not very elegant.
Therefor I want to show you today how to include the Windows Media Player control, with which MP3 files and most other audio formats can be played.
The control can be added to the toolbox by right clicking on this and then selecting Select element .... In the opening window then switch to COM - controls and select Windows Meida Player.
This can now be placed like a button on the form.
If the player is just used for playing audio files, the property Visible can be set to false, so it is not visible on the form.
With the property URL the file to be played can be selected. Normally, the player then directly starts with playing the file.
With the property Ctlcontrols we can access the loaded data of the player, the functions start() and stop() serve the purpose of starting and stopping the playing manually.
Over settings some properties of the player, like the volume, can be modified.
In the following example an MP3 - file is loaded, the playing is stoppend and the application waits for 2 seconds. Afterwards, the player is set to full volume and the playing is continued:
Danach wird der Player auf volle Lautstärke gestellt und die Datei abgespielt:

axWindowsMediaPlayer1.URL = @"C:\Dokumente und Einstellungen\Oliver\Eigene Dateien\Eigene Musik\101-darius_and_finlay_and_shaun_baker_-_show_me_10_(dj_gollum_edit).mp3";
axWindowsMediaPlayer1.settings.volume = 100; // 0 = no sound, 100 = full volume;

Wednesday, June 9, 2010

Installing and Including the DirectX SDK

In more complex multimedia applications, for example in games, DirectX nowadays is most essential.
Luckily .Net provides also for this topic extended librariers.
For C++ and .Net languages there is the DirectX SDK.
With this definitely many cool applications can be created, in the future I will write some posts about it.
On Udo's Blogs you can find 2 interesting posts, describing how to use DirectSound and how to use Joysticks in C#.
But for today, as the title already says, I will just describe the installation and inclusion of the DirectX SDK, which can cause some problems (at least for me it did not work directly).
The newest version of this SDK is availale for download here. With Windows XP and .Net framework 4.0 I could though not use that file, I took the version of March.
After installation the SDK can be used, but in every project, where DirectX functions are to be used, references have to be set to the right DLL files, which can be added via Project - Add Reference. According to the documentation the corresponding files (e.g. Microsoft.DirectX) should be available in Add Reference in the tab .Net. For me though this was not the case, I had to include them manually.
To search references you want to include manually, you have to switch to the tab Browse and then select the corresponding files.
In my case the DLLs were placed in C:\WINDOWS\Microsoft.NET\DirectX for Managed Code. If you do not find them, just do a search for the file "Microsoft.DirectX.dll".
Okay, now you should be able to use the SDK, in the internet there are cool tutorials explaining its use and also saying which references are needed when.

Sunday, June 6, 2010

Find Out Application Path

Often it makes sense to store application relevant data in the folder of the application. But can to determine this path?
The following command returns the path to the application, without the name of the .exe file:

Playing a Wave - File

For playing Wave - files .Net provides the class System.Media.SoundPlayer.
This class can either be initialized with a path to the Wave - file in its constructor, or the path can be set by the property SoundLocation.
The following code plays a sample sound:
System.Media.SoundPlayer ExamplePlayer = new System.Media.SoundPlayer();
ExamplePlayer.SoundLocation = "C:\\Dokumente und Einstellungen\\Oliver\\Desktop\\wav\\MM_Lachen.wav";
In the post Playing MP3 - Files I show the use of the Windows Media Player control, which allows the playing of nearly all audio formats (so the title actually is a bit wrong). So anybody who wants to use more audio formats than just the Wave described here, is refered to that post.

Saturday, June 5, 2010

Get System Time

In the previous post I explained the basics of P/Invoke and how to change the system time by that.
Similarly, the system time can of course also be readout by an API - call:
    public class ZeitLesen
        struct str_Zeit
            public ushort Jahr;
            public ushort Monat;
            public ushort TagInDerWoche;
            public ushort Tag;
            public ushort Stunde;
            public ushort Minute;
            public ushort Sekunde;
            public ushort Millisekunde;

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern void GetSystemTime(out str_Zeit AktuelleZeit);

        public void LeseSystemzeit()
            str_Zeit Zeit = new str_Zeit();
            GetSystemTime(out Zeit);
            DateTime AktuelleZeit = new DateTime(Zeit.Jahr, Zeit.Monat, Zeit.Tag, Zeit.Stunde, Zeit.Minute, Zeit.Sekunde, Zeit.Millisekunde);
If one just wants to read the current date and time though, this can be accomplished with means of .Net much easier by using the class DateTime:
DateTime CurrentDate = DateTime.Now;

Change System Time

To change or read the clock of the pc, the .Net framework provides no in-house version. But with all .Net languages the functions of the Win32-API can be used.
The Win32-API is a very mighty programming interface, which provides functions for programming for Windows.
The mostly systemclose functions are all written in C or Assembler and are saved in dll - files.
Luckily, there also is a function to manage the system time, which we can include in our C# - application. The including of external functions is called Platform Invoke (P/Invoke).
Now to the code:
To be able to include DLLs, the following using - directive is necessary:
using System.Runtime.InteropServices;

The external function to set the system time is made known to the program eventually as follows:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetSystemTime(ref str_Zeit neueZeit);

The function SetSystemTime() then can be called as a normal function. As parameter it expects an object of the type of the structure str_Zeit, which we define ourselves:
struct str_Zeit
            public ushort Jahr; // year
            public ushort Monat; // month
            public ushort TagInDerWoche; // day in week
            public ushort Tag; // day
            public ushort Stunde; // hour
            public ushort Minute; // minute
            public ushort Sekunde; // second
            public ushort Millisekunde; // millisecond
This structure is a replication of the type which the function expects - every structure with 8 unsigned 16-bit integers suffices the requirement.
The complete code could finally look like this (a call of the function SetzeSystemzeit() with a date object as parameter changes the system time to the given value):

public class ZeitSetzen
        struct str_Zeit
            public ushort Jahr;
            public ushort Monat;
            public ushort TagInDerWoche;
            public ushort Tag;
            public ushort Stunde;
            public ushort Minute;
            public ushort Sekunde;
            public ushort Millisekunde;

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool SetSystemTime(ref str_Zeit neueZeit);

        public void SetzeSystemzeit(DateTime neueZeit)
            str_Zeit Zeit = new str_Zeit();
            Zeit.Jahr = (ushort)neueZeit.Year;
            Zeit.Monat = (ushort)neueZeit.Month;
            Zeit.TagInDerWoche = (ushort)neueZeit.DayOfWeek;
            Zeit.Tag = (ushort)neueZeit.Day;
            Zeit.Stunde = (ushort)neueZeit.Hour;
            Zeit.Minute = (ushort)neueZeit.Minute;
            Zeit.Sekunde = (ushort)neueZeit.Second;
            Zeit.Millisekunde = (ushort)neueZeit.Millisecond;
            SetSystemTime(ref Zeit);
Be careful when using Windows Vista, 7 and 8: To change the system time the program needs administrative rights. How that can be achieved, is explained in this post.

Friday, June 4, 2010

Create Random Numbers

Even if it is maybe unexpected, random parameters do play an important role in the design of many programs. Especially in games random values are highly valued.
But a computer cannot create "real" random numbers, only pseudo-random numbers, since the behaviour of a today's computer is deterministic and has no random elements in it.
Good pseudo-random numbers though look statistically random, meaning every possible number has about the same chance of appearance and the order of appearance is hard to see through. But, in fact they are created by a deterministic algorithm.
Who has become interested in this topic is heartly invited to keep reading somewhere else, here though I just want to list the code.
In C# the class Random is responsible for random numbers. It can either be initialized parameterless or with a seed (that is the number the creation algorithm uses to calculate the first number).
The function Next() finally is the function, which gives us our random number. It has 3 overloadings, which I want to show in the following example:

Random Rnd = new Random(); // initializes the random class
int RndNr1 = Rnd.Next();
int RndNr2 = Rnd.Next(10000);
int RndNr3 = Rnd.Next(0, 2);

The parameterless call saves in RndNr1 a non-negative random number. The random number can be any number of all possible integer - values.
If the function is given a parameter, it is this the exclusive upper bound, so all interger numbers below this bound can appear.
If Next() is called with 2 parameters, the first one is the inclusive lower bound and the second one again the exclusive upper bound. So RndNr3 gets either the value 0 or 1 in the above example.
The created random numbers looked as follows in the example:
RndNr1 = 304286837
RndNr2 = 9060
RndNr3 = 0

Wednesday, June 2, 2010

Use Clipboard

In C# you can easily access the clipboard, inserting or reading data.
In this post I will describe how to do so, just focussing on text and images though, which is anyways probably the most used feature.
For managing the clipboard the class System.Windows.Forms.Clipboard is responsible.
The function ContainsText() returns true if text is available in the clipboard, otherwise false.
Consequently ContainsImage() has the same meaning just with images.
GetText() gets the copied text, SetText() sets it.
Similiarly, GetImage() gets the copied image, SetImage() copies one in the clipboard.
The following example code checks on runtime the content of the clipboard, if text is available, this is copied to the textbox textBox1, if an image is available, this is shown in pictureBox1:
if (System.Windows.Forms.Clipboard.ContainsText())
textBox1.Text = System.Windows.Forms.Clipboard.GetText();
if (System.Windows.Forms.Clipboard.ContainsImage())
pictureBox1.Image = System.Windows.Forms.Clipboard.GetImage();

Tuesday, June 1, 2010

Serialize Objects

Serialization is an efficient concept for converting and subsequently saving objects.
In many programs the entered data is not thought for unique use, but supposed to be reused the next time when the program is executed.
Accordingly, data has to be saved. With streams data can be written in files or the memory. StreamWriter and StreamReader are probably the most known representatives, they excel in reading and saving text files.

But, saving data as text, is in most cases costly, unsafe and not exactly elegant.
In .Net there are possibilites to convert data in a specific format and to write them in a file - it can be serialized. Basically, there are the classes BinaryFormatter, SoapFormatter and XmlSerializer.
With XmlSerializer data can be serialized in the XML - format, with SoapFormatter in the Soap - format.
BinaryFormatter serializes object into a binary format, for this class I want to post an example:
We construct a minimal employee management as example. Employees are saved as instances of the class Employee:
public class Employee
static int GlobalID = 0;

int ID;
string Surname, Prename;
double Salary;
string Email;

public Employee(string surname, string prename)
ID = GlobalID++;
Surname = surname;
Prename = prename;
The attribute [Serializable] is necessary, so that the class can be serialized.
For the easy example the serialization and deserialization happens on loading the form:
private void Form1_Load(object sender, EventArgs e)
List DemoList = new List();
DemoList.Add(new Employee("Wurst", "Hans"));
DemoList.Add(new Employee("Mustermann", "Max"));


List DeserializedList = DeserializeEmployees();
In this function at first a list of the type Employee is created and "Hans Wurst" and "Max Mustermann" are added.
Then a function to serialize this data is called, which looks as follows:
private void SerializeEmployees(List employees)
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(Application.StartupPath + "\\list.emp", FileMode.Create);
bf.Serialize(fs, employees);
The class BinaryFormatter provides us with the function Serialize(), which expects as parameter a stream as well as the object which is to be serialized.
In this case the list employees is written via FileStream to the file "list.emp" in the application directory.

In Form1_Load(), afterwards the process is reversed and a function for deserialization is called:
private List DeserializeEmployees()
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(Application.StartupPath + "\\list.emp", FileMode.Open);
List Result = (List)bf.Deserialize(fs);
return Result;
BinaryFormatter provides a function Deserialize() as well, which creates an object from the given stream. This is then converted to the requested type (here List) and returned.

In the end, the list DeserializedList in Form1_Load() contains the same employees as the original list.