How to remove an element from a regular array in C#?

How to remove an element from an regular array in C#?

Well, you can’t really change a regular array or remove an item from it. You have to create a new array that is a copy of the current array without the one value you want.

Here is a quick static class I created that will copy your array, leaving out the one item you don’t want.

namespace ArrayItemDeleter
{
static class ArrayItemDeleter
{
public static void RemoteArrayItem(ref T[] inArray, int inIndex)
{
T[] newArray = new T[inArray.Length – 1];
for (int i = 0, j = 0; i < newArray.Length; i++, j++) { if (i == inIndex) { j++; } newArray[i] = inArray[j]; } inArray = newArray; } } } [/sourcecode] Here is how you would use it in your program. [sourcecode language="csharp"] using System; namespace ArrayItemDeleter { class Program { static void Main(string[] args) { string[] str = {"1","2","3","4","5"}; ArrayItemDeleter.RemoteArrayItem(ref str, 2); } } } [/sourcecode] Now, if you really want to add and remove items a lot, you should use a System.Collections.Generic.List object;


Equivalent of mysqldump for Microsoft SQL Server 2008

There is a Database Publishing Wizard 1.1 you can download that may work for SQL Server 2005, but didn’t work for me with SQL Server 2008. However,Database Publishing Wizard 1.3 is installed with Visual Studio 2008 but I cannot find a separate download. This tool gets you the schema and data and everything but the “drop and create database” script.

So I think you need Visual Studio 2008 for this for SQL Server 2008 to get it. I am not sure why I cannot find it separately. Maybe Microsoft has a reason.

Step 1 – In Visual Studio 2008, go to Tools | Connect to Database and connect to a MS SQL database.

Under the Server Explorer window, the connection now appears.

Step 2 – Expand Data Connections.

Step 3 – Right-click on the connection and choose Publish to provider.

Step 4 – Click Next.

Step 5 – Choose the database.

Step 6 – Click Next.

Step 7 – Select the publishing options (such as to export the schema and data or just the schema).

Step 8 – Choose a file.

Step 9 – Click Finish.

Step 10 – The one thing this is missing is the script to drop and create the database. You can easily get this from Microsoft SQL Server Management Studio 2008 (there is a free Express version if you don’t have it). Just connect to the database, right-click on the database and choose Script Database as | Drop And Create to | Clipboard. Now past this text to the top of your file you just created.


How to connect to Salesforce / SForce with C#?

Step 1 – Download and import the wsdl (sorry no steps for this here yet).

Step 2 – Use the following code example

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

namespace SforceConnection
{
    public class Program
    {
        static void Main(string[] args)
        {
            SforceService service = new SforceService();
            LoginResult loginResult = new LoginResult();
            string username= "youruser@yourdomain.tld";
            string password= "P@sswd!";
            service.Timeout = 60000;
            loginResult  = service.login(username, password);
            service.Url = loginResult.serverUrl;
            service.SessionHeaderValue = new SessionHeader();
            service.SessionHeaderValue.sessionId = loginResult.sessionId;

            // Do something you are now connected

        }
    }
}

How to return a string array from an enum in C#?

So I have a enum and I want to pass it to a ComboBox, so I need it to be an array of strings.

Well, this was much more simple than I thought:

public static string[] EnumToStringArray(Type inType)
{
	return Enum.GetNames(typeof(inType));
}

I found a few sites that were taking some much more complex routes, maybe they didn’t know about this feature.


How to find the file and line number of memory leaks using C++ with wxWidgets in Visual Studio 2008?

Ok, so I am coding with C++ and wxWidgets using Visual Studio 2008 as the IDE.

I got the following output when my my program was launched in debug mode and it exited.

Detected memory leaks!
Dumping objects ->
{1535} normal block at 0x005C1920, 18 bytes long.
 Data: <                > 00 00 00 00 00 00 00 00 00 00 00 00 00 00 CD CD

I can’t have memory leaks and while they aren’t a big deal and are with objects I create once so they really aren’t that bad, my obsessive compulsiveness (I’m just a little OC but not OCD) wouldn’t let me move on with the program or do anything else until I had solved these memory leaks.

