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

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? &#91;1 - 10&#93; " << 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;
}

Understanding the Unary Scope Resolution Operator

The Unary Scope Resolution Operator is used to access a global variable when a local variable of the same name exists.

For example, look at the following code

#include
using namespace std;

int number = 100;

int main()
{
double number = 27.9;

int a = number;
// The global variable ::number is intended.
// This line should be: int a = ::number;
cout << a; cout << number; cout << ::number; } [/sourcecode] Question
What is the value of A going to be? 27.9 or 100?
Answer
Neither, it will be 27.

Explanation
One can assume that because variable a is an int and the global variable number is an int, that the global variable ::number was intended over the local variable number.

However, the local variable number that is a double was used.

Since variable a is an int, the value of the local variable number is casted to an int when assigned, so 27.9 becomes 27.

This can lead to difficult to solve bugs. The value should be 100 but is 27.

Looking at the code, this doesn’t look obviously wrong.

If a developer makes it a practice to always preface global variables with the Unary Scope Resolution Operator, such bugs can be avoided.

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

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

Having used other languages where this is much simpler, I was surprised at how “not simple” this was in C#. I expected it to be a little more complex than in some scripting language such as PHP, but it was way more complex.

Here is how I do it:

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

namespace CountRows
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a string to hold the database connection string
            string sdwConnectionString = @"Data Source = ServerName; user id=UserName; password=P@sswd!; Initial Catalog = DatabaseName;";

            // Create a string to hold the database connection string
            string query = "SELECT * FROM MyTable";

            // Pass both strings to a new SqlCommand object.
            SqlCommand queryCommand = new SqlCommand(query, sdwDBConnection);

            // Create a SqlDataReader
            SqlDataReader queryCommandReader = queryCommand.ExecuteReader();

            // Create a DataTable object to hold all the data returned by the query.
            DataTable dataTable = new DataTable();
            dataTable.Load(queryCommandReader);

            // The DataTable object has a nice DataTable.Rows.Count property that returns the row count.
            int rowCount = rowCount = dataTable.Rows.Count;
        }
    }
}

Now doing it this way, you also have the data available in the DataTable dataTable object so you don’t have to go to the database and get it again.

 

Return to ADO.NET and Database with C#

How I get the number of a rows in a Micorosft SQL table using C#?

How I get the number of rows in a table using C#?

Here is a step by step:

Step 1 – Create a new class: (attached click here: SQLTableRowCounter.cs)

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

namespace SQLTableRowCounter
{
    class SQLTableRowCounter
    {
        private string mCountQuery;
        private SqlConnection mConnection;
        private int mNumberOfRows;

        public SQLTableRowCounter(String inTableName, SqlConnection inConnection)
        {
            mCountQuery = "SELECT COUNT(*) FROM " + inTableName;
            mConnection = inConnection;
            mConnection.Open();
            SqlCommand mCountQueryCommand = new SqlCommand(mCountQuery, mConnection);
            mNumberOfRows = (int)mCountQueryCommand.ExecuteScalar();
        }

        public int NumberOfRows
        {
            get { return mNumberOfRows; }
            set { mNumberOfRows = value; }
        }
    }
}

Step 2 – Now create the object and get the value:

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

namespace SQLTableRowCounter
{
    class Program
    {
        static void Main(string[] args)
        {
             string connectionString = @"Data Source = ServerName; user id=UserName; password=P@sswd!; Initial Catalog = DatabaseName;";
             SqlConnection connection = new SqlConnection(connectionString);
             SQLTableRowCounter qrc = new SQLTableRowCounter("TableName", connection);
             int numRows = qrc.NumberOfRows;
        }
    }
}

Welcome to my new blog

Hey all,

I have had a computer since 1984 when I was 7.  I have been a computer geek most of my life.  I have ten years of intense technical support experience with computer operating systems, networking equipment, and desktop management.

I am currently a Systems Analyst / Developer for LANDesk.

I know FreeBSD, Linux, Windows.  I have worked with the following languages: C++, C#, Java, PHP and dabbled with a couple others.
I have worked with the following database: MySQL, MS SQL, Postgresql.

I need a place to store my knowledge.  I need a location to store my knowledge that I am sure will not disappear.  If I find a good knowledge source, the page may change or the site may be discontinued. Or I may never find a good source and I have to figure something out through trial an error, and a text file on my laptop is probably going to get lost and it also doesn’t help anybody else out.

So I hope this site eventually helps you as much as it helps me.

Thanks,

Rhyous (Jared Barneck)