Thursday, September 30, 2010

Solution of the Riddle

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

Computer class in Microsoft.VisualBasic.Devices

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).

Readout current time and date (see this post for an alternative):

Computer ThisComputer = new Computer();
MessageBox.Show(ThisComputer.Clock.LocalTime.ToString());

Determine RAM size:

Computer ThisComputer = new Computer();
ulong RAMSize = ThisComputer.Info.TotalPhysicalMemory;

Tuesday, September 28, 2010

Record Sound from the Microphone

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 using System.Runtime.InteropServices is needed):

[DllImport("winmm.dll")]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

The parameters have the following meaning:
  • lpstrCommand: MCI command to be send
  • lpstrReturnString: if necessary, a buffer saving the result
  • uReturnLength: size of this buffer
  • hwndCallback: window handle, which shall be notified on return

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("winmm.dll")]
        private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

        public Form1()
        {
            InitializeComponent();
        }

        // start the recording
        private void button1_Click(object sender, EventArgs e)
        {
            mciSendString("open new Type waveaudio Alias recsound""", 0, 0);
            mciSendString("record recsound""", 0, 0);
        }

        // stop the recording
        private void button2_Click(object sender, EventArgs e)
        {
            mciSendString("save recsound C:\\records\\record1.wav""", 0, 0);
            mciSendString("close recsound""", 0, 0);
        }

    }
}

Monday, September 27, 2010

Riddle: What Does This Program Do?

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:

    public class CrazyTool
    {
        public string ABC(string a, string b, string c)
        {
            if (!DEF(a, b, c))
                return "d";

            if (a == "x")
            {
                int d = 0;
                if (b == "x")
                    d = 0;
                else
                    d = 1;
                int e = d + int.Parse(c.Replace('x', '0').Replace('y', '1'));
                switch (e * 3)
                { 
                    case 0: return ("aa");
                    case 3: return ("ba");
                    case 6: return ("ab");
                }
            }
            else
            {
                int f = 0;
                if (b == "x")
                    f = 0;
                else
                    f = 1;
                int g = f + int.Parse(c.Replace('x', '0').Replace('y', '1'));
                switch (g * 3)
                { 
                    case 0: return ("ba");
                    case 3: return ("ab");
                    case 6: return ("bb");
                }
            }

            return "d";
        }

        private bool DEF(string a, string b, string c)
        {
            if (a != "x" && a != "y")
                return false;
            if (((byte)(b.ToCharArray()[0]) != 120 && ((byte)(b.ToCharArray()[0]) != 121)))
                return false;
            Regex r = new Regex("[xy]");
            if (!r.IsMatch(c))
                return false;
            return true;
        }
    }

Saturday, September 25, 2010

Determine Number of Connected Screens

The number of to the computer connected monitors can be determined in different ways, one is to use the class SystemInformation:

int MonitorsCount = SystemInformation.MonitorCount;

Tuesday, September 21, 2010

Get HTML Source Code

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:

WebClient Webclient1 = new WebClient();
string SourceCode = Webclient1.DownloadString("http://csharp-tricks.blogspot.com/feeds/posts/default?orderby=updated");

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

Find Out CLR Version

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

