How to change the system date from the shell on FreeBSD?

The system date and time can be changed with the date command.

Set Date only

date YYMMDD

or

date YYYYMMDD

Set Date and Time

date YYMMDDHHMM

or

date YYYYMMDDHHMM

Set Time only

date HHMM

Example
So for example, if you want to set the date to Nov. 6, 2009 and the time to 8:58, you would use this command:

# date 0911060858

See man date for more information.


How to start, stop, restart MySQL on FreeBSD or Red Hat?

FreeBSD

Starting MySQL


/usr/local/etc/rc.d/mysql-server start

Stopping MySQL


/usr/local/etc/rc.d/mysql-server stop

Restarting MySQL


/usr/local/etc/rc.d/mysql-server restart

Red Hat

Starting MySQL


/etc/init.d/mysql start

or


/sbin/service mysql start

Stopping MySQL


/etc/init.d/mysql stop

or


/sbin/service mysql stop

Restarting MySQL


/etc/init.d/mysql restart

or


/sbin/service mysql restart


How to install MySQL on FreeBSD 7.2 or on Red Hat 5.4?

FreeBSD
There are two easy ways on FreeBSD:

From Ports

You can install easily from Ports. Make sure your ports tree is up to date:

$ su

Password:

ServerName#

ServerName#

ServerName#

portsnap fetch

portsnap extract

portsnap udpate

Then just do this to install MySQL on FreeBSD.

ServerName#

ServerName#

cd /usr/ports/databases/mysql51-server

make install

Or if you want to use utf8 by default, run this command:

ServerName# make WITH_CHARSET=utf8 install

MySQL 5.1 Server (and MySQL 5.1 client) will download, compile, and install automagically for you.

From Packages

You can also install easily as a binary package with this simple command.

ServerName# pkg_add -r mysql51-server

Make sure to secure you MySQL installation.
http://dev.mysql.com/doc/mysql-security-excerpt/5.1/en/default-privileges.html

Red Hat
Using RPM

You have to go to the MySQL site and download the MySQL 5.1 server RPM and install it.
http://dev.mysql.com/downloads/

It does not automatically install the MySQL client, you have to download that as a separate RPM and install it.

Using yum

Since I didn’t have a MySQL license, yum didn’t work, so I don’t know if it can be installed using yum.

Make sure to secure you MySQL installation.
http://dev.mysql.com/doc/mysql-security-excerpt/5.1/en/default-privileges.html


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 a UTF-8 Unicode Database on MySQL and make UTF-8 Unicode the default?

How to create a UTF-8 Unicode Database on MySQL?

I am not going to cover installing, I have done that here:
How to install MySQL on FreeBSD 7.2 or on Red Hat 5.4?

So when you open MySQL using the command line MySQL client, you can see what Character Set your server is configured to use with this command:

show variables like 'character_set_server';

Often the default is Latin-1. I wish UTF-8 was the default but it is not.

You can see the language your database is created with by using this command:

show create database dbname

Again, usually the default is Latin-1 and again, I wish the default were UTF-8 but it is not.

So how do I make my MySQL database UTF-8?
How do I make UTF-8 the default?

I am going to find out…

Ok, so I have MySQL installed on two different platforms:
FreeBSD 7.2 x64.
Red Hat 5.4 x64.

My question are these:
What level do you set the Unicode setting at? Install instance, database, or column type.

MySQL – Looks like it can be configured globally in the my.cnf or it can be database specific.

To configure globally

Add the following to the my.cnf file:

[mysqld]
init_connect=’SET collation_connection = utf8_general_ci’
init_connect=’SET NAMES utf8′
default-character-set=utf8
character-set-server=utf8
collation-server=utf8_general_ci
skip-character-set-client-handshake

Note: There are other options for collation besides utf8_general_ci such as utf8_unicode_ci. See this article:
http://dev.mysql.com/doc/refman/5.1/en/charset-unicode-sets.html

Do I have to create the database in a special way?

Not if you configure the setting globally. However, if you don’t configure unicode support globally then yes you have to create your database in a specific way.

