Archive for September 2009

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

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.

What is the equivalent in Unix\Linux?

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.

Why can you not get your C++ program to accept ANY KEY in Unix/Linux?
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.

So how do I at least get the “You can press [Enter] only to continue.” option?

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

Doing it all in main.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 [ 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();
}

Doing it as a class or object

main.cpp

#include <iostream>
#include <Pause.h>

using namespace std;

int main()
{
	new Pause();
}

Pause.h

#include <iostream>

class Pause
{
	public:
		Pause();
};

Pause.cpp

#include <iostream>
#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();
}

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.

How do I access a MySQL database with C#?

This was a little bit easier for me because I had just figured all this out on Microsoft SQL and (lo and behold), MySQL had created the exact same function structure for MySQL.

So I read through this document first:
Beginning MYSQL 5 with Visual Studio.NET 2005.pdf

It was very informative and showed this code to get into a MySQL database:

string connectionString = "server=ServerName; user id=UserName; password=P@sswd!; database=MyDatabase";
string query = "Select * from users";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
    connection.Open();
    MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, connection);
    DataSet dataSet = new DataSet();
    dataAdapter.Fill(dataSet, "users");
}

I had been accessing tables in a Microsoft SQL database using a different set of functions, so I tested to see if the method I had been using for Microsoft SQL would work for MySQL, since the object and function names are almost identical.

The following code also accessed the database and I like it better because a DataTable seems more of an obvious choice to return data from table.

string connectionString = "server=ServerName; user id=UserName; password=P@sswd!; database=MyDatabase";
string query = "Select * from users";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
    connection.Open();
    MySqlCommand command = new MySqlCommand(query, connection);
    MySqlDataReader reader = command.ExecuteReader();;
    DataTable table = new DataTable();
    table.Load(reader);
}

So I left wondering how these two methods are different…I guess I need to answer the following:

  1. Which of the above two SQL database access methods should be considered best practice and why?
  2. Is one more efficient than the other?
  3. What is the difference between a DataSet and a DataTable?
    DataSet Class
    DataTable Class

Why my variable and object names in my code are so long

WhyMyVariableAndObjectNamesInMyCodeAreSoLong

Reason 1 – One of the main reasons that variable names have been shortened in the past are because you have to type them and the longer they are the longer they take to type. However, with today’s Integrated Development Environments (IDEs) you only have to type a few characters and then hit tab or enter and it finishes the variables for you. So this reason for short variable names has become a non-factor.

Reason 2 – The longer the variable name, the better documented your code is. Lets face it, there are those that demand documentation and those that argue that code should be so well written it doesn’t need documentation. So if I have a variable that represents the time it takes to drive to work, I will go ahead and make the variable name, theTimeItTakesToDriveToWork.

The Tower of Hanoi as an example of using a recursive functions in C++

I am not going to explain the Tower of Hanoi here. I assume if you are reading this you know what you are looking for. Otherwise, read this:
http://en.wikipedia.org/wiki/Tower_of_Hanoi

Main.cpp

#include <iostream>
#include "TowerOfHanoi.h"

int main()
{
	TowerOfHanoi *toh = new TowerOfHanoi(true);
	std::cout << toh->toString();
	toh->solve();
	system("pause");
}

TowerOfHanoi.h

#include <iostream>
#include <string>
#include <sstream>
#include <string>

#define leftPeg 1
#define middlePeg 2
#define rightPeg 3

class TowerOfHanoi
{
	public:
		// Constructors
		TowerOfHanoi(bool inPromptUser);
		TowerOfHanoi(int inNumberOfRings);

		// Destructor
		~TowerOfHanoi();

		// Other functions
		void solve();

		// Standard functions
		std::string toString();
		bool equals(TowerOfHanoi inTowerOfHanoi);

	private:
		void initializeClass(int inNumberOfRings);
		void runRecursiveAlgorithm(int inNumberOfRings, int mPegOriginallyHoldingRing, int inTemporaryPeg, int inDestinationPeg);
		std::string intToString(int i);
		int power(int inInteger, int inExponent);
		std::string getTabs();

		int mNumberOfRings;
		int mPegOriginallyHoldingRing;
		int mDestinationPeg;
		int mTemporyPeg;
		int mNumberOfStepsToSolve;
		int mStepCounter;
};

TowerOfHanoi.cpp

#include "TowerOfHanoi.h"
#include <iostream>
#include <string>
// Constructors
TowerOfHanoi::TowerOfHanoi(bool inPromptUser)
{
	int tmpNumberOfRings;
	std::cout << std::endl << "How many rings? [1 - 10] " << std::endl;
	std::cin >> tmpNumberOfRings;
	initializeClass(tmpNumberOfRings);
}

TowerOfHanoi::TowerOfHanoi(int inNumberOfRings)
{
	initializeClass(inNumberOfRings);
}

// Destructor
TowerOfHanoi::~TowerOfHanoi()
{
}

// Other functions
void TowerOfHanoi::solve()
{
	mStepCounter = 0;
	runRecursiveAlgorithm(mNumberOfRings, mPegOriginallyHoldingRing, mTemporyPeg, mDestinationPeg);
}

// Private functions
void TowerOfHanoi::initializeClass(int inNumberOfRings)
{
	mNumberOfRings = inNumberOfRings;

	mNumberOfStepsToSolve = power(2, inNumberOfRings) - 1;

	mPegOriginallyHoldingRing = leftPeg;
	mDestinationPeg = rightPeg;
	mTemporyPeg = middlePeg;
	mStepCounter = 0;
}

void TowerOfHanoi::runRecursiveAlgorithm(int inNumberOfRings, int mPegOriginallyHoldingRing, int inTemporaryPeg, int inDestinationPeg)
{
	std::string tabs = "\t\t";
	if (inNumberOfRings == 1)
	{
		std::cout << "Step " << ++mStepCounter << getTabs() << mPegOriginallyHoldingRing << " > " << inDestinationPeg << std::endl;
	}
	else
	{
		runRecursiveAlgorithm(inNumberOfRings - 1, mPegOriginallyHoldingRing, inDestinationPeg, inTemporaryPeg);
		std::cout << "Step " << ++mStepCounter << getTabs() << mPegOriginallyHoldingRing << " > " << inDestinationPeg << std::endl;
		runRecursiveAlgorithm(inNumberOfRings - 1, inTemporaryPeg, mPegOriginallyHoldingRing, inDestinationPeg);
	}
}

std::string TowerOfHanoi::getTabs()
{
	if (mStepCounter > 99)
	{
		return "\t";
	}
	return "\t\t";
}

// Standard functions
std::string TowerOfHanoi::intToString(int i)
{
	std::stringstream ss;
	std::string s;
	ss << i;
	s = ss.str();
	return s;
}

int TowerOfHanoi::power(int inInteger, int inExponent)
{
	int retVal = 1;
	for (int i = 0; i < inExponent; i++)
	{
		retVal *= inInteger;
	}

	return retVal;
}

// Standard Functions
std::string TowerOfHanoi::toString()
{
	return "Tower of Hanoi with " + intToString(mNumberOfRings) + " rings.\n";
}

bool TowerOfHanoi::equals(TowerOfHanoi inTowerOfHanoi)
{
	if (this->mNumberOfRings == inTowerOfHanoi.mNumberOfRings)
	{
		return true;
	}
	return false;
}