I did some researching and tried a lot of things before I finally found this website:
http://www.litwindow.com/Knowhow/wxHowto/wxhowto.html#debug_alloc

So I gave the steps a try. I had a little bit of a problem but I got them to work, so I am re-writing the steps so that I remember how to do it again and don’t run into the same problem.

Steps for Finding Memory Leaks in C++ and wxWidgets using Visual Studio 2008

  1. Create a new header (.h) file called: stdwx.h 
    // wxWidgets precompiled / standard headers
    #include "wx/wxprec.h"
    
    // When debugging changes all calls to "new" to be calls to "DEBUG_NEW" allowing for memory leaks to
    // give you the file name and line number where it occurred.
    #ifdef _DEBUG
    	#include <crtdbg.h>
    	#define DEBUG_NEW new(_NORMAL_BLOCK ,__FILE__, __LINE__)
    	#define new DEBUG_NEW
    #else
    	#define DEBUG_NEW new
    #endif
    

    Note: The site I linked to had much more in the header file, but I like to know the minimal requirements for the task at hand and so I commented out the lines that I thought didn’t matter and tested by recompiling and running in debug and sure enough, only the above lines are needed. However, that shouldn’t stop you from adding #includes you always use to your header file. Notice the use of #ifdef _DEBUG which means that this code will only be used when debugging and so your release code will not contain this debugging code (which is useless for release builds).

  2. Create a new .cpp file called: stdwx.cpp. Add A single line including stdwx.h.Yes, it is really only supposed to be one #include line as shown:
    #include "stdwx.h"
    
  3. Now add that same #include line to every .cpp file in your project:
    // Include the stdwx.h in every .cpp file
    #include "stdwx.h"
    
  4. Now in Visual Studio 2008, under Solution Explorer, right-click on the Project (my test project happens to be Dice at the moment) and choose Properties.
  5. Expand Configuration Properties | C/C++ and select Precompiled headers.
  6. Use the drop down for Create/Use Precompiled Header to select Create Precompiled Header (/Yc).
  7. Under Create/Use PCH Through File, type in stdwx.h.Note: The Precompiled Header File setting should auto-popluate with the correct value of $(IntDir)\$(TargetName).pch.
  8. Click OK to save the project properties.

A screen shot is included to provide further help on these settings:

Precompiled Headers Settings

Precompiled Headers Settings

You should now be ready to recompile your program and now instead of seeing just vague memory locations of memory leaks, you should see the exact file and line number, which is key in detecting and deleting the allocated memory.

Detected memory leaks!
Dumping objects ->
{1535} normal block at 0x005C1920, 18 bytes long.
 Data: <                > 00 00 00 00 00 00 00 00 00 00 00 00 00 00 CD CD
c:\users\jbarneck\documents\visual studio 2008\projects\dice\dice\die.cpp(183) : {1529} normal block at 0x005C18D0, 20 bytes long.
 Data: <          \ . \ > 00 00 00 00 CD CD CD CD 20 19 5C 00 2E 19 5C 00

Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.


How to create and use dynamic event handlers in wxWidgets for an array of buttons using the Connect() function?

Description
Ok, so I have an array of buttons. Well, actually it is a vector, and could be any size. So wxWidgets usually recommends static event handlers and using dynamic event handlers was really confusing.

So I have the wxWidgets book, I researched the website and found the Connect() function.

So I have a class called wxDieFrm (because I was creating dice). This wxDieFrm object has the following code snippet to create dynamic events for each button. So I incorrectly figured I would use the wxButton.Connect() method. Let me show what I did wrong and then how easily it was fixed.

	for (int i = 0; i < mSetOfDice->getNumberOfDice(); i++)
	{
		// Some code here...
		wxButton *rollButton = new wxButton(this, *buttonID, wxT("Roll"), wxPoint(5, 15), wxSize(75, 25), 0, wxDefaultValidator, wxT("buttonRoll"));
		//The following line is incorrect and the cause of the problem
		rollButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxDieFrm::buttonRollClick) );
		WxBoxSizer->Add(rollButton,0,wxALIGN_CENTER | wxALL,5);
	}