I found this post that is for an applications that uses a MySQL Unicode database. I don’t care about the application, just the MySQL data.
http://dev.mysql.com/doc/refman/5.1/en/create-database.html
http://dev.mysql.com/doc/refman/5.1/en/charset-applications.html

So the syntax will be:

CREATE DATABASE mydb   DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;

Do I have to compile differently to get unicode support?

I didn’t have to recompile on either FreeBSD or Red Hat.

Is there differences for each platform?

Slight differences.

FreeBSD

FreeBSD has the MySQL client as a dependency so it gets installed with the server with out any extra work.

The Database folder is /var/db/mysql.

For the global configuration there is not a my.cnf file created by default.

FreeBSD has example my.cnf files located here:

/usr/local/share/mysql
/usr/local/share/mysql/my-huge.cnf
/usr/local/share/mysql/my-innodb-heavy-4G.cnf
/usr/local/share/mysql/my-large.cnf
/usr/local/share/mysql/my-medium.cnf
/usr/local/share/mysql/my-small.cnf

You can create your own my.cnf or you can copy one of the examples.

In order to get the my.cnf to work, you should copy it and change the owner and add the [mysqld] settings.

#
#
#
?
?
?
?
?
?
?
?
#
cp /usr/local/share/mysql/my-medium.cnf /var/db/mysql/my.cnf
chown mysql:mysql /var/db/mysql/my.cnf
cat << EOF >> /var/db/mysql/my.cnf
[mysqld]
init_connect=’SET collation_connection = utf8_general_ci’
init_connect=’SET NAMES utf8′
default-character-set=utf8
character-set-server=utf8
collation-server=utf8_general_ci
skip-character-set-client-handshake
EOF

Red Hat

Red Hat does not have the MySQL client installed with the server, you have to download a separate RPM and install it. But it is really easy. Download both RPMs and install them.

The Database folder is /var/lib/mysql.

For the global configuration there is not a my.cnf file created by default.

Red Hat has example my.cnf files located here:

/usr/share/mysql
/usr/share/mysql/my-huge.cnf
/usr/share/mysql/my-innodb-heavy-4G.cnf
/usr/share/mysql/my-large.cnf
/usr/share/mysql/my-medium.cnf
/usr/share/mysql/my-small.cnf

Same as FreeBSD, there isn’t one used by default and you have to copy one and use it.
You can create your own my.cnf or you can copy one of the examples.

In order to get the my.cnf to work, you should copy it and change the owner and add the [mysqld] settings.

#
#
#
?
?
?
?
?
?
?
?
#
cp /usr/share/mysql/my-medium.cnf /var/lib/mysql/my.cnf
chown mysql:mysql /var/lib/mysql/my.cnf
cat << EOF >> /var/lib/mysql/my.cnf
[mysqld]
init_connect=’SET collation_connection = utf8_general_ci’
init_connect=’SET NAMES utf8′
default-character-set=utf8
character-set-server=utf8
collation-server=utf8_general_ci
skip-character-set-client-handshake
EOF

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 do I install FreeBSD 8?

See the updated version here:
How to install FreeBSD 9

