Sunday, November 28, 2010

Check If Network Connection Exists

We use the class System.Net.NetworkInformation.NetworkInterface to check, if the computer has a connection to a network.
The function needed for that is GetIsNetworkAvailable(). It checks, whether the computer is connected to a network by any adapter. However, it does not check, whether this network is working or having a connection to the internet.
The following code sample checks connectivity:

bool NetworkAvailable = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

Thursday, November 25, 2010

Assertions

Assertions are methods to verify the correctness of a program. They are conditions, which throw an exception when not met.
Assertions mostly preceed sections of the code, which do not work without meeting the condition. If an assertion is thrown, the programmer knows, that he has to catch the exception in this area.
The expression System.Diagnostics.Debug.Assert() can be used in the debug configuration, System.Diagnostics.Trace.Assert() in the release version. As example a function for division, which prohibits a division through 0:

public double divide(double divident, double divisor)
{
    System.Diagnostics.Debug.Assert(divisor != 0);
    return (divident / divisor);
}

Tuesday, November 23, 2010

String Representation of a Class Via Overloading ToString()

All objects and structures in C# inherit implicitely of the class Object. This class provides basic functions like Equals() (checks for equality) and ToString() (displays the class as string).
That means, by default all classes and structures implement these functinos too.
Most will probably know the notation Console.WriteLine(x.ToString());, it prints the value of the integer as a string. Many classes created by programmers also inherit from Object, therefore they also implement ToString(). But, this will probably not lead to the desired result. When called, the compiler simply prints the type name of the class as string, where should it know how to display the value of an instance as a string.
For that reason it might be clever to override the function ToString() in own classes. For overriding, in the child class a function with the same signature as in the father class has to be created. If now the function is called with an instance of the child class, the call is not forwarded to the base class anymore, but directly done in the child class.
The following console application implements a little class Employee, in which the function ToString() is overridden.
In the modified version, name and salary of the employee are printed out:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        Employee TestEmployee = new Employee("Hans Meier", 1000);
        Console.WriteLine(TestEmployee.ToString());
    }
}

class Employee
{
    public string Name;
    public int Salary;

    public Employee(string name, int salary)
    {
        Name = name;
        Salary = salary;
    }

    public override string ToString()
    {
        return "Name: " + Name + ", Salary: " + Salary + ".";
    }
}

Sunday, November 21, 2010

A Quine With C#

A quine is a program, which prints it complete source code as output.
So for example, if the source code is

class Quine
{
    static void Main()
    {
        System.Console.WriteLine("This is no quine (yet).");
    }
}

The program had to output exactly this text. Depending on your experience in this topic, you will maybe find the task to write a quine as easy, hard or even impossible.
(For people interested in theory: It is guaranteed that quines exist in all "higher" programming languages, so for example, C, C#, Java etc. - since all these languages are Turing complete, and in Turing complete languages quines can be realised.)
If you start the problem naively, you could maybe suppose it is quickly solved. First you print the code until the line WriteLine(), then this line and finally the rest.
But hang on - we have to print the whole source code, including all WriteLine().
So if you write for example
string test = "abc";
and print this line via WriteLine()
WriteLine("string test = \"abc\";");
, in the next step this line has to be printed as well.
To avoid infinite recursion, the trick is to save the code in a string and then just print this string. Furthermore we also use, that in C# there are placeholders in the WriteLine() command which can be replaced later.
I now show the code of a quine written by me, the abstract requirements from above then hopefully get clear:

class Quine
{
    static void Main(string[] args)
    {
        string s = "class Quine {3} {0} {3} static void Main(string[] args) {3} {0} {3} string s = {2}{1}{2}; {3} System.Console.WriteLine(s, System.Convert.ToChar(123), s, System.Convert.ToChar(34), System.Environment.NewLine, System.Convert.ToChar(125)); {3} {4} {3} {4}";
        System.Console.WriteLine(s, System.Convert.ToChar(123), s, System.Convert.ToChar(34), System.Environment.NewLine, System.Convert.ToChar(125));
    }
}

Saturday, November 13, 2010

Write to the Windows Event Viewer

The Windows Event Log saves many information relevant to the system (e.g. the starting / stopping of clients, to name just one of many fields of application).
With C# we can easily add entries to this with the class System.Diagnostics.EventLog, for example to monitor the program flow. For that we have to first create a new source in the event log (if not already existing).
If there is not yet an entry of the application, so if we create a new source, we have to specify, to which category the program belongs to. For example there are the categories "Application", "Security", "Installation" etc.
The writing of the event is done via the function WriteEntry(). This expects the source as the first parameter, the category as second and optionally as the third the type of the event (e.g. warning, information, error ...)
For writing in the Event Log the programm will probably need administrative rights, how to do that you can read there.
The following code sample writes a short information text to the Windows Event Log (using System.Diagnostics; is required):

        private void Form1_Load(object sender, EventArgs e)
        {
            string Source;
            string LogType;
            string LogEvent;

            Source = "Event Log C# Demo";
            LogType = "Application";
            LogEvent = "I like this blog.";

            if (!EventLog.SourceExists(Source))
                EventLog.CreateEventSource(Source, LogType);

            EventLog.WriteEntry(Source, LogEvent, EventLogEntryType.Information);
        }

Monday, November 8, 2010

Cancel / Delay Shutting Down of Windows

In the previous post I showed, how to discover whether the computer is shutting down.
This post shows how to cancel / delay the shutting down to save data before, example.
In the previous post the function FormClosing() was used, in which the reason for quitting was determined. With this function we also can easily delay the shutting down by setting e.Cancel = true. Now though the shutting down is not fully cancelled, but just delayed until the program is stopped - now for example the application has time to save unsaved data.
In Windows Vista and higher a dialog pops up saying that a program is delaying the shutdown.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.WindowsShutDown)
        e.Cancel = true;
}

Another possibility to delay the shutting down of Windows is to use the Microsoft.Win32.SystemEvents.SessionEnding event, which is called when the system is shutting down. The event can be assigned a function handler like other events (e.g. a click on a button), which is called when the event occurs.
The following code sample shows this:

        private void Form1_Load(object sender, EventArgs e)
        {
            Microsoft.Win32.SystemEvents.SessionEnding += new Microsoft.Win32.SessionEndingEventHandler(this.WinShutdown);
        }

        private void WinShutdown(object sender, Microsoft.Win32.SessionEndingEventArgs e)
        {
            e.Cancel = true;
        }

Saturday, November 6, 2010

Discover If System Is Shutting Down

Some people want to get to know via C#, whether the system is currently being shutdown.
Logically, when doing that, all running programs have to be terminated. We will use that and ask for the reason of quitting in the function FormClosing() of the main form, which is called when the form is closed.
The reason can be determined via CloserReason of the argument e. If a shutdown is the reason, this is CloseReason.WindowsShutDown.
The following code snippet displays a message, when the computer is shutting down:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.WindowsShutDown)
        MessageBox.Show("PC wird heruntergefahren.");
}

The use of the event Microsoft.Win32.SystemEvents.SessionEnding, which only occurs when the PC is shut down, is explained in the next post.