New Shop!

I have a new shop opened on Zazzle

Got lots of Computer Programming related designs, mugs, t-shirts, etc, plus items with some of my photography and some other random designs…

I will be adding a lot of new products over the next few weeks.

If you see any designs you like and would like to see them on different products, or have a specific design in mind that you can’t find, please send me an email via the Zazzle site.

Click here go to to shop!

Posted in Shopping | Tagged , , , , , | Leave a comment

Add child items to ToolStripMenuItem using C# – C Sharp

I wanted to be able to populate menu items from a database, i.e. I had a Print Document top level menu item and I wanted to be able to populate the children from the database dynamically with each available document.

The theory was this:

1. Use the MouseHover event for the main menu item
2. When the user hovers over the item, get the list of documents and add them as children
3. Add a Click event handler to process clicks on the children

Below is the MouseOver code (NB I’ve replaced the load from database code with three simple allocations to simplify the code). Notice that the property that holds the menu item children is DropDownItems.

private void MyToolStripMenuItem_MouseHover(object sender, EventArgs e)
    //create tsParent using sender
    ToolStripMenuItem tsParent = (ToolStripMenuItem)sender;

    //check to see if the children have already been created 
    //(stops them being added repeatedly if you hover more than once)

    if (tsParent.DropDownItems.Count == 0)
        //define new ToolStripMenuItem to use as the new child
        ToolStripMenuItem newChild;

        //in the real case this is a loop adding items from a database
        //notice the Click event handler added to each item detailed below
        newChild= new ToolStripMenuItem();
        newChild.Text = "Added Item One";
        newChild.Tag = 1;
        newChild.Click += new EventHandler(processMeunItem);
        //add the new child to the parent DropDownItems collection

        newChild= new ToolStripMenuItem();
        newChild.Text = "Added Item 2";
        newChild.Tag = 2;
        newChild.Click += new EventHandler(processMeunItem);

        newChild= new ToolStripMenuItem();
        newChild.Text = "Added Item 3";
        newChild.Tag = 3;
        newChild.Click += new EventHandler(processMeunItem);

The code above will add three children to the menu item when you hover over it. Now we need to do something when a child is clicked:

//code runs when any of the new children are clicked
private void processMeunItem(object sender, EventArgs e)
    //Get the tag of the selected menu item and assign to integer selectedMenuTag
    int selectedMenuTag = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);

    //do something with the selected item...

This will allocate the Tag of the clicked item to selectedMenuTag, you can then use it for further processing.

Posted in Programming | Tagged , , , , , , | Leave a comment

Shuffle an Array in C#

As part of a basic guessing game I wanted to be able to shuffle an array of n chars into a random order.

The method I decided to use was the following.

Create a loop to iterate n times (where n is the number of elements in the array). Randomly select one array element and add this to a new array. Replace the removed item with the last item in the array (effectively making the array one element smaller). This seemed easier than shifting all the elements along one to remove the gap (which was my first thought). The new array will hold the ‘shuffled’ items.

Pictorial example:

Shuffle Array

Shuffle Array

Here you can see each step (the selected item is shown in Red).

In code this translates to the following shuffle function:

private char[] shuffle(char[] charArray)
    char[] shuffledArray = new char[charArray.Length];
    int rndNo;

    Random rnd = new Random();
    for (int i = charArray.Length; i >= 1; i--)
        rndNo = rnd.Next(1, i+1) - 1;
        shuffledArray[i - 1] = charArray[rndNo];
        charArray[rndNo] = charArray[i - 1];
    return shuffledArray;

This can be called in the following way:

char[] list1 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M' };
char[] shuffled = shuffle((char[])list1.Clone()); 

Here the list1 array will be shuffled and returned to the shuffled array. Note that I pass a clone of the list1 array, this is because arrays are passed by reference and if I didn’t do this the list1 array would be altered which I didn’t want.

One other thing to note is that this would work for any kind of array, just by changing the array type.

I don’t know exactly how random this function is. However, I ran a loop shuffling 13 chars 1,000,000 times and had 42 duplicate outputs.

Posted in Programming | Tagged , , , , , | 3 Comments

Loading Data into a DataReader and Looping Through Records OLEDB / C#

Just a quick example of loading data into a data reader using C#. My data source is MS SQL Server in this case, although you would just need the correct OLEDB connection string to use any other data source.

//database connection string & SQL Statement to return SERVICE_LEVEL_ID and DEFINITION from a table called property.SERVICE_LEVEL
string dbConnectionString = @"Provider=SQLNCLI10;Server=(local)\SQLEXPRESS;Database=XXXXX;Uid=XXXXXX;Pwd=XXXXXXXXX;";

//Create and open connection string
OleDbConnection dbConnection = new OleDbConnection(dbConnectionString);

//create a command object using the sql and the connection object
OleDbCommand dbCommand = new OleDbCommand(dbSQL, dbConnection);
dbCommand.CommandType = CommandType.Text;

//excute the command object and write the output to the datareader dr
OleDbDataReader dr = dbCommand.ExecuteReader();

//loop through all the records in the datareader
while (dr.Read())
    //write the DEFINITION field out to a message box