I do this:

  1. Download the DVD.
    1. Go to www.freebsd.org
    2. Click the yellow Get FreeBSD Now button
    3. Under your appropriate processor type (in my case it is usually i386 or amd64) click ISO.
    4. I download the DVD ISO. (You can download a bunch of CD ISOs if you want.)
    5. Note: There is also a boot only, which can download fast because it is small. I often use this option because of the way I install. However, it doesn’t have the install files, instead it just has the boot files. Once you get booted, it downloads the options you have chosen to install from FreeBSD’s website or a mirror. So while the download is faster, the install may take longer. However, if you are doing a minimal install, which I usually do, it could be faster than waiting for an entire DVD to download since the DVD includes a lot of data your won’t be using for a minimal install.

  2. Burn the ISO to disk. I am not going to explain how to do this but I will say this:
    Please make sure you don’t burn the ISO as a file on the disk, but instead you burn choose the option to burn a disk from the ISO.
  3. Boot from DVD.
    1. Put the DVD (or CD) in your drive.
    2. Turn on your system or if it is on, reboot it.
    3. Make sure you BIOS is configured to allow you to boot off the DVD or CD drive.
    4. Choose to boot from the DVD or CD drive.
  4. The first “gui-like screen you will see is the Country Selection screen. Choose your Country using the up and down arrows on your keyboard to highlight your country. Once your country is highlighted, hit Enter to choose OK.
  5. The next screen is the Main Menu. Again, use the up and down arrows on your keyboard to highlight Standard. Once Standard is highlighted, hit Enter to Select it.
  6. The following screen is an informational message. Read it if you like and hit enter to choose OK.
  7. The next screen appears like a DOS screen. It is asking how much of the disk you want to dedicate to FreeBSD. Dual-booting is actaully not common anymore because of virtualization such as VMWare, so I assume you are using the entire disk.

    Press “A” on the keyboard to select the Use Entire Disk option and then press “Q” to Finish.

  8. The next screen asks if you want a boot Manager. A boot manager is mostly likely used for dual booting, so choose Standard and hit enter.
  9. The following screen is a second informational message. Read it if you like and hit enter to choose OK.
  10. The next screen appears like a DOS screen and looks very similar to the previous DOS-like screen you saw, however it is not asking how much of the disk you are going to use for FreeBSD; instead, it is asking what partitions you want and how much space you want to allocate to each partition.

    Press “A” on the keyboard to select the Auto Defaults option and then press “Q” to Finish.

  11. The next screen is the Choose Distributions screen. So let’s choose your distributions.
    1. Use the down arrow to scroll all the way down to Custom and hit Enter. This brings up the “Select the distributions you wish to install” screen.
    2. Select base and hit Enter
    3. Select kernels and hit Enter and another screen appears.
      1. Select the GENERIC kernel and hit enter. This checks the box but does not continue.
      2. Press Tab to get the cursor over the OK button and hit enter. This takes you back to the “Select the distributions you wish to install” screen.
    4. Select games.

      You may want to skip this because you are thinking, this is my server, I don’t want games. But if you are reading this, then you are not a FreeBSD guru and you are problably a newbie. The “games” option includes simple command line only games and does not take up much space. The important thing is that it includes the feature where every time you log in, you get a nice tip. You can escape your newbie-ness by paying attention to these tips, so just select games already.

    5. Select man
    6. Press Tab to move the cursor over OK.
    7. Before hitting Enter, look at it one more time and make sure you have selected these options: base, kernels, games, man.

      Yes if you are NOT a newbie select whatever you want.

    8. Hit enter. This take you back to the Choose Distributions screen
  12. Just like the last screen, press Tab to move the cursor over OK and click enter.
  13. The next options is the Choose Installation Media screen. If you downloaded the CD or DVD, select CD/DVD (which is highligted by default) so just press enter.

    I am assuming you downloaded the DVD here. Screens may differ in order slightly if you used the Boot Only CD but you should be able to figure it out.

  14. The next screen is the User Confirmation Requested screen. Up until this point, nothing has been done to your system. You drive is untouched.

    Press Enter to choose Yes and install FreeBSD.

    The drive is formatted, configured to boot to FreeBSD, the partitions are created, and the base, kernels, games, man distributions are installed.

  15. The following screen is another informational message that tells you, “Congratulations! You now have FreeBSD installed on your system”. Read it if you like and hit enter to choose OK.
  16. Now you are at the Post-installation configuration screens. You will be asked a lot of questions, most of which you will say “No” too.

  17. Would you like to configure any Ethernet or SLIP/PPP network deices:

    Choose Yes.

    This opens the Network Interface screen.

    1. Select your Ethernet card and hit Enter. The card name is not always the same.
    2. Do you want to try IPv6 configuration of the interface?

      Choose No. (Maybe someday soon you will choose Yes here.)

    3. Do you want to try DHCP configuration of the interface?

      Choose No. (If you are not building a server then maybe you want DHCP but if you aren’t building a server, you should probably be installing PC-BSD.)

      The Network Configuration screen opens.

    4. Under Host enter you host name.
    5. Under Domain enter you domain name.
    6. Under IPv4 Gateway enter you default gateway’s IP address.
    7. Under Name server enter the DNS server’s IP address.
    8. Under IPv4 address enter the machine’s IP address.
    9. Under Netmask enter the subnet mask.
    10. Choose OK.
  18. Do you want the machine to function as a network gateway?

    Choose No.

  19. Do you want to configure inetd and the network services it provides?

    Choose No.

  20. Do you want to enable ssh login?

    Choose Yes.

  21. Do you want to have anonymous FTP access to this machine?

    Choose No.

  22. Do you want to configure this machine as an NFS server?

    Choose Yes.

  23. Do you want to configure this machine as an NFS client?

    Choose No.

  24. Would you like to customize your system console settings?

    Choose No.

  25. Would you like to set the machine’s time zone now?

    Choose Yes.

  26. Is this machine’s CMOS clock set to UTC?

    Choose No (unless you know that it is).

  27. Select a region.
  28. Select a Country.
  29. Select a time zone.
  30. Does the abreviation ‘MST’ look reasonable? (Your time zone acronym may be different.)

    Choose Yes.

  31. Would you like to enable Linux binary compatibility?

    Choose No.

  32. Does this system have a PS2, Serial, or bus mouse?

    Choose No if you have a USB mouse. Choose Yes if you have a PS2 mouse. (Usually a mouse that is not USB is uncommon these days, however, there are still plenty of PS2 mice around.)

  33. The FreeBSD package collection is a collection of thousands of ready to run applications, from text editors to games to WEB servers and more. Would you like to browse the collection now?

    Choose No.

  34. Would you like to add any initial user accounts to this system?

    Choose Yes.

    The User and Group Management screen appears.

  35. Select User and press Enter.

    The Add a new user screen appears.

    1. Under Login ID enter the user name.
    2. Leave the UID unchanged. By default is is 1001.
    3. Leave the Group field blank.
    4. Enter a password.
    5. Enter your full name.
    6. Under Member groups enter this group: wheel
    7. Leave the Home directory as is: /home/username
    8. Leave the Login shell as is: /bin/sh
    9. Tab to OK and press Enter.

      You are returned to the User and Group Management screen.

  36. Select Exit and press Enter.
  37. Now you must enter the systems management password.
    This is the password you’ll use to log in as root.

    Press Enter.

  38. Enter the new password.
  39. Retype the new password.
  40. Visit the general configuration menu for a chance to set any last options?

    You are returned to the sysinstall Main Menu.

  41. Tab to Exit Install and press Enter.
  42. Are you sure you wish to exit?

    Choose Yes. (Make sure to remove the bootable disk from the CD or DVD drive.

Your system will now reboot and FreeBSD should boot up.

Now check out my post about the updating FreeBSD.
What are the first commands I run after installing FreeBSD

This will tell you how to apply FreeBSD updates/patches and how to load the ports tree.


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 do I install FreeBSD?

I have an article depending on the version you are trying to install

I also have aarticles for dual-booting.


How to make a nice box of shell commands that show the prompt text and the command text but allows coping the shell commands without the shell prompt

Ok so this is a trick that involves two elements:

  1. An html box made from an html division element, that I describe here:
    How to make a nice quote field with a different background color in your WordPress blog post?
  2. A table with only one row and two columns. The first row has the prompt text and the second row has the command text. You don’t create multiple table rows. Instead, you only have one row and for line, both columns will use a html break.

Short version

<div style="width:90%;background-color:#363636;color:#ffffff;border-style:ridge;border-width:5px;padding:10px;font:courier-new">
<table><tr><td valign="top">
#
</td>
<td style="white-space: nowrap">
command 1
</td></tr></table>
</div>
# command 1

Long version

<div style="width:90%;background-color:#363636;color:#ffffff;font:courier-new;border-style:ridge;border-width:5px;padding:10px;">
<table><tr><td valign="top">
#<br />
#<br />
#<br />
#<br />
#<br />
#<br />
#<br />
#<br />
#<br />
</td>
<td style="white-space: nowrap">
command 1<br />
command 2<br />
command 3<br />
command 4<br />
command 5<br />
command 6<br />
command 7<br />
command 8<br />
</td></tr></table>
</div>

It looks like this:

#
#
#
#
#
#
#
#
#
command 1
command 2
command 3
command 4
command 5
command 6
command 7
command 8
command 1

And a good example of really using this trick with a little more complexity would be this example of logging into to FreeBSD as a user, then switching to run a shell as root and running commands.

<div style="width:500px;background-color:#363636;color:#ffffff;border-style:ridge;border-width:5px;padding:10px;">
<table><tr><td valign="top">$<td style="white-space: nowrap">su</td></tr></table>Password:
<table><tr><td valign="top">
ServerName#<br />
ServerName#<br />
ServerName#<br />
ServerName#<br />
</td><td style="white-space: nowrap">
freebsd-update fetch<br />
freebsd-update install<br />
portsnap fetch<br />
 portsnap extract<br />
</td></tr></table>
</div>
$

su

Password:

ServerName#
ServerName#
ServerName#
ServerName#
freebsd-update fetch
freebsd-update install
portsnap fetch
portsnap extract

You can easily make this green on black just by changing the color and background-color values in the division element.

<div style="width:500px;background-color:#000000;color:#00cc00;font:courier-new;border-style:ridge;border-width:5px;padding:10px;">
<table><tr><td valign="top">
$
</td><td style="white-space: nowrap">
su
</td></tr></table>

Password:

<table><tr><td valign="top">
ServerName#<br />
ServerName#<br />
ServerName#<br />
ServerName#<br />
</td><td style="white-space: nowrap">
freebsd-update fetch<br />
freebsd-update install<br />
portsnap fetch<br />
 portsnap extract<br />
</td></tr></table>
</div>

A green on black version would look like this.

$

su

Password:

ServerName#
ServerName#
ServerName#
ServerName#
freebsd-update fetch
freebsd-update install
portsnap fetch
portsnap extract

What are the first commands I run after installing FreeBSD? Or How to patch FreeBSD? Or How to install ports on FreeBSD?

Ok, so you just installed FreeBSD, an maybe you are not familiar with it, so you think, “What now?”.

Well, think about what you do when you install any platform. You do three things:

  1. Apply patches/updates.
  2. Install software
  3. Post-installation configuration of system and software

For example, when you install a new windows operating system, it is common to go to Windows Update and update your server. Then you install software such as microsoft office, etc… The same for servers. You update the server, then maybe you add your server software. Then you configure it some more.

The order may vary for every install or you may even do this three step process multiple times.

Just because you are on FreeBSD does not mean the same three step process doesn’t apply. This three item process is operating system independent. It is the first thing I do on FreeBSD as well.

So here are the first commands that I run after logging into a new FreeBSD install.

$ su

Password:

ServerName#
ServerName#
ServerName#
ServerName#
freebsd-update fetch
freebsd-update install
portsnap fetch
portsnap extract

Same commands in a nice script/code box you can use to copy and paste.

freebsd-update fetch
freebsd-update install
portsnap fetch
portsnap extract

Let me explain what each command does:

  1. freebsd-update fetch – This download patches that have been released for the version of FreeBSD you have installed. It does not install the patches.
  2. freebsd-update install – This command installs the patches that were previously download.
  3. portsnap fetch – This download a compressed version of the ports tree. Ports means applications that have been ported or developed to compile and run on FreeBSD. So the ports tree is basically a database of available software that can be install on FreeBSD.
  4. portsnap extract – This extracts the compressed version of the ports tree.

So with these four commands you have your system updated/patched. You also have all the software that is available ready to be installed.

Update 1:

I am not sure why i didn’t know this before, but you can combine each pair of commands into one command:

ServerName#
ServerName#
freebsd-update fetch install
portsnap fetch extract
freebsd-update fetch install
portsnap fetch extract

Stay tuned for my article on searching the ports tree.

Update 2:

As you can read in the comments, it is good to know that you only have to “extract” the ports tree once and for every subsequent update to the ports tree, you should only run it with the “update” command as shown.

portsnap fetch update

How to execute SQL statement that has a single quote in C# or insert a row with a value that has a quote?

Imagine you have a query such as the following:

SELECT * FROM User WHERE LastName='O'Conner'

INSERT INTO User (FirstName, LastName, UserName, Email) VALUES ('John','O'Conner','jo'conner','joconner@somedomain.tld')

Well, that is obviously not going to work, because the apostrophe or single quote in the name O’Conner is going to break the query syntax.

You have to have two single quotes to use a quote.

SELECT * FROM User WHERE LastName='O''Conner'

INSERT INTO User (FirstName, LastName, UserName, Email) VALUES ('John','O'Conner','jo''conner','joconner@somedomain.tld')

Ok, so there are two ways to make sure you have two quotes in C#:

  1. You manage the query string yourself.
  2. You use a DataTable and let it manage the query string for you.

Managing the query string yourself

Ok, the answer is simple. You need two single quotes next to each other.

Now, when you have single string, this is easy to do. You need to replace each instance of a single quote with two single quotes using this function which already exists for you:

string.replace(string inStringToBeReplaced, string inNewString)

Here is an example of doing it wrong, then fixing it. Step through this in a debugger.

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

namespace SingleQuoteInSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            string FirstName = "John";
            string LastName  = "O'Conner";
            string UserName  = "joconner";
            string Email     = "joconner@domain.tld";

            // Both these queries are broken because of the space.
            string strQuery1 = "SELECT * FROM User WHERE LastName='" + LastName + "'";
            string strQuery2 = "INSERT INTO User (FirstName, LastName, UserName, Email) VALUES (" +
                        "'" + FirstName + "'," +
                        "'" + LastName + "'," +
                        "'" + UserName + "'," +
                        "'" + Email + "')";

            // This will actually break your query too, because it will replace valid single quotes
            // with two single quotes.  You need to do this on the actually data strings.
            strQuery1 = strQuery1.Replace("'", "''"); //
            strQuery2 = strQuery1.Replace("'", "''");

            // Replace any intance of a single quote with two single quotes, ''.
            // IMPORTANT: Typing two single quotes ('') is not the same as a double quote (").
            FirstName = FirstName.Replace("'", "''");
            LastName = LastName.Replace("'", "''");
            UserName = UserName.Replace("'", "''");
            Email = Email.Replace("'", "''");

            // Both these queries are working now;
            strQuery1 = "SELECT * FROM User WHERE LastName='" + LastName + "'";
            strQuery2 = "INSERT INTO User (FirstName, LastName, UserName, Email) VALUES (" +
                        "'" + FirstName + "'," +
                        "'" + LastName + "'," +
                        "'" + UserName + "'," +
                        "'" + Email + "')";
        }
    }
}

