Archive for the ‘ Microsoft ’ Category

Binding a Windows Forms ComboBox in C#


Most often when reading the selected item of a bound combobox you will need more information than just the selected text or the selected index of the combo. For example, if you have a combobox bound to a user table in your database, you will most probably want to have the full user name displayed in the combobox, but when a user is selected you will want to work with the user code or user id. In this case the combo’s selected index is of no use and neither is the display text. You need a way to be able to retrieve the user code when a user is selected.

Fortunately, this is quite easy to accomplish. All we need to do is bind our combobox to a list of KeyValuePair objects. In this article I am going to show you how to do exactly that.

To start off create a form which looks similar to the below one:

Now in the Form_Load event handler we must add the following code:

private void MainForm_Load(object sender, EventArgs e)
{
    // Create a List to store our KeyValuePairs
    List> data = new List>();

    // Add data to the List
    data.Add(new KeyValuePair("p1", "Joe"));
    data.Add(new KeyValuePair("p2", "David"));
    data.Add(new KeyValuePair("p3", "Keith"));
    data.Add(new KeyValuePair("p4", "Andrew"));
    data.Add(new KeyValuePair("p5", "Maria"));

    // Clear the combobox
    cboData.DataSource = null;
    cboData.Items.Clear();

    // Bind the combobox
    cboData.DataSource = new BindingSource(data, null);
    cboData.DisplayMember = "Value";
    cboData.ValueMember = "Key";
}

In the first line of code we are creating a List object to store our KeyValuePair objects. The KeyValuePair class can be very useful since it allows you to create a pair of objects of any type, one of which is the key and the other is the value. What this means is that you can have an object of type string paired with a key of type integer for example. Or you could have a value of type MyClass with a key of type string. The combinations are limitless.

As you can see in the code, we are creating a KeyValuePair where both the key and the value are strings. We are then adding data to the List object by creating KeyValuePair instances and adding them to our List. Next we are clearing the combobox as a precaution (just in case it was populated with something already), and finally we are binding the combobox to the List.

The last two lines of the above code are critical for your binding to work correctly. We must tell the combo which is the DisplayMember and which is the ValueMember of our KeyValuePair so that it will know which object from the pair to display and which to use as the key.

Once you have created the above code run your project and you will see that the combobox is populated with the above names. The key value however cannot be seen, so let’s create some code to visually see the selected key.

Subscribe to the SelectedIndexChanged event of your combobox and add the following code:

private void cboData_SelectedIndexChanged(object sender, EventArgs e)
{
    // Get the selected item in the combobox
    KeyValuePair selectedPair = (KeyValuePair)cboData.SelectedItem;

    // Show selected information on screen
    lblSelectedKey.Text = selectedPair.Key;
    lblSelectedValue.Text = selectedPair.Value;
}

What we are doing here is retrieving the combo’s selected item and converting it to a KeyValuePair object. Then from our KeyValuePair object we are accessing the Key and the Value properties and assigning them to the labels on our form.

Now if you run the application again you should have something like the following, and as you can see the key and value are being displayed in our labels.

Now using this technique you can easily bind a combobox and have one value displayed while another value is used as your key.

Create a Worker Thread for your Windows Form in C#


When performing a relatively heavy operation on your Windows Form, what often happens is that your application’s UI will freeze until the heavy operation completes. This is usually unacceptable because your application’s end user will think it crashed and probably try to close it. To solve this problem you need to run your heavy operation on a separate thread from that of your UI. This way you will be able to run your operation while also keep the end user informed of the progress from the UI. In this article I will show you how to do just that.

First let’s create a form with a textbox which displays the progress of the heavy operation, and two buttons, one to start the process and one to stop it.

Next we need to create our heavy operation method. For this example let’s just create a loop which iterates for 1 million times.

private void HeavyOperation()
{
    // Example heavy operation
    for (int i = 0; i <= 999999; i++)
    {
    }
}

Now let’s declare our thread and a boolean flag used to stop the heavy operation. We must use the System.Threading namespace to access the Thread class.

// Declare our worker thread
private Thread workerThread = null;

// Boolean flag used to stop the
private bool stopProcess = false;

Next in the start button event handler method, we will initialise the thread and tell it to run the HeavyOperation method.

private void btnStart_Click(object sender, EventArgs e)
{
    this.stopProcess = false;

    // Initialise and start worker thread
    this.workerThread = new Thread(new ThreadStart(this.HeavyOperation));
    this.workerThread.Start();
}