Receive Emails

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():

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net.Sockets;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        TcpClient POP3Server = new TcpClient(); // TcpClient for the connection to the server
        NetworkStream POP3Stream; // network stream for the connection with the server
        StreamReader StreamListener; // StreamReader to convert byte data to readable text
        byte[] CommandBuffer = new byte[1024]; // byte Array for sending commands to the server
        ASCIIEncoding AscEncoding = new ASCIIEncoding(); // ASCII encoding to encode ASCII commands to byte data

        private void Form1_Load(object sender, EventArgs e)
        {
            if (Connect("hosturl", port, "benutzername""password"))
            {
                /* remove the following comment to get all mails from the server */
                // ListMails();
                /* remove the following comment to read the context of message with ID id */
                // richTextBox1.Text = ReadMailContent(id);
                Quit();
            }
        }

        /// <summary>
       /// tries to connect to the given POP3 server
        /// </summary>
        /// <param name="server">URL of the server</param>
        /// <param name="port">port of the server</param>
        /// <param name="user">username</param>
        /// <param name="password">password</param>
        /// <returns>true if connection successful, otherwise false</returns>
        private bool Connect(string server, int port, string user, string password)
        {
            POP3Server.Connect(server, port); // connect
            POP3Stream = POP3Server.GetStream(); // create network stream
            StreamListener = new StreamReader(POP3Stream); // create StreamReader from network stream

            if (POP3Server.Connected) // connection succesful
            {
                MessageBox.Show(StreamListener.ReadLine());

                // send username
                CommandBuffer = AscEncoding.GetBytes("USER " + user + "\r\n");
                POP3Stream.Write(CommandBuffer, 0, CommandBuffer.Length);
                MessageBox.Show(StreamListener.ReadLine());

                // send password
                CommandBuffer = AscEncoding.GetBytes("PASS " + password + "\r\n");
                POP3Stream.Write(CommandBuffer, 0, CommandBuffer.Length);
                MessageBox.Show(StreamListener.ReadLine());

                return true;
            }

            return false;
        }

        /// <summary>
       /// terminate connection to the POP3 server
        /// </summary>
        private void Quit()
        {
            // send quit command
            CommandBuffer = AscEncoding.GetBytes("QUIT\r\n");
            POP3Stream.Write(CommandBuffer, 0, CommandBuffer.Length);
            MessageBox.Show(StreamListener.ReadLine());
        }

        /// <summary>
       /// reads the content of the given mail
        /// <summary>
        /// <param name="mailNr">ID of the mail which should be read</param>
        /// <returns>content of the mail</returns>
        private string ReadMailContent(int mailNr)
        {
            // send command to retrieve the correspondign mail
            CommandBuffer = AscEncoding.GetBytes("RETR " + mailNr + "\r\n");
            POP3Stream.Write(CommandBuffer, 0, CommandBuffer.Length);

            // 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();
            }

            return FullEmailContent.ToString();
        }

        /// <summary>
       /// Lists all mails available on the server
        /// </summary>
        private void ListMails()
        {
            // send command to list all mails
            CommandBuffer = AscEncoding.GetBytes("LIST\r\n");
            POP3Stream.Write(CommandBuffer, 0, CommandBuffer.Length);

            /* 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:

WEB:
hosturl: pop3.web.de
port: 110
username: Email address without the ending @web.de
passwort: you should know that

GMX:
hosturl: mail.gmx.net
port: 110
benutzername: complete email address
password: you should know that

Thursday, September 9, 2010

String vs Stringbuilder

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:

StringBuilder DynamicString = new StringBuilder("Replace me");
DynamicString.Replace("Replace me""Replaced.");
MessageBox.Show(DynamicString.ToString());

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":

string OrdinaryString = "";
for (int i = 0; i &lt; 100000; i++)
{
    OrdinaryString += "zeichenkette";
}

The program takes for execution on my laptop over a minute, using a string.
The same can be done using StringBuilder without noticeable time passing by!

StringBuilder BetterString = new StringBuilder();
for (int i = 0; i &lt; 100000; i++)
{
    BetterString.Append("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

Comments in C#

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

Send Emails Using C#

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.

Hinweis: Dieser Post erklärt die Grundlagen des Sendens von Emails. Zur Zeit des Posts war dies noch ohne SSL möglich, heutzutage ist dies jedoch meist Voraussetzung. Daher erkläre ich das Senden von Emails unter Benutzung einer SSL-Verbindung in diesem neuen 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:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail; // add

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MailMessage Email = new MailMessage();

            Console.WriteLine("Sender:");
            MailAddress Sender = new MailAddress(Console.ReadLine());
            Email.From = Sender; // set sender

            Console.WriteLine("Receiver:");
            Email.To.Add(Console.ReadLine()); // add receiver

            Console.WriteLine("Subject:");
            Email.Subject = Console.ReadLine(); // add subject

            Console.WriteLine("Message text:");
            Email.Body = Console.ReadLine(); // add message text

            Console.WriteLine("Outgoing mail server:");
            string ServerName = Console.ReadLine();
            Console.WriteLine("Port:");
            string Port = Console.ReadLine();

            SmtpClient MailClient = new SmtpClient(ServerName, int.Parse(Port)); // set outgoing mail server

            Console.WriteLine("Credentials needed?"); // "Yes" or "No" possible

            bool LoginNecessary = (Console.ReadLine() == "Yes");
            if (LoginNecessary)
            {
                Console.WriteLine("User name:");
                string UserName = Console.ReadLine();
                Console.WriteLine("Password:");
                string Password = Console.ReadLine();
                System.Net.NetworkCredential Credentials = new System.Net.NetworkCredential(UserName, Password);

                MailClient.Credentials = Credentials; // set credentials
            }

            MailClient.Send(Email); // send emails

        }
    }
}

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

Difference Between Value Types and Reference Types

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:

        private void Form1_Load(object sender, EventArgs e)
        {
            // value types
            int NumberA = 8;
            int NumberB = 3;

            // reference types
            int[] Numbers = { 8, 3 };

            int NumberC = ResultValue(NumberA, NumberB);
            int NumberD = ResultReference(Numbers);
        }

        private int ResultValue(int numberA, int numberB)
        {
            numberA /= 2; // divide numberA by 2
            return numberA * numberB;
        }

        private int ResultReference(int[] numbers)
        {
            numbers[0] /= 2; // divide first number in the array by 2
            return numbers[0] * numbers[1];
        }

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 types
            int 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

Sort Lists

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

Sort Arrays

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):

int[] TestArray = new int[] { 5, 3, 4, 1, 2 }; // short way to initialize arrays
Array.Sort(TestArray);

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).