Using a DataTable to manage this for you automagically

This actually looks like more work at first, but really when handling a lot of data, it is much more easy to code using DataTables and DataRows.

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

namespace SingleQuoteInSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            string FirstName  = "John";
            string LastName  = "O'Conner";
            string UserName  = "joconner";
            string Email        = "joconner@domain.tld";

            // Create the connection
            string mConnectionString = "Data Source=ServerName; user id=UserName; password=pw; Initial Catalog=DatabaseName;";
            SqlConnection mSqlConnection = new SqlConnection(mConnectionString);

            // Create a data adapter, this is what does the magic.
            String mQueryForSqlDataAdapter = "Select * from TableName";
            SqlDataAdapter tmpSqlDataAdapter;
            SqlCommandBuilder tmpSqlCommandBuilder;
            DataTable tmpDataTable = new DataTable();
            tmpSqlDataAdapter = new SqlDataAdapter(mQueryForSqlDataAdapter, mSqlConnection);

            // Use the SqlDataAdapter to create a table with the right schema but no data
            tmpDataTable = tmpSqlDataAdapter.FillSchema(tmpDataTable, SchemaType.Mapped);

            // Create a SqlCommandBuilder
            tmpSqlCommandBuilder = new SqlCommandBuilder(tmpSqlDataAdapter);

            // Create a DataRow and populate it
            DataRow row = tmpDataTable.NewRow();
            row["FirstName"] = FirstName;
            row["LastName"] = LastName;
            row["UserName"] = UserName;
            row["Email"] = Email;

            // Add this row to the DataTable
            tmpDataTable.Rows.Add(row);

            // Write this to the database
            tmpSqlDataAdapter.Update(tmpDataTable);
        }
    }
}