Your code should be able to compile and run but you won’t see anything happening because we still have to display the heavy operation’s progress on the UI.

This is where Delegates come in. In .NET a delegate is a form of type-safe function pointer. From the HeavyOperation method which is being run under the worker thread, we cannot access the UI thread directly because it would cause a cross-thread operation exception. This is because the UI thread and our worker thread are running independently of each other and cannot access objects which have not been created by themselves.

So to write to our status textbox which is on the UI from our worker thread, we must use a delegate. At the top of our class declare a delegate and an instance of the delegate as shown below:

// Declare a delegate used to communicate with the UI thread
private delegate void UpdateStatusDelegate();
private UpdateStatusDelegate updateStatusDelegate = null;

Next initialise the delegate in form load for example:

private void Form1_Load(object sender, EventArgs e)
{
    // Initialise the delegate
    this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus);
}

As you can see in the above code, the delegate is being passed the method name UpdateStatus. This method will be used to display activity indication to the end user. Now let’s create the method:

private void UpdateStatus()
{
    this.txtProgress.Text += "*";
}

Next, let’s update our HeavyOperation method to call the delegate, which updates the status:

private void HeavyOperation()
{
    // Example heavy operation
    for (int i = 0; i <= 999999; i++)
    {
        // Check if Stop button was clicked
        if (!this.stopProcess)
        {
            // Show progress
            this.Invoke(this.updateStatusDelegate);
        }
        else
        {
            // Stop heavy operation
            this.workerThread.Abort();
        }
    }
}

As you can see, to call the delegate we are using the Invoke keyword, which executes the delegate on the UI thread, since we are calling Invoke from the this object.

And to add the final touch to our application, we must add an event handler for the stop button and set the stopProcess flag to true.

private void btnStop_Click(object sender, EventArgs e)
{
    this.stopProcess = true;
}

Now if you run the application and click on your start button, you will see the status textbox filling up with the “*” character. What’s happening is your worker thread is iterating for 1 million times and for each iteration a star is written to the textbox using the delegate.

How to Capture System Events using C#


What are system events? Well, basically they are events raised by the operating system when a user performs an action which affects the operating environment.

System events are accessible through the Microsoft.Win32.SystemEvents class.

SystemEvents Events
Below is a list of all the system events found within the SystemEvents class.

Name Description
DisplaySettingsChanged Occurs when the user changes the display settings.
DisplaySettingsChanging Occurs when the display settings are changing.
EventsThreadShutdown Occurs before the thread that listens for system events is terminated.
InstalledFontsChanged Occurs when the user adds fonts to or removes fonts from the system.
LowMemory Obsolete. Occurs when the system is running out of available RAM.
PaletteChanged Occurs when the user switches to an application that uses a different palette.
PowerModeChanged Occurs when the user suspends or resumes the system.
SessionEnded Occurs when the user is logging off or shutting down the system.
SessionEnding Occurs when the user is trying to log off or shut down the system.
SessionSwitch Occurs when the currently logged-in user has changed.
TimeChanged Occurs when the user changes the time on the system clock.
TimerElapsed Occurs when a windows timer interval has expired.
UserPreferenceChanged Occurs when a user preference has changed.
UserPreferenceChanging Occurs when a user preference is changing.

Note: Some of these system events may not be raised on Windows Vista.

Example Application
As an example let’s create a simple Windows Forms Application and place two buttons and a textbox on the main form. The buttons are going to subscribe and unsubscribe from the system events and the textbox is going to display the captured event details.

In our application we are going to listen for the following four system events: InstalledFontsChanged, DisplaySettingsChanged, TimeChanged, and UserPreferenceChanged. The code for this is shown below:

private bool eventHandlersCreated;

private void btnStartListening_Click(object sender, EventArgs e)
{
    this.StartListening();
}

private void btnStopListening_Click(object sender, EventArgs e)
{
    this.StopListening();
}

private void StartListening()
{
    Microsoft.Win32.SystemEvents.InstalledFontsChanged += new EventHandler(FontHandler);
    Microsoft.Win32.SystemEvents.DisplaySettingsChanged += new EventHandler(ScreenHandler);
    Microsoft.Win32.SystemEvents.TimeChanged += new EventHandler(TimeHandler);
    Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(PreferenceChangedHandler);

    this.eventHandlersCreated = true;
}