Notice I commented just before the problem line, so you would know the cause.

Then the event functions is this:

/*
 * buttonRollClick
 */
void wxDieFrm::buttonRollClick(wxCommandEvent& event)
{
	wxButton *button = (wxButton*)event.GetEventObject();
	int id = button->GetId() - 4001;
	int rollValue = mSetOfDice->getDie(id).roll();
	wxBitmap *bmp = mBitmapVector->at(rollValue - 1);
	mDice->at(id)->SetBitmap(*bmp);
}

Problem
This didn’t work. I got all kinds of access violation errors, which was strange to me, because being in the wxDieFrm::buttonRollClick() function, the entire wxDieFrm should have been accessible. But nothing I did could and no amount of debugging helped me figure out this. It took reading a bunch of different posts before I finally found the answer.

Cause
There was really only one problem. I was having the button call its Connect() method. This was a problem because when the code went to the wxDieFrm::buttonRollClick() in that it only allowed me access to my button object.

Resolution
The fix was simple, don’t call Connect() from the button, just call it using the wxDieFrm object.

	for (int i = 0; i < mSetOfDice->getNumberOfDice(); i++)
	{
		// Some code here...
		wxButton *rollButton = new wxButton(this, *buttonID, wxT("Roll"), wxPoint(5, 15), wxSize(75, 25), 0, wxDefaultValidator, wxT("buttonRoll"));
		WxBoxSizer->Add(rollButton,0,wxALIGN_CENTER | wxALL,5);
	}

	//The following line is THE CORRECT VERSION and the RESOLUTION to the problem
	Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxDieFrm::buttonRollClick) );

Reference Material
The following are the resources and different articles I had to pore over to finally reach this understanding:
Chapter 2 of the WxWidgets book, the event handler section.
Chapter 7 of the WxWidgets book.
http://wiki.wxwidgets.org/Events#Using_Connect.28.29
http://wiki.wxwidgets.org/Example_Of_Using_Connect_For_Events
http://wxwidgets.blogspot.com/2007/01/in-praise-of-connect.html
http://wiki.wxwidgets.org/Using_Connect_To_Add_Events_To_An_Existing_Class

The funniest part is the last one has a big post that says THE REST OF THIS PAGE IS WRONG and so I passed over it a half dozen times, before finally reading it. It was actually the one that gave me the answer under the diagnosing the problem section, it reads:

So my experiment reveals a characteristic of wxEvtHandler::Connect that is not explicitly documented (though it may be obvious to those who actually know C++): the wxObjectEventFunction passed to Connect() will be called with this set to whatever called Connect().

So by calling wxButton.Connect() instead of wxDieFrm.Connect() (or this.Connect() or just Connect() ) the value of this (the code word this not the preposition) was the wxButton and not wxDieFrm. That is why i was getting access violations.

So as soon as I switched to wxDieFrm.Connect() the value of this because my wxDieFrm and my access violations went away and everything works. For a minute I considered dropping wxWidgets altogether, but now that I understand this features, I like wxWidgets much more than ever.


Visual Studio 2008 editor colors set to use a black background and how to add these settings yourself or keep your color settings on re-install?

So I recently installed Windows 7 64 bit on my laptop. Before I was using XP Pro SP3 32 bit. I had visual studio 2008 installed and had the editor using a black background exactly how I like it.

So really, all I wanted was my colors in my editor. So it turns out you can export them.

  1. On you current install, go to Tools | Import and Export Settings.
  2. Choose Export selected environment settings and click next.
  3. Click the top box to remove the check box from everything.
  4. Expand All Settings | Options | Environment.
  5. Click to check the box next to Fonts and Colors
  6. Click next and save your file

I won’t walk you through importing it because you should be competent enough to do that on your own having now exported it.

Want it in a download?

Visual Studio Black Theme

Want just the XML? For those of you who also want a black background and just want the XML, here is my Environment_FontsAndColors section and a screen shot of it.

Visual Studio 2008 Text Editor with black background

Visual Studio 2008 Text Editor with black background

Here is the xml code, you can copy and paste:








      2














































































































Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.