Notice we didn’t have to do a string replace of ‘ for ”.


How to delete a vector of pointers in C++?

Ok, so lets say you have a pointer to a vector of pointers and you delete the pointer to the vector. That will result in a memory leak.

Here is an example of a memory leak.

#include <vector>
using namespace std;
int main()
{
	// This is one pointer to a vector of pointers
	vector<int*> *intList1 = new vector<int*>();
	for (unsigned short i = 0; i < 10; i++)
	{
		intList1->push_back(new int(i));
	}
}

Ok, so now that I have shown you this code that can be a memory leak, lets look at some more code to see why.

Step through this code in a debugger and read the comments to help you understand what is happening.

#include <vector>

using namespace std;

/*
 * Pointer deleter for a vector of pointers
 */
template <class T>
void deleteVectorOfPointers( T * inVectorOfPointers )
{
    T::iterator i;
    for ( i = inVectorOfPointers->begin() ; i < inVectorOfPointers->end(); i++ )
    {
        delete * i;
    }
    delete inVectorOfPointers;
}

int main()
{
	// This is one pointer to a vector of pointers
	vector<int*> *intList1 = new vector<int*>();
	for (unsigned short i = 0; i < 10; i++)
	{
		intList1->push_back(new int(i));
	}

	// This is another pointer to a vector of the same pointers

	vector<int*> *intList2 = new vector<int*>();
	for (unsigned short i = 0; i < intList1->size(); i++)
	{
		intList2->push_back(intList1->at(i));
	}

	// This is a third pointer to a vector of the same pointers

	vector<int*> *intList3 = new vector<int*>();
	for (unsigned short i = 0; i < intList1->size(); i++)
	{
		intList3->push_back(intList1->at(i));
	}
	// Break here and look at the three vectors.
	// - Notice all 10 elements in each vector are the exact same
	// memory locations.
	// - Notice the memory locations hold values 0 thru 9

	// Delete the intList pointer
	delete intList1;

	// Break here and look at the three vectors.
	// One is deleted, but the other two are still there and all
	// the vectors' pointers are still there and did not delete.

	// Delete all the pointers in the vector.
	deleteVectorOfPointers(intList2);

	// Stop here and look at the three pointers.
	// Specifically look at the values of intList3.  They no longer
	// hold values 0 thr 9 because they were deleted since they
	// are the same pointer that intList2 had.

	// We don't need to delete the pointer in intList3 because
	// they were already deleted.
	delete intList3;
}

