On this blog I regularly publish articles with tips and tricks for the programming language C# .Net.
C# is a modern, object-oriented programming language, which fully ultilizes the possibilites of the .Net framework. I also write about app programming for Android via C#, as well as PHP and Matlab. The difficulty of this blog is supposed to be variable, I hope for beginners and experts there is always something to look for.
If you have questions or suggestions, I am happy about your emails.

Thursday, September 30, 2010

In a previous post I presented a little programming riddle. Now the solution:
The "gadget" I was looking for is a full adder.
That is a digital circuit, which can add 3 binary numbers. So the circuit has 3 inputs for the 3 numbers to be added and 2 outputs, s and c.
The output s (sum) outputs the digit with low value, the ouput c (carry) the one with high value.
You can find more detailed information on wikipedia.
In the code class from the riddle the calculation is started by the method ABC(). This expects 3 strings as parameters, which expect the binary numbers to be added.
The letter "x" represents digit 0, "y" digit 1. First now DEF() is called, in which is checked in multiple ways, whether really only "x" and "y" are given as inputs.
If a not valid input is given, the program returns "d", representing error. In ABC() otherwise the sum of the 3 numbers is calculated and the result returned as a string. The left digit of the result string is the lower one of the sum (s), the right one the high (c).
In the result now an "a" stands for a 0, a "b" for a 1.

Wednesday, September 29, 2010

In the namespace Microsoft.VisualBasic.Devices there is the class Computer, which provides some very interesting functions. Most of them can probably be implemented differently too (with "real" C# functions), still I want to have a look at this class in this post out of curiosity.
To be able to use the class, a reference to Microsoft.VisualBasic (Project - Add Reference, tab .Net) has to be added and this has to be included by using Microsoft.VisualBasic.Devices.
The Computer class can be used to manipulate objects, which concern the own computer, the scope of application ranges from Audio over keyboard and mouse to ports.
Here some examples, what can be done with it:

Playing .wav files (the "C# variant" was describedi in this post):

// using Microsoft.VisualBasic; has to be included for this example as well!
Computer computer = new Computer();
computer.Audio.Play("pfad zur .wav - Datei", AudioPlayMode.Background);

The function Play() expects as first parameter the path to the file to be played, and as second one the playmode.
The function used here plays the sound in the background while the program continues running. Furtheremore there are the modes WaitToComplete (the program waits for the sound) and BackgroundLoop (the sound is repeatedly played in the background).

Tuesday, September 28, 2010

In today's post I want to describe how to record sound from a microphone. In C# we therefor need the WinAPI function mciSendString().
The Media Control Interface (MCI) is an interface, which provides commands to play and record multimedia elements. With the previously described function these commands can be send to the computer and thus be processed there.
The function mciSendString() is contained in the file winmm.dll and can be included as follows (to include external libraries usingSystem.Runtime.InteropServices is needed):

To control the microphone we only need the 1st parameter and handover "" respectively 0 for the others.
To start the recording, we then need the commands "open new Type waveaudio Alias recsound" and "record recsound", to stop it "save recsound" and "close recsound".
The code of a Windows Forms Application having 2 buttons to start and stop the recording could look as follows:

Monday, September 27, 2010

On the occasion of the 100th post I prepared a little riddle.
The presented class describes the function of a "gadget" of the field of technical computer science, whoever gets this first, is the winner.
The class is programmed chaotically on purpose, when using it the function ABC() is called with 3 parameters.
Now the code:

Tuesday, September 21, 2010

The HTML source code of a website can be readout by the class WebClient. This provides different functions to send and receive internet ressources and is located in the namespace System.Net, using System.Net is required.
To get the source code 2 functions can be used, DownloadString(string url) and DownloadFile(string url, string filename).
The first one downloads the source code of the given address and returns this as a string, the second saves the source code in the given file.
The following example reads the source code of the RSS feed of this blog:

In some cases for the right display the coding has to be changed. The WebClient downloads the requested resource in the form of byte arrays, these then are converted with some coding (the most common one for example is UTF-8) into a string.
To change the coding, before downloading the property Encoding of the class WebClient has to be changed.

Sunday, September 19, 2010

The versions of the .Net framework differ in parts substantially in their functionalities, the current version 4 provides much more features than version 1.
Core component of the .Net framework is the so called Common Language Runtime (CLR), which is the runtime environment, in which the programs run.
To determine this version nummer, the class System.Environment.Version is needed.
The following line of code reads out the installed version of the CLR, in which the program runs:

string CLRVersion = System.Environment.Version.ToString();

Note though, that the version of the Common Language Runtime is not identical to the version of the .Net framework!
The .Net versions 1.0 and 1.1 use the CLR version 1.0, the .Net framework 2.0, 3.0 and 3.5 the version 2.0 and the current .Net framework 4.0 uses CLR 4.0.

Tuesday, September 14, 2010

Attention: This post describes the basic of receiving emails. At the time of this post this was possible without the use of SSL, nowadays this is required by most providers Therefore I explain the receiving of emails with an SSL connection in this new post. There also the usage of an IMAP server is described - in this post only a POP3 server is considered.

In a previous post I showed, how to send emails with C#.
Today is about receiving emails using C#.
Sending was relatively easy, since .Net provided methods to connect to an SMTP server, over whcih emails can be send.
Receiving is a bit harder, we have to logon to the incoming mail server and send the right commands to check and geet emails.
Clients can get emails from the mail server usign the POP3 or IMAP protocoll. IMAP provides more functionality, the most free mail providers like WEB or GMX though use POP3.
The code shown here also works with the POP3 protocoll.
A POP3 server waits for requests on a specific port (mostly 110). A client then can input username and password there and then send commands, which all have to be separated by a linebreak.
The server sends to every command and answer and waits for input, if necessary.
We impement the POP3 server in C# with a TcpClient and send the commands via a NetworkStream.
Before I go into more details of the code, first I want to explain the basic process of communication with the incoming mail server:
After setting up the connection this first expects a username, which we set with the command "USER username". Then the password follows with "PASS password".
To list all mails available on the server the command "LIST" is needed. In response to that, the server sends all messages as an answer - for each ID and size of the message, per line one message, the end of a line is characterized by ".".
One specific email can be retrieved via "RETR id". The server then answers with the complete content.
To terminate the connection to the server, there is the command "QUIT".

Now to the implementation:

To represent the POP3 server an instance of the class TcpClient. To send the commands described above, we use the class NetworkStream, which connects to the stream of the server.
Since computers work with binary number, but we humans understand words over our alphabet better, we have to convert the commands to bytecode, which can be done with the class ASCIIEncoding.
An instance of the class StreamReader eventually is used to read the answers sent by the server.
The following program demonstrates a communication with the incoming mail server, the programming style (using global variables etc.) is not the best, but I think, the basic principles should become clear quickly in this way.
The program consists of 4 functions, which are all called from Form1_Load():

// StringBuilder for a quicker loading of the mail content
StringBuilder FullEmailContent = new StringBuilder();

/* as long as not "." is read, the email is not at its end, write read lines in the StringBuilder */string TempLine = StreamListener.ReadLine();
while (TempLine != ".")
{
FullEmailContent.Append(TempLine + "\r\n");
TempLine = StreamListener.ReadLine();
}

/* as long as not "." is read, there are more emails available on the server, iterate through them and output ID + size */string CurrentMessage = StreamListener.ReadLine();
while (CurrentMessage != ".")
{
MessageBox.Show(CurrentMessage);
CurrentMessage = StreamListener.ReadLine();
}
}

}
}