Couple of things to notice in this code are the While(dr.Read()) line. Not only does dr.Read() get the next record in the data reader, it also returns true if a record is returned or false if one isn’t. So it effectively checks for EOF (end of file) at the same time. Also the dr[“DEFINITION”].ToString() could be replaced with an index based call of dr.GetString(1). NB column indexes start at 0

Posted in Programming | Tagged , , , , , | Leave a comment

Changing Default Parameter Value SSRS (SQL Server Reporting Services) 2008

If you’re here you have probably found that if you’ve deployed a report to your server updating the default parameter values and redeploying has no effect on the server report.

E.g. I had a report with an integer parameter with a default of 25 that had been deployed to the server. On my development machine I updated the default value and redeployed the report. However, when I ran the report the default value hadn’t changed.

The reason for this is that the parameters are managed on the server once the report has been deployed. So to change them you need to log in to your reporting services on your server (you’ll have a screen something like the one below):


To update your parameters, select “Manage” from the drop-down list on the report you want to change. You should see a screen like below:


Click on the “Parameters” option on the left-hand side and you will be taken to a screen that allows you to update parameter options for the report.

Posted in Programming | Tagged , , , , , | Leave a comment

Image Slideshow on Windows Form C# with Timer Control

Quick example of how to display an image control that loops through a folder of images.

Firstly drop a timer control onto your form (name: tmrNextImage), set the Interval to 1000 milliseconds (1 second) and set enabled to true.

Next drop a PictureBox control onto your form (name: imgPicture) and set SizeMode to Zoom (this will force your image to fit the box), drag your box to any size you like.

Now we need some images. I copied images to a folder (C:\Data_Store\Images\) and named them Logo1.jpg, Logo2.jpg, etc up to Logo6.jpg

Now lets make the code to load the image into the PictureBox control. We need a variable to ‘remember’ our image count, in this case imageNumber. Our loadNextImage checks to see if we’ve reached 7 (one more than the number of images we have) and if so sets imageNumber back to 1.

We then set the ImageLocation to our C:\Data_store\images\ plus our image name with the imageNumber inserted into the filename, e.g. Logo1.jpg the first time round. And then increment imageNumber by 1.

        private int imageNumber = 1;

        private void loadNextImage()
            if(imageNumber == 7)
                imageNumber = 1;
            imgPicture.ImageLocation = string.Format(@"C:\data_store\images\logo{0}.jpg",imageNumber);

So now we need to trigger the image to change. To do this we use the Tick event of the timer (which will happen every 1000 milliseconds as we set earlier). So each time the tick event happens we call the loadNextImage code.

        private void tmrNextImage_Tick(object sender, EventArgs e)

Now when you open the form the image should change every second.

Posted in Programming | Tagged , , , , | 7 Comments

Find all Subdirectories from a given path using C# – With Error Handler

In my earlier post () I showed how you can iterate through folders and add the folder names to a list (lstDirs). The problem with this code was that if you encountered a folder you didn’t have access to it all fell over. Below I’ve added a function to test the folder access (canReadDir()), if the folder is inaccessible the path is added to lstFailed and reading is skipped for this folder:

private void loadSubDirs(string sPath)
        DirectoryInfo dInfo = new DirectoryInfo(sPath);
        DirectoryInfo[] subDirs = dInfo.GetDirectories();

        foreach (DirectoryInfo dir in subDirs)
            //call loadSubDirs with current dir name

private bool canReadDir(string sPath)
   DirectoryInfo dInfo = new DirectoryInfo(sPath);
      //try to get directories if fails will go to catch
      DirectoryInfo[] subDirs = dInfo.GetDirectories();
      return true;
      return false;

Posted in Programming | Tagged , , , , | Leave a comment

Search for Value in Multiple Columns SQL Server T-SQL

Having to write some SQL SELECT’s on some un-normalized tables left me thinking there has to be a tidier way. I started with:


(@SCAN_ID is a variable declared earlier)

I ended up with:


Maybe not a massive improvement, but personally I find this easier to read and debug (especially if there are other conditions in the WHERE)

Posted in Programming | Tagged , , , | Leave a comment

Browse for SQL Server 2008 R2 Installation Media

When running the SQL Server Installation Centre I was receiving the above error. This seems to be caused by the software being installed to a temp folder which is subsequently deleted post install.

Mine had been installed from a folder on the network. Even pointing to this folder when prompted didn’t resolve the problem.

Solution that worked for me:

1. Copy the entire installation folder to my local drive (this step may not be necessary but made it easier for me). E.g. C:\SQL Server Install\

2. Launch the SQL Server Installation Centre.

3. Go to Options – and set Installation Media Root Directory to the folder you copied the installation files to. E.g. C:\SQL Server Install\

You may be able to leave the files in the original install location and just set the path depending on access.

Posted in Programming | Tagged , , | 2 Comments

SQL Server 2008 R2 Maintenance Cleanup Task Not Deleting bak Files

I noticed that my old backup files were not being deleted despite my Cleanup Task being set to delete all bak files more than a day old. Having checked, and double checked the path, file age, etc. I decided it was time to try a couple of random things.

Firstly I added a \ to the file path, this seemed to make no difference. So I then decided to remove the . before the bak extension (put there by SQL Server).

SQL Server Maint Task

All is now working as expected.

Posted in Programming | Tagged , , | Leave a comment