So in conclusion you can see that the problem with deleting the pointer to the vector is that deleting the pointer to the vector doesn’t delete the pointers added to the vector. You don’t want to leave 10 pointers hanging around in memory every time you use a piece of code.

You have to first delete the pointers added to the vector, and then delete the pointer to the vector.


How to query for the amount of objects in Salesforce?

Well, this was simple.

It is almost the same as doing a count in a MS SQL or MySQL query, only you don’t specify a column name or a * inside the parenthesis.

SELECT count() FROM SalesForceObject

So for example if you wanted to know how many User objects, you could run this SOQL query:

SELECT count() FROM User

Which Operating System release are you most excited about?


How long have you been using Windows 7?

So Windows 7 has been around in Release To Manufacturer (RTM) for since August 14, 2009.

Many have been using it in production since then. In fact, many have been using in Production since it was still in beta/release candidate form.

I have been using it for 1 month.

Quick Opinion
It is so much better than Vista and XP that it would take a novel to describe all the ways it is better. Most of them are simple things.

Anyway, please post comments on how long you have been using Windows 7 and why you like it.


How to convert an int to a character array when you don't have access to the C++ Standard Library?

Ok, so I have a great way to convert and int (or any other type) to a string using the stringstream from the standard library. This is listed here:
How to convert an int to a string in C++? (Also doubles, floats, etc…)