The function ReadMailContent() writes the content of the read mail in a RichTextBox (which has to be available on the form), since this control supports basic formattings (like links and split lines), like they occur in emails.
When using the function Connect(), the parameters have to be replacecd by own ones.
For the free mail providers WEB and GMX the following parameters are needed:

Thursday, September 9, 2010

Strings are mostly represented as values of the type String in C#.
If a string is initialized, it is not changeable anymore. Operations which work on Strings (as for example Replace() or Trim()), leave the original unchanged and create instead a copy which they then return.

To use changeable strings in .Net, we need the class StringBuilder. Instances of this class are created by the operator new and can dynamically be changed. Operations then work on the actual object:

DynamicString contains after the replacement the value "Replaced", as with a String this was not the case.
As you can see in the code, a string of type StringBuilder has to be explicitely converted to String, if a String is needed.

The technical details though are probably not that interesting, one very interesting feature of the class StringBuilder is its speed.
Generally, the processing of strings of the type String is pretty slow. If you for example read a text file and write its content to a String, this action takes some time.
The following code example appends 100000 times the wort "zeichenkette":

When working with longer strings thus you should definitely use the class StringBuider, because an immense speedbost comes with that - but to be fair one has to also say, that String is more effective or short strings.
You can use the same trick, when writing longer texts in a TextBox. The property Text is also of the type String, so it can be more effective, to build the contents together using StringBuilder, and then assigning the whole to the textbox.

Tuesday, September 7, 2010

The programming language C# supports 3 types of comments:
Single line comments, multi line comments and documentation comments.
Single line comments are introduced by the symbol // and stretch till the end of the current line:

namespace ConsoleApplication1 // this is a single line comment

Multi line comments stretch between the symbols /* and */ and can thus stretch over multiple lines:

/* This is a comment,* which stretches over multiple* lines. */

Finally there are documentation comments, which are started by the symbol ///.
Actually they are a topic for themselves and do not belong to the actual code comments, since they have a XML structure and are used for an automatic code commentation.
Documentation comments are put in front the actual object they are supposed to comment, the development environment automatically adds some tags then.
I do not want to go deeper in this topic, but just give an example how the main function could be commented like:

/// <summary>/// main function of the program/// <summary>/// <param name="args">commandline arguments the program was called with<param>

Monday, September 6, 2010

Attention: This post describes the basics of sending emails. At the time of this post this was possible without the help of SSL, nowadays though this is required by most providers. Thus I explain the sending of emails with an SSL connection in this new post.

Surprisingly, emails can be send with only a few lines of code in C#.
The class System.Net.Mail provides the necessary functions and therefor has to be included in the project via using.
The new email can then be created as an instance of the class MailMessage.
The sender address is set by the property From, which expects an object of type MailAddress. The properties To, Body and Subject are of type string and describe the recipient address, the message text and subject of the message.
Zu send the mail an instance of the class SmtpClient is needed.
This expects the address of the outgoing mail server in the constructor (it has to be an SMTP server) as well as the port to be used.
Some mail servers expect a logon before the sending of emails. For that an instance of the class System.Net.NetworkCredential has to be created, in the constructor username and password are set.
The instance is then given to the property Credentials of the class MailMessage. The following program is a little console application, which creates an email from the inputted data and sends it:

This method to send emails works with all email providers, which have an STMP outgoing mail server.
It is important, that as a sender the actual email address is given and the server information are correct (they are the same as in an email program, e.g. Outlook in account settings).
Most providers require credentials to send emails, therefor the property Credentials has to be set.

Friday, September 3, 2010

In C# there are, like in many programming languages, basically 2 datatype variants: There are value types and reference types.
Variables, which base on value types, save the actual value of the variable. In contrast to that, variables which base upon reference types, only save a reference to the memory address of the variable.
Another difference between these types is: Value types are saved in the stack, reference types in the heap.
If you copy a value type, the value gets copied, after that exist 2 variables with the same value. If you copy the value of a reference type though, only the reference is copied, afterwards there are 2 references point on the same value in the heap. So if you change the value of the original reference variable, you also change the value of the copied reference variable, as they point to the same memory address.
The most datatypes in C# are value types, as for example byte, int and char. Reference types are generally only classes and arrays.

So why do we need to know all this when programming?
Most essential is this knowledge, when calling functions with parameters.
The following easy example should illustrate this:

There are 2 functions, ResultValue() and ResultReference(), which are called from Form_Load().
The first expects 2 variables of the type integer as parameter, which are the numbers 8 and 3. In the first function the first given number (8) is divided by 2 and the product of both numbers (4 * 3 = 12) is returned.
In the second function ResultReference() also the first number of the array is divided by 2 and the product returned (4 * 3 = 12).
However, the integer parameters of the first method are value types, so when handing them over to ResultValue(), a copy of them is created in the memory. The division is only done with the copy, the original number NumberA still is 8 after returning from the function.
The array given to ResultReference() is a reference type, when handing the parameter over to the function only the reference is copied, the variable still points to the same memory address in the heap. If the first number of the array is divided by 2, after returning from the function also the original number in the array is 4.

To change this behaviour, there is the keyword ref. If this is put in front of the value type parameter, this is created as a reference type parameter, when handing it over to the function, no value copy is created, but the reference to the original value:

// value typesint NumberA = 8;int NumberB = 3;

int NumberC = ResultValue(ref NumberA, ref NumberB);

In the above example then the original variable, NumberA, is divided by 2.
To convert value types to reference types there is no corresponding keyword, when handing over the parameters manually a true copy of the object, a deep copy, has to be created.

Thursday, September 2, 2010

Lists are represented by the type List<T> in the .Net framework, whereby T denotes any type, meaning lists can be typified, so that they accept only objects of one type to grant data consistence.
In this post I will explain how to sort lists, in the previous post I had shown how to sort arrays. Since I started explaining sorting there, this post will be slightly shorter.
As explained there for arrays the static function Array.Sort() was used, for lists the instance function has to be used. That means, that for arrays we could use the function of the not instanced class Array, for lists we have to call this function of a instance of the class List, so for example MyCreatedList.Sort().
The following source code sorts the list TestList in decreasing order:

List<int> TestList = new List<int>(){5, 1, 2, 4, 3}; // short way to initialize and fill lsits
TestList.Sort(); // sort the list increasing
TestList.Reverse(); // reverses the order of the elements

Wednesday, September 1, 2010

A really important function when handling data is to sort it.
The .Net framework provides a lot of methods to do that, arrays for example can be sorted easily via Array.Sort().
This sorts the given array in increasing order using the Quicksort algorithm, which is one of the best sorting algorithms.
The following example sorts an integer array in increasing order (when using strings or characters these are sorted alphabetically):

The result is finally directly saved in TestArray, meaning the data manipulation has been done in the array itself, as in .Net arrays are reference types.
To order the array in decreasing order, after sorting it the function Array.Reverse() can be called to reverse the array:

Array.Reverse(TestArray);

For readers interested in the theory and also for publicity in my own cause, here you find an Android app by me which visualizes different sorting algorithms (amongst others Quicksort).