How to convert an int to a string in C++? (Also doubles, floats, etc…)

Here is how I do it. This procedure actually works for any type such as: int, double, float, etc…

Convert an Int Only

#include
#include
#include

using namespace std;

int main()
{
int i = 10;
string s = inToString(i);
return 0;
}

string intToString(int inInt)
{
stringstream ss;
string s;
ss << inInt; s = ss.str(); return s; } [/sourcecode] As a Template So It Works with All Types (int, float, double, etc…)

I found a comment on another guys blog that actually makes it work for any type such as double, float, etc.. It has this code using this template.
http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

template
string anyTypeToString(const T& t)
{
std::stringstream ss;
ss << t; return ss.str(); } [/sourcecode] This works really well, I have been using it and it is so simple. Key words: int to string intToString double to string doublToString float to string floatToString


Working with DateTime and Unix Time Stamps or Universal time (UTC) in C#

I ended up creating an extender class. Here is an example.

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

namespace LANDesk.Install.Common.Extenders
{
    public static class DateTimeExtender
    {
        #region Functions
        /// <summary>
        /// Methods to convert DateTime to Unix time stamp
        /// </summary>
        /// <param name="_UnixTimeStamp">Unix time stamp to convert</param>
        /// <returns>Return Unix time stamp as long type</returns>
        public static long ToUnixTimestamp(this DateTime thisDateTime)
        {
            TimeSpan _UnixTimeSpan = (thisDateTime - new DateTime(1970, 1, 1, 0, 0, 0));
            return (long)_UnixTimeSpan.TotalSeconds;
        }

        #endregion
    }
}

Here is some code you can use for learning, to know what functions do what with DateTime. You should be able to learn everything you need to know by evaluating it.

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

namespace UTC
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt = DateTime.Now;

            Console.WriteLine("Outputting the type of DateTime object used:");

            Console.WriteLine(dt.Kind);

            Console.WriteLine("\nOutputting the current time as is:");

            Console.WriteLine(dt);

            Console.WriteLine("\nOutputting the current time using the ToUniversalTime() function:");

            Console.WriteLine(dt.ToUniversalTime());

            Console.WriteLine("\nOutputting the current time using the ToFileTime() function:");

            Console.WriteLine(dt.ToFileTime());

            Console.WriteLine("\nOutputting the current time using the ToFileTimeUtc() function:");

            Console.WriteLine(dt.ToFileTimeUtc());

            Console.WriteLine("\nOutputting the current time using the Ticks property:");

            Console.WriteLine(dt.ToFileTimeUtc());

            Console.WriteLine("\nCreating a DateTime and setting it as follows:\nDateTime udt1 = DateTime.Parse(\"1/1/1970\");");

            DateTime udt1 = DateTime.Parse("1/1/1970");

            Console.WriteLine(udt1);

            Console.WriteLine("\nCreating a DateTime and setting it as follows:\nnew DateTime(1970, 1, 1, 0, 0, 0, 0);");

            DateTime udt2 = new DateTime(1970, 1, 1, 0, 0, 0, 0);

            Console.WriteLine(udt1);

            Console.WriteLine("\nOutputting the time stamp of this Unix Time Stamp value: 1254322574 (seconds)\nTo do this i use these lines:\n DateTime udt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n udt.AddSeconds(1254322574448);");

            Console.WriteLine(udt1.AddSeconds(1254322574));

            Console.WriteLine("\nOutputting the time stamp of this Unix Time Stamp value: 1254322574789 (milliseconds)\nTo do this i use these lines:\n DateTime udt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n udt.AddMilliseconds(1254322574448);");

            Console.WriteLine(udt1.AddMilliseconds(1254322574789));

        }
    }
}

Ok, so here is the output:

Outputting the type of DateTime object used:
Local

Outputting the current time as is:
9/30/2009 3:49:18 PM

Outputting the current time using the ToUniversalTime() function:
9/30/2009 9:49:18 PM

Outputting the current time using the ToFileTime() function:
128988209584600486

Outputting the current time using the ToFileTimeUtc() function:
128988209584600486

Outputting the current time using the Ticks property:
128988209584600486