However, what do you do if you don’t have access to the C++ Standard Library? There is not stringstream or string so the solution in the above linked-to post won’t work.

So I have created a simple class Int.h that can do this conversion without the C++ Standard Library. Notice it is Int.h with a capital “I”.

It handles both positive and negative numbers.

Int.h

#pragma once

class Int
{
public:
	// Constructor
	Int(int inInt);

	// Desctructor
	~Int();

	// Public functions
	void intToCharArray(char inChar[]);
	char * intToCharArrayPointer();

private:
	// Members
	int mInteger;

	// Functions
	char digitToChar(int inInt);
};

Int.cpp

#include "Int.h"

Int::Int(int inInt)
{
	mInteger = inInt;
}

Int::~Int()
{
}


char Int::digitToChar(int inInt)
{
	char digit[11] = {'0','1','2','3','4','5','6','7','8','9'};
	//digit[0] = '';
	for (short i = 0; i < 10; i++)
	{
		if (inInt == i)
		{
			return digit&#91;i&#93;;
		}
	}
	return '';
}


void Int::intToCharArray(char inChar&#91;&#93;)
{
	char tmpVal&#91;11&#93;;
	int tmpInt = mInteger;
	bool isNegative = false;

	if (mInteger < 0)
	{
		tmpInt *= -1;
		isNegative = true;
	}

	short i = 0;
	while (tmpInt > 0)
	{
		int rightDigit = tmpInt % 10;
		tmpVal[i] = digitToChar(rightDigit);
		tmpInt = tmpInt/10;
		i++;
	}
	tmpVal[i--] = '';
	// tmpVal should now be the number in reverse.

	short j = 0;
	if (isNegative)
	{
		inChar[j++] = '-';
	}
	while (i > -1)
	{
		inChar[j++] = tmpVal[i--];
	}
	inChar[j] = '';
	// inChar should now be the number in correct order.
}

char * Int::intToCharArrayPointer()
{
	// Integers hold as many as 10 character, plus 1 for the null char.
	char * retVal = new char[11];
	intToCharArray(retVal);
	return retVal;
}

Here is a quick example of how to use it. Load this up in your favorite IDE/debugger.

Main.cpp

#include "Int.h"

int main()
{
	Int int1 = 1027;
	Int int2 = -2387809;

	char * charPtr = int1.intToCharArrayPointer();
	char charBuff[11];
	int2.intToCharArray(charBuff);
}

I haven’t seen it fail to convert any integers, positive or negative yet. Let me know if you see anything I could improve on.


How to post code in a wordpress blog so it maintains its formatting?

Hey all,

This was really easy to figure out, since there is a nice WordPress discussion about it here:
http://en.support.wordpress.com/code/

So a quick example:

So if you want your code to show up in your post and be nicely formatted and colored, similar to how it is in your favorite IDE, then put your code in between the following lines:

[sourcecode language=”cpp”]
int main()
{
    //Code
}
[/sourcecode]

It looks like this:

int main()
{
	//Code
}

Put your cursor over the code and check out the top right icons that appear. You can simply click an icon to open the source in a text editor or copy the source to your clipboard.

By the way, you must have the “language=” tag and you must use one of the following short names for the code language:

  • bash
  • cpp
  • csharp
  • css
  • delphi
  • html
  • java
  • jscript
  • php
  • python
  • ruby
  • shell
  • sql
  • vb
  • xml