private void StopListening()
{
    Microsoft.Win32.SystemEvents.InstalledFontsChanged -= new EventHandler(FontHandler);
    Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= new EventHandler(ScreenHandler);
    Microsoft.Win32.SystemEvents.TimeChanged -= new EventHandler(TimeHandler);
    Microsoft.Win32.SystemEvents.UserPreferenceChanged -= new Microsoft.Win32.UserPreferenceChangedEventHandler(PreferenceChangedHandler);

    this.eventHandlersCreated = false;
}

As you can see in the StartListening and StopListening methods we are subscribing and unsibscribing to the system events. Each event handler delegate is calling a particular method, and these methods are shown below:

private void FontHandler(object sender, EventArgs e)
{
    txtStatus.Text += string.Format("Installed fonts changed. {0}", Environment.NewLine);
}

private void PreferenceChangedHandler(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
{
    txtStatus.Text += string.Format("You changed a setting: {0} {1}", e.Category.ToString(), Environment.NewLine);
}

private void ScreenHandler(object sender, EventArgs e)
{
    txtStatus.Text += string.Format("Screen resolution changed. {0}", Environment.NewLine);
}

private void TimeHandler(object sender, EventArgs e)
{
    txtStatus.Text += string.Format("System time changed. {0}", Environment.NewLine);
}

If you were to run this application and then go and change the screen resolution for example, the DisplaySettingsChanged event will fire and its delegate will call our ScreenHandler method, and you will see the text Screen resolution changed in the textbox.

Below is a screenshot of our application:

Note: Since these system events are static events, you must make sure you detach your event handlers when disposing your application, or you will end up with memory leaks!

To take care of this memory leak potential problem, when closing our application we are calling the StopListening method to unsubscribe from the event handlers.

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.eventHandlersCreated)
        this.StopListening();
}

Note: Do not perform time-consuming processing on the same thread that raises a system event handler because it might prevent other applications from functioning.

If your application must perform time-consuming processes, do the processing on a separate worker thread and not on the same thread which raises the system events.

Recursively Search Directories


Listing files from directories and sub-directories is a common requirement for many developers. In this short tutorial I will show you how to do this in two different ways.

The Directory.GetFiles() Method

This first method is by far the easier of the two, but to implement this you must be working with Microsoft .NET Framework version 2.0 or later.

The System.IO.Directory class contains a method called GetFiles(). It returns a string array of full file names for each file it finds. It also accepts a number of parameters which allow you to customize your search. Below are examples of the three overloads for GetFiles().

Here we are getting a string array of all the files within the directory “E:\Music\Dire Straits”.

string[] files = Directory.GetFiles("E:\\Music\\Dire Straits");

Now here we are filtering which files to get by file extension – we are getting only the files with an extension of “.mp3″ from “E:\Music\Dire Straits.”

string[] files = Directory.GetFiles("E:\\Music\\Dire Straits", "*.mp3");

Finally here we are getting all the “.mp3″ files from “E:\Music\Dire Straits” and all its sub-directories.

string[] files = Directory.GetFiles("E:\\Music\\Dire Straits",
                                    "*.mp3",
                                    SearchOption.AllDirectories);

As you can see, the guys from Microsoft have made getting files from directories recursively very easy – it is just one line of code!

Create a Recursive Search Method

If you are running Microsoft .NET Framework 1.1 you will have to create your own method to recursively search your directory since the GetFiles() method does not support the SearchOption overload.

A recursive method is basically a method which calls itself. Recursion is a very useful technique but can also be demanding on memory if the recursion gets too deep.

So, let’s create a recursive method which will search for all “mp3″ files within a given directory and its sub-directories.

private void DirSearchMP3(string directory)
{
    foreach (string dir in Directory.GetDirectories(directory))
    {
        foreach (string file in Directory.GetFiles(dir, "*.mp3"))
        {
            this.files.Add(file);
        }

        this.DirSearchMP3(dir);
    }
}

As you can see in the above example, we are iterating all the directories within the given directory passed as a parameter, and then searching for “.mp3″ files within each directory. Then the DirSearchMP3() method calls itself and starts the whole process again. It keeps doing this until no more sub-directories are found.

Below is the whole file listing for this example.

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;

namespace RecursiveFileSearch
{
    public partial class Form1 : Form
    {
        List files = new List();

        public Form1()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            // Search for mp3 files within all sub-directories directories
            this.DirSearchMP3("E:\\Music\\Dire Straits");

            // Search for mp3 files within current directory
            foreach (string file in Directory.GetFiles("E:\\Music\\Dire Straits", "*.mp3"))
            {
                this.files.Add(file);
            }

            // Display all files found
            foreach (string file in this.files)
            {
                Console.WriteLine(file);
            }
        }

        private void DirSearchMP3(string directory)
        {
            foreach (string dir in Directory.GetDirectories(directory))
            {
                foreach (string file in Directory.GetFiles(dir, "*.mp3"))
                {
                    this.files.Add(file);
                }

                this.DirSearchMP3(dir);
            }
        }
    }
}

As you can see from this small tutorial, recursively searching directories is much easier with the .NET 2.0 framework.
Paul

How to use Temporary Files in C#


What exactly is a temporary file? Put simply, a temporary file is a file used by an application for storing temporary data. There is no fixed rule which specifies what this data should be, but generally temporary files (or temp files) are used for storing ‘work data‘. For example Microsoft Office uses temp files to store backups of documents being created or edited. Other applications might use temp files to store large amounts of data which would otherwise occupy too much memory. Basically, it is up to the developer to decide what should be kept within his/her application’s temp files.

In Microsoft Windows, temp files end with the .tmp extension and by default are stored in C:\Users\[username]\AppData\Local\Temp.

The .NET Framework makes creating and using temp files a breeze, so let me show you how to use them.

Create a new Console Application and add a method called CreateTmpFile. In this method we will use the System.IO.Path class to create our temp file.

private static string CreateTmpFile()
{
    string fileName = string.Empty;

    try
    {
        // Get the full name of the newly created Temporary file.
        // Note that the GetTempFileName() method actually creates
        // a 0-byte file and returns the name of the created file.
        fileName = Path.GetTempFileName();

        // Craete a FileInfo object to set the file's attributes
        FileInfo fileInfo = new FileInfo(fileName);

        // Set the Attribute property of this file to Temporary.
        // Although this is not completely necessary, the .NET Framework is able
        // to optimize the use of Temporary files by keeping them cached in memory.
        fileInfo.Attributes = FileAttributes.Temporary;

        Console.WriteLine("TEMP file created at: " + fileName);
    }
    catch (Exception ex)
    {
       Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
    }

    return fileName;
}

As you can see in the above code we are calling the GetTempFileName method of the Path class to create our temp file. When called, this method will automatically create the temp file in the correct folder according to your version of Windows. Then we are creating a FileInfo object and setting the Temporary attribute of our temp file. You can work without setting this attribute, but it is recommended to set it since the .NET Framework will optimize the way it uses your temp file if set.

And that’s all you need to do to create a temp file. The temp file’s name is automatically generated and looks something like this: tmpBD28.tmp.

Now let’s write some data to our temp file:

private static void UpdateTmpFile(string tmpFile)
{
    try
    {
        // Write to the temp file.
        StreamWriter streamWriter = File.AppendText(tmpFile);
        streamWriter.WriteLine("Hello from Paul Mercieca");
        streamWriter.Flush();
        streamWriter.Close();

        Console.WriteLine("TEMP file updated.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error writing to TEMP file: " + ex.Message);
    }
}

As you can see all we are doing here is opening the temp file using the StreamWriter class and then writing to it. It’s just like writing to a normal text file.

To read from the temp file is quite similar:

private static void ReadTmpFile(string tmpFile)
{
    try
    {
        // Read from the temp file.
        StreamReader myReader = File.OpenText(tmpFile);
        Console.WriteLine("TEMP file contents: " + myReader.ReadToEnd());
        myReader.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error reading TEMP file: " + ex.Message);
    }
}

Once you’re done using the temp file you need to delete it or else it will obviously remain there, and over time these files will end up filling your temp folder.

private static void DeleteTmpFile(string tmpFile)
{
    try
    {
        // Delete the temp file (if it exists)
        if (File.Exists(tmpFile))
        {
            File.Delete(tmpFile);
            Console.WriteLine("TEMP file deleted.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error deleteing TEMP file: " + ex.Message);
    }
}

Once you create all the above methods, you can call them for testing purposes as shown below:

static void Main(string[] args)
{
    string tmpFile = CreateTmpFile();
    UpdateTmpFile(tmpFile);
    ReadTmpFile(tmpFile);
    DeleteTmpFile(tmpFile);

    Console.ReadLine();
}

Another useful method within the Path class is the GetTempPath() method. This returns the path of the current system’s temporary folder, which you might want when working with temp files.

I hope you found this article useful. Feel free to add comments or ask any questions below.
Paul

Survey: Windows 7 getting popular with developers


Apps builders like touch and multitouch capabilities but are challenged by supporting older versions of the OS

Developers are hopping on the Windows 7 bandwagon, according to survey results released Monday by database and developer tools vendor Embarcadero Technologies.

In a survey of 606 respondents conducted in May, Embarcadero found 54 percent indicated they were developing applications for Windows 7. Another 25 percent said they plan to develop applications for Microsoft’s latest client OS in the next year. Just 10 percent have no plans to build for Windows 7.

[ Get all the details you need on deploying and using Windows 7 in the InfoWorld editors’ 21-page Windows 7 Deep Dive PDF special report. ]

But more than 15 percent of respondents are waiting for more organizations to adopt Windows 7 to make it worth their while, according to Embarcadero. Respondents were comprised of developers, architects, and analysts.

Respondents, Embarcadero found, are enticed by Windows 7 capabilities such as touch, multitouch, and enhanced graphics. Microsoft began shipping Windows 7 last fall.

“The popularity of devices like the iPhone and iPad have helped drive mainstream acceptance of touch-based technologies. This popularity transcends into the developer community, and I doubt we’ll see it abate anytime soon,” said Michael Rozlog, product manager for Delphi Solutions at Embarcadero, in a statement released by the company.

Building for Windows 7 is not without challenges, however. Thirty-four percent of respondents indicated the biggest challenge is supporting users on older versions of Windows. Microsoft is ending support for Windows XP in April 2014 and analysts are encouraging enterprises and consumers to move to Windows 7 by the end of 2012, Embarcadero said. These urgings, however, have been met with reluctance, the company noted.

Better than 10 percent of respondents said learning something new was the biggest challenge to developing for Windows 7.

The survey also found that the majority plan to build Windows 7 desktop applications first, with database applications second on the list, followed by utilities and tools. Small business applications are of higher priority than enterprise applications.

This article, “Survey: Windows 7 getting popular with developers,” was originally published atInfoWorld.com. Follow the latest developments in business technology news and get a digest of the key stories each day in the InfoWorld Daily newsletter and on your mobile device atinfoworldmobile.com.

Microsoft sees jump in XP attacks


Microsoft has tracked 25,000 attempts to exploit a flaw in Windows XP’s Help and Support Center — a critical bug fixed in the latest security patches

Microsoft is urging Windows users to update their software, saying it’s now seen more than 25,000 attacks leveraging one of the critical bugs fixed in July’s monthly security patches.

Microsoft researchers tracked a “fairly large,” spike in Web based attacks that exploit the problem over the past weekend, the company said in a blog posting Tuesday. “As of midnight on July 12 (GMT), over 25,000 distinct computers in over 100 countries/regions have reported this attack attempt at least one time.”

On the busiest single day, Microsoft researchers tracked more than 2,500 attacks, a small number considering Windows’ massive user-base. Still, Microsoft and security experts are worried about this flaw because it’s been publicly known for more than a month, and has shown up in real-world attacks.

Users in Russia are now the most-targeted, Microsoft said. They have accounted for 2 percent of all attacks, which translates to about 10 times the total number of attacks per computer as the worldwide average. Portugal is the number-two most-targeted region.

Successful attacks secretly install malicious software on the victim’s machine, often a program called Obitel. Once Obitel is on a PC, it enables other malware to be loaded, such as malware that can log keystrokes, send spam, or perform other nefarious task.

Two weeks ago, the total number of attacks logged by Microsoft was 10,000.

Security experts say the flaw is being exploited in drive-by Web attacks that are triggered by malicious code placed on hacked or malicious websites, although it could also be triggered in other applications — email readers, for example — that can interact with Web pages.

To protect themselves from these attacks, Windows users need to install the MS10-042 update, released Tuesday. It fixes a bug in the Windows Help and Support Center, which ships with Windows XP. Although this flaw also affects Windows Server 2003, Microsoft has only seen Windows XP attacks used by criminals.