Creating a DateTime and setting it as follows:
DateTime udt1 = DateTime.Parse(“1/1/1970”);
1/1/1970 12:00:00 AM

Creating a DateTime and setting it as follows:
new DateTime(1970, 1, 1, 0, 0, 0, 0);
1/1/1970 12:00:00 AM

Outputting the time stamp of this Unix Time Stamp value: 1254322574 (seconds)
To do this i use these lines:
DateTime udt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
udt.AddSeconds(1254322574448);
9/30/2009 2:56:14 PM

Outputting the time stamp of this Unix Time Stamp value: 1254322574789 (milliseconds)
To do this i use these lines:
DateTime udt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
udt.AddMilliseconds(1254322574448);
9/30/2009 2:56:14 PM
Press any key to continue . . .


How to pause a Console application in C++ on Unix/Linux or the equivelent to the windows C++ system(”pause”)statement or the _getch() functions in conio.h?

So in C++ on windows, there are two ways to get this feature:

Calling this line, which really is making a call to system to open a cmd.exe process and run “pause” inside the cmd.exe process. So this is really not something that should be in production code.

system("pause");

Or using _getch() from conio.h, which is probably something that would be better for “windows only” production code. At least it is better than doing a system call to open a separate cmd.exe process to run “pause” and it takes less resources.

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
	std::cout << "Press any key to continue...";
	_getch();
}
&#91;/sourcecode&#93;

These above options give you two main features in Windows:

1. Your console application pauses.
2. You can get the option to "Press any key to continue . . ." which allows you to press ANY key on the keyboard to continue.

<blockquote>What is the equivalent in Unix\Linux?</blockquote>
First, there is no equivalent to do exactly what you want on Unix/Linux platforms.  You really can only get these two features on Unix/Linux in C++.

1. Your console application pauses.
2. You can get the option to "Press [ Enter ] to continue . . ." which mean that presses anykey on the keyboard isn't going to work, only pressing Enter will work.

<strong>Why can you not get your C++ program to accept ANY KEY in Unix/Linux?</strong>
Now, in my research it appears that your C++ program does not take control of your keyboard and read every key stroke.  Instead, it waits for the console or tty to actually pass the keyboard strokes to the program, which usually happens when you press [Enter] and not before. This is called "line-buffered" input.  While Microsoft's CMD.EXE (which is a type of console or tty on windows) passes each key stroke to your program immediately and is not "line-buffered", which is why this works on windows.

So these differences are not something you have control over, unless you want to write your own Linux/Unix console or write your program to somehow interface with the console or tty to disable "line-buffered" input and get each key stroke passed to your program.  In my research I found some say you could configure this but I couldn't find any concrete examples.

<strong>So how do I at least get the "You can press [Enter] only to continue." option?</strong>

Here is how I did it, feel free to give me feed back if I left something out.

<strong>Doing it all in main.cpp</strong>

[sourcecode language="cpp"]
#include <iostream>

using namespace std;

int main()
{
	doPause();
}

void doPause()  // I had an error on FreeBSD because there was already a pause() function elsewhere, so I changed it to doPause();
{
	std::cout << "Press &#91; Enter &#93; to continue...";
	cin.clear(); // Make sure the buffers are clear, you may want to do cin.flush() as well but I am not sure if both are needed.
	cin.ignore();
}
&#91;/sourcecode&#93;

<strong>Doing it as a class or object</strong>

main.cpp
[sourcecode language="cpp"]
#include <iostream>
#include <Pause.h>

using namespace std;

int main()
{
	new Pause();
}

Pause.h

#include <iostream>

class Pause
{
	public:
		Pause();
};

Pause.cpp

#include
#include “Pause.h”

Pause::Pause()
{
std::cout << "Press [ Enter ] to continue..."; cin.clear(); // Make sure the buffers are clear, you may want to do cin.flush() as well but I am not sure if both are needed. cin.ignore(); } [/sourcecode] When I get an example of how to do by turning of "line-buffered" input, I will update this blog.


What is the Microsoft SQL equivalent to MySQL's "Limit" feature in a SQL query?

Here is a MySQL Query

SELECT * FROM Table LIMIT 10

Here is a Microsoft SQL Query to perform the same

SELECT TOP10 * FROM Table


How to check if a SQL Table exists in C#?

Simple question, simple answer

SQL Query to return the data

SELECT TABLE_NAME FROM DBName.INFORMATION_SCHEMA.Tables WHERE TABLE_NAME='Article'

How do I check this in C#?

As for how you check that in C#? You just make sure the Row count returned from the query is 1. See this article I have already posted.

How do I get the number of rows returned from a Microsoft SQL Query in C#?

 

Return to ADO.NET and Database with C#


How to pause a Console application in C# or the equivelent to the C++ system("pause") statement?

How to pause a Console application in C# or the equivelent to the C++ system(“pause”) statement?
I actually had to spend way more time to figure this out. I assumed that there was a simple pause function, but there is not. C# has left out that function. So if you are looking for a way to do this with a single statement, you are not going to find it. I searched, and searched, and searched.

I just wanted to pause, something that is common in C++. In C++ people always do the following:

system("pause");

Note: This is not actually an efficient method to do this in C++. It is loading a cmd.exe process and running the pause command inside it. So should you really be loading a separate external process and all its resources every time you want to pause? Well, it isn’t really that many resources so who really cares, right? You could do the same thing in C# by launching a cmd.exe process but it is probably not what you really want to do.

The best solutions I found are documented, one uses a function, one uses a Pause class.

How to pause a Console application in C#?

Step 1 – Create a function in your Program.cs class called pause as shown here:

public static void Pause()
{
	Console.Write("Press any key to continue . . . ");
	Console.ReadKey(true);
}

Step 2 – Call this function in your code. The following is a complete example

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

namespace Pause
{
    class Program
    {
        static void Main(string[] args)
        {
            Pause();
        }

        public static void Pause()
        {
            Console.Write("Press any key to continue . . .");
            Console.ReadKey(true);
        }
    }
}

How to do this as a Pause class?

Step 1 – Create the following class

Pause.cs

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

namespace Pause
{
    class Pause
    {
        public Pause()
        {
            Console.Write("Press any key to continue . . .");
            Console.ReadKey(true);
        }
    }
}

Step 2 – Add this to your project and then call new Pause(); and you did it. As

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

namespace Pause
{
    class Program
    {
        static void Main(string[] args)
        {
            new Pause();
        }
    }
}

How to insert a row into a Microsoft SQL database using C#?

The following steps accomplishes this:

  1. Create a connection string.
  2. Create an insert query string.
  3. Create a SQLConnection object that uses the connection string.
  4. Create a SqlCommand object that used both the SQLConnection and the query string.
  5. Open the connection.
  6. Execute the query.
  7. Close the connection.
Steps are in the code with comments.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace InsertToDatabase
{
	public class InsertToDatabase
	{
		// Step 1 - Create a connection string.
		string connectionString = @"Data Source = ServerName; user id=UserName; password=P@sswd!; Initial Catalog = DatabaseName;";
		// Step 2 - Create an insert query string
		string query = "INSERT INTO Users (Firstname, Lastname, Email) VALUES ('Jared','Barneck','Jared.Barneck@somedomain.tld')";
		// Step 3 - Create a SQLConnection object that uses the connection string.
		SqlConnection connection = new SqlConnection(connectionString);
		// Step 4 - Create a SqlCommand object that used both the SQLConnection and the query string.
		SqlCommand command = new SqlCommand(query, connection);
		// Step 5 - Open the connection.
		connection.Open();
		// Step 6 - Execute the query.
		command.ExecuteNonQuery();
		// Step 7 - Close the connection.
		connection.Close();
	}
}

What is the difference between a DataSet and a DataTable?

What is the difference between a DataSet and a DataTable?
Here is a link to the MSDN class information for both:
DataSet Class
DataTable Class

So a DataTable is just a table.

However, a DataSet is a collection of tables that can have their data linked together with a DataRelation Class.

So when accessing a database, which should you use?
Well, if you only need a single table, then just use a DataTable.
However, if you need multiple tables and those tables may have some type of relationship, use a DataSet.