Just Code it!
Header

This post is a tutorial that will explain hot to write a simple C++ code that can be considered the starting point for any other program you intend to write in C++ with the intention to use a MySQL Database.

In order to connect to MySQL from C++ we will use some libraries specifically designed for this purpose.

Despite the concept seems simple, there are a series of gotchas and configurations that can put off the task many people, increasing the amount of work needed and not necessarily forecasted.

This tutorial will reach the goal starting essentially from scratch, where the environment needs to be completely configured… even without Visual Studio!

While writing this tutorial, I decided to split it in multiple sub-posts because of the amount of information I ended up collecting. Doing this will remove some of the noise around the main topic and will allow to follow the post and the specific sections even for people with different requirements that have already available some of the systems I am going to describe.

As a reference, these are the additional posts:

 

Enough said, let’s start the journey! See you at the end of this. Happy reading.

mysql-connector (1.1.4) – Download

First things first… let’s immediately download what we are really interested in, the C++ libraries (source) that will allow us to connect and interact with a MySQL database.

Open the browser to the MySQL website and navigate to the page with the information about the connector:

http://dev.mysql.com/downloads/connector/cpp/

Select the “Source Code” option from the drop-down menu:

Download the generic Windows version:

In the following page select your preferred download option or just download it using the link at the bottom of the page:

Let’s remember the warning reported on the website:

Warning
One problem that can occur is when the tools you use to build your application are not compatible with the tools used to build the binary versions of MySQL Connector/C++. Ideally, you need to build your application with the same tools that were used to build the MySQL Connector/C++ binaries. 

 

Create a folder, for example “C:\libs\” and extract the archive in there.

The structure should look like this:

In order to build the source code for the connector libraries we need to download CMake.

It’s time to switch to the first sub-post if you need to perform this step and install CMake (CMake Installation and usage (Command Prompt Console and GUI)).

Jump to this post and see you here once you are ready to continue (I would suggest you to follow just the initial part of the tutorial, limited to installing it. The remainder will be useful later on and will probably not work on your system if you don’t have everything else already configured): CMake Installation and usage

Back from CMake Installation

I will assume that you have CMake installed on your system now.

mysql-connector 1.1.4 – Build – First Potential Problem (Missing Visual Studio)


If we try to run the CMake command to generate the Visual Studio solution from the mysql-connector code we could potentially immediately receive an error.
Let’s try this using the Command line:

C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

If you don’t have the C/C++ compiler then you will see this error:

Pay particular attention to the lines:

If that’s the case, what you need to do is installing Visual Studio.

Visual Studio (C++ 2010 Express)

Let’s download Visual Studio (Visual C++ 2010 Express is ok for us)
Go to the website:
and find the Install Now link:
Install it executing the installation file (vc_web.exe) downloaded.
Then try again!

mysql-connector (1.1.4) – Build – Second Potential Problem (Missing Boost Libraries)

If we try again now:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”
This time it should go further and complain about the (potential) next problem:

 

The main issue is now:

The problem now is that in order to build this code you need to have installed the BOOST libraries.
If that’s the problem you see as well, then you can happily jump to the next sub-post where is explained in detail how to install and configure boost libraries: Boost Libraries Installation
See you when you are ready to proceed!

Back from Boost Libraries Installation

You should now have a system with CMake, Visual Studio and Boost Libraries installed and configured. Time to continue!

mysql-connector (1.1.4) – Build – Third Potential Problem (MySQL not installed)

Go back into the connector folder and execute again:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

NOTE:

If you decided at any point to move the folder after executing cmake the first time you will potentially see an error:

To quickly fix this, just remove the file “CMakeCache.txt” and run cmake again.

If you don’t have MySQL installed on your system, then you will probably see this error:

The main indicator for this problem is the line:
If that’s what you see as well… well, you know what’s coming. Yep, another sub-post: MySQL Service, Workspace, Users and Tables
Jump to this post and you can read for now just the initial part that covers the download and installation of MySQL.
The rest of that post will show how to create a database, user and table that we will here, but you can go back to that section later on.

Back from MySQL installation

If everything went as planned until this point you should have CMake, Boost libraries,Visual Studio and MySQL installed and ready to rock.

mysql-connector (1.1.4) – Build – Creating the Visual Studio Solution

Now we can go back into our connector folder and try once again to recreate our Visual Studio Solution.
Yhou can follow this step in the CMake tutorial if you want (where it is explained how to obtain the same result using the command line or the GUI).
This is an extract of it, where I will show only the command line option.
If you run the same command again:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

You should finally succeed in this step, obtaining:
Now, if everything went as planned, you should be able to see a solution file (and other files as well) into your connector’s folder:
Now we can finally open the created solution (MYSQLCPPCONN.sln) with Visual Studio!
Simply double-click on:
MYSQLCPPCONN.sln

Build MySqlCppConn.sln – Debug

In Visual studio, set the configuration to DEBUG and try to Build.
What should happen is that you will see a series of errors:
ERRORS:

Open the properties for the project “mysqlcppconn“. Right-click on it and select “Properties”:

We can do this using different techniques, but I want to use one (even if it is not my preferred one) just for a change :).

 

Make sure to be in the configuration “Debug” and go in the section:

Common Properties -> Linker -> Input

 

Open the “Additional Dependencies” drop-down list and click on “<Edit…>”:

Substitute the entry:

  • C:\Program Files\MySQL\MySQL Server 5.6\lib\mysqlclient.lib
with:
  •  C:\Program Files\MySQL\MySQL Server 5.6\lib\debug\mysqlclient.lib

If you build now you could receive another error:


Open the project properties for the project “mysqlcppconn-static

Go in the section:
Common Properties -> Librarian -> Command Line
and change the additional options from:
  • C:/Program Files/MySQL/MySQL Server 5.6/lib/mysqlclient.lib
to:
  •  “C:/Program Files/MySQL/MySQL Server 5.6/lib/debug/mysqlclient.lib”
including the quotes
Build again and everything should be ok now!

Build MySqlCppConn.sln – Release

For the release build the only fix I had to do was only the “Additional Options” section in the Librarian -> Command Line

section for the “mysqlcppconn-static” project (in Release configuration).

Add the quotes to:

  • C:/Program Files/MySQL/MySQL Server 5.6/lib/mysqlclient.lib
Also in this case you should receive a successful compilation:

 

Libraries

If you open now the window explorer in the connector folder, in the sub-folder “driver”:
C:\libs\mysql-connector-c++-1.1.4\driver
you should see the two build folders “Debug” and “Release”:
Inside these you should find at least the three files:
  • mysqlcppconn.dll
  • mysqlcppconn.lib
  • mysqlcppconn-static.lib
We are ready to use it finally!

Creating a DB

It is finally time to create a database in MySQL that we will use in C++.
You can refer back to the post already highlighted previously (MySQL installation and Usage) and continue to follow it from where you left it until the end.
In that tutorial I explain how to create a sample DB with a sample user that will have access rights and a sample table that we will be able access from code.
When that system is ready, is time to jump into the final step!

Coding – Create a new Visual Studio Solution

In Visual Studio create a new project (I selected a simple Win32 Console Application)
Right click on the source folder and add a new cpp file:
Let’s give it a simple name (the very original “main.cpp” :P):
You should see the new file added:
Before writing any code, let’s configure our environment setting up the folder and libraries that we need to use/reference in order to successfully build our app.

Coding – Configure the Environment


Open the properties window of the project and go to the settings page:
Configuration Properties -> VC++ Directories
And edit the entry:
Include Directories
Make sure you are in the “All Configurations” configuration:

Edit it adding the lines:

C:\libs\mysql-connector-c++-1.1.4\cppconn

C:\Boost\include\boost-1_56

Edit then the Library Directories property, adding the line:

C:\libs\mysql-connector-c++-1.1.4\driver\$(Configuration)\

Edit then the property in:

Configuration Properties -> Linker -> Input -> Additional Dependencies

adding the line:

mysqlcppconn.lib

One last step you may need to do is copying the “libmysql.dll” and “copy “mysqlcppconn.lib” into your output folder.

Just open the properties to:

Configuration Properties -> Build Events -> Post-Build Event

Then edit “Command Line” and type in this (or the equivalent line that you need in order to copy the missing dll to the output folder):

copy “C:\Program Files\MySQL\MySQL Connector C 6.1.5\lib\libmysql.dll” “$(OutDir)”

copy “C:\libs\mysql-connector-c++-1.1.4\driver\$(Configuration)\mysqlcppconn.dll”  “$(OutDir)”

Remember to edit All Configurations:

Finally it’s time to code!

Coding – Code: Connecting to MySQL

Open the “main.cpp” and let’s put some code.

The first simple code will just test the library, connecting to the DB (our one) using the user that we previously set-up in MySQL Workbench.
Remember to configure correctly:
  • The database address (and port)
  • The User and Password for your user
  • The Database name (that contains the “contacts” table)
That’s the simplest code with some error handling:

If your run this code and you didn’t set-up correctly one of the used parameters, then you will see the error text (without crashing). If that’s the case, check your parameters and verify that you will see the “Connection to the DB established!” string.

Coding – Code: Connecting and using the DB

For the final part of this post we are going to see how to connect now to our DB and retrieve and print the data from our table!
The new lines are the ones that follow the connection established message and few extra includes.
I will omit any exception handling to keep the code short and simple.
This is the final code:

If you build and run the code, you should be finally happily able to see the rows that we entered in our table using MySQL Workbench!


 

That’s all!

 

Of course you can now play around with it inserting, editing, removing entries. For these functionalities and more advanced one I point you to the official website and in particular to the Developer Zone:
Please Link and comment if you found this interesting or useful.

Boost Libraries Installation

January 25th, 2015 | Posted by riccardotramma in Boost | C++ | Download - (0 Comments)

This post is really a subpost I made while I was writing a larger post where I explain how to download and use MySQL connector C++ libraries (MySQL C++ with mysql-connector).

That post soon became pretty big due to the amount of stuff you need to configure in order to achieve the goal, therefore I decided to split it in smaller posts that one one side are useful on their own and on the other helps in keeping the main post they came from slightly smaller and easier to follow. Because of this I will keep these posts quite short.

If you are interested in this post as well, you can fint it there:

Let’s enter in the core of the topic now!

 

Boost Libraries (1.56.0) – Download
Let’s download them here:
Just click on the Download link:
Click then on the zip file:
Once downloaded extract it, for example in the same lib folder, so you should now have:
Boost Libraries (1.56.0) – Install
Enter into the boost_1_56_0 folder and execute the file “bootstrap.bat“:
C:\libs\boost_1_56_0>bootstrap.bat
The output should be: 
The next step, is to execute “.\b2”. We could use some parameter here, such as:
b2 install –prefix=PREFIX 

where PREFIX is a directory where you want Boost.Build to be installed.
Optionally, add PREFIX/bin to your PATH environment variable. 

We will be ok with the default setting, therefore we will just execute:

C:\libs\boost_1_56_0>b2 install
It will start to compile the code… it will take a bit and a loooong output.
The initial part will be something along this line:

 

Once this is done you should see a new folder on your drive: “C:\Boost\
This is how the situation should look like at this point:
That’s it for this part.
As mentioned this is a subpart I splitted from a larger topic.
If you want to continue the reading of the original topic that originates this continue here: MySQL C++ with mysql-connector
Thanks and share and comment if you find this useful or interesting.

Comment or Leave a Message

Please Comment or Leave a Message if this is what you are looking for or if you have any question/comment/suggestion/request.

If you are reading this post it is probably because you have some trouble trying to have your application to run on a system where some COMs dependencies don’t seem to be happily resolved, or because you can’t afford to register the COMs at all (policy?)… or if you don’t have any COM problem at all, well… keep reading. The DLL Hell is always behind the corner.
Because the problem is quite annoying when happens, I provide at least four solutions so that you can choose the one you find more comfortable to use :). Let me know which one you prefer and if you know other alternative ways to do it as painlessly as possible.

The Problem
Imagine to have a simple application that references a COM object. You try to build your COM and then your app, and eventually you try to run it on your machine and… it works! Good! So you happily go and copy your App and the DLL of the COM in a single folder on a second machine and… BUM! Your App crashes without hope.
So, what’s going on?
The problem relies on the fact that when you use a COM DLL (with Early Binding), you are somehow coupling your App with a precise version of your COM library. This means that if one day you or someone else upgrades the COM DLL, then the App will still continue to work using the original COM it was binded to. What really happens is that your App will not simply try to locate the DLL (using only its name) in the current folder and then in the PATH environment variable, but will actually use a GUID (the CLSID) to locate the COM DLL in the Windows Registry and from there locate the file in the file system. GUID stands for Globally Unique IDentifier (while CLSID is the CLaSs IDentifier) and is automatically generated for you when you create the COM object and automatically used when you reference your COM from your App. If you want to see how to use a COM you can have a look at my other post ([intlink id=”114″ type=”post”]Create a .NET COM and use it in Unmanaged C++[/intlink]).
This GUID is then the only thing that the App will use to locate the COM DLL, and in order to make this work you have to “Register” your COM classes as we already know.
So, what if you don’t want to register it?

Sample Scenario
Let’s assume that we have a couple of COM DLLs with one sample Object each and both with a simple (different) method defined. In my example I have these:

  • MyPippoCOM COM with a SillyAdder class (CoClass)
  • MyOtherCOM COM with a SmarterMultiplier CoClass
  • TestApp exe that uses the two previous COMs using Early Bindings

In TestApp I instantiate the objects using the ProgID.

The Tool
Fortunately Microsoft came up with a (almost) simple solution.
The trick is create a *special* file that will tell to our App how to behave and where to look for what it needs. This file is the “Manifest”.
As a brief description let’s just say that this is a simple XML file and in there we can specify where are the DLLs that we want to provide to our app, bypassing the normal searching behaviour.

The Problem of the Tool
The problem here is that writing what you need here is not always (actually almost never) easy. In fact, in order to describe the COM that you App will have to use, you must “describe” it, specifying all the GUIDs, ProgIds (if you need it), and other nasty details that are generally (and fortunately) auto-generated for us when we Create and use a COM in a normal/standard way… So why do we have to suffer now? Fortunately we don’t, we are safe this time as well :P.

The Basic Solution – Understand What’s Going On
Based on Microsoft Documentation, the way to create a manifest for your DLL is to use the Tool mt.exe (this is the Documentation).
With this tool you can generate the manifest that you will have to use with your App if you want to achieve our goal.
For example, considering our MyPippoCOM.dll DLL, we could do something like this (from the command prompt, in the folder where the dll and tlb files are stored):

This will generate a file named “mySample.manifest” that, in my case, will contain something like this:

At this point you could do the same thing for the other DLL and then (only after), create the manifest for your app.
This is because with this tool you can only specify one dll and tlb when you generate a manifest and consequently you cannot create a manifest with the data for both DLLs in one go. Fortunately though this tool allows you to merge multiple manifests! So you could use this as final step toward the creation of the Application manifest. I said “toward the creation” because unfortunately the manifest that you will have at the end of this process will be incomplete and could contain some errors as well if you didn’t follow exactly my example and you specified the dll and tlb file using an absolute/relative path instead. I’ll explain later how fix this. For now le’s see how could you merge the two manifests:

The result will be a file named “merged.manifest” that in my case will contain this:

As it stands you cannot use it directly. You need to rename it, fix a couple of things in it, adding some missing informations and you need to build the TestApp without embedding its manifest.
So, first things first. Go back in VS2005 and build our TestApp changing one setting. Open the project’s properties, expand the section “Manifest Tool” and enter in the “Input and Output” entry. In the option screen on the right set “Embed Manifest” to “No”.
Now you can build the project again and this time a file TestApp.exe.manifest (in my case) will sit next to the executable.
Now open it. It should look like this (the dependentAssembly section will include the proper assembly based on which type of build you selected, debug or release):

Now it is just a question to grab our previous merged manifest (from the two COMs) and copy all the content that appears inside the “assembly” tags into the TestApp.exe.manifest, just before the assembly closing tag. In my case this will be the result of this step:

Ok! Almost there.
The final step is to add something that mt.exe doesn’t add for us but that I like to have, the ProgID attribute. You have to do this by hand unfortunately. Just add this attribute to any comClass tag. The final result in my case is this (I optimised some tags a little bit as well):

Note that the ProgID should actually contain the version number as well (e.g. progid=”MyPippoCOM.SillyAdder.1″), but the other version does work if you don’t specify this number when creating the object in your code as in:

That’s all for this first long manual version.
There is a way to skip some steps and do it slightly more automatically.

The Semi-Practical Solution – The Slightly More Automatic Way
A way that I found helpful to adopt is to make usage of the post-build steps feature.
To keep it short and simple, what you can do is edit the post-build event for both of your COMs projects, adding somethig like this:

(and similarly for the other COM).
This will generate automatically a manifest named “manifest.manifest” (nice name uh? :P) in the project output folder.
Then edit the TestApp project’s properties, writing in “Manifest Tool | Input Output | Additional Manifest Files” the location of any manifest that you want to merge.
Those two settings will essentially automate the creation and merge of the manifest that we previously did manually!
You will have to do the final fixes anyway. Maybe you can try to automate this as well :).

The Practical Solution – The Fast Way
I found a way to cheat and generate the manifest with even less work. It is sort of cheating, but it is fast and works! :).
Instead of opening Visual Studio 2005, open VS2010 and create a new project. Just any project, a console app for example.
Now right click the References tab in the solution explorer and select “Add Reference…”.
In the window that will pop-up select “Browse” and navigate where the first COM DLL is located and add it.
Repeat the same process for all the other COMs.
When the References list is completed, expand it and select all the COMs that you just added.
Go in the “Properties” window of the selected references entries and change the value of “Isolated” to True.
Job Done!
Now when you will build the project a .manifest file will be automatically generated and it will contain the correct XML for both COMs.
mine looks like this:

Notice that it contains the ProgID attribute with the version number (“.1″) at the end of the string (see: progid=”MyPippoCOM.SillyAdder.1”). You will have to remove it if you don’t specify it in your TestApp application.
Apart from this, you can directly use this as input manifest for the TestApp saving even more time! :) (you can consider to change the assemblyIdentity attribute if you do this).
NOTE: In order to apply this solution the COMs must be registered on the developer machine. This must be said just in case you did some previous steps and you unregistered them and you didn’t rebuild the projects ever after.

The Speedy Solution – The Last Tip!
There is a final tip to avoid even more typing. The only thing to prepare is the merged manifest in the way you prefer and use this one as Additional Manifest File in the Input and Output section of the Manifest Tool in the properties of the C++ TestApp project. Then, instead of setting the Embed Manifest to “No”, Leave it to “Yes”.
This will generate the application exe without any needed manifest and this is ready to be executed side-by-side with the COM DLLs.
No more editing, no more problems :).

Note about VB6 COMs
If you have VB6 COMs the previous method will still work really well (even with a correct ProgID), but if you want to explore even alternative ways, there is an interesting tool that you can try to use to generate the manifest for each specific COM.
You can find the tool here: Make My Manifest
What it does is essentially create a manifest for any VB6 projects (not only COMs) generating a complete manifest with all the project’s COM dependencies.
So this is more exhaustive than our single C++ COM manifest and this means that if you have multiple VB6 COMs that uses others COMs, then the manifests could contain common elements and thus the merge should take care of this. But for the rest it is a quite nice tool to use, so give it a try.

Conclusion
The DLL Hell is not a random name and what I tried to cover in this post is just the tip of the iceberg.
I wanted to write this because I found quite difficult to gather the practical information that I ended up discovering personally through a long series of frustrating experiments in order to properly understand and faultlessly solve the main problem.
I hope that this helped you and you found it interesting.
Let me know if you discovered other ways to solve it or if you have any suggestion/question/information that you want to share ;).

Comment or Leave a Message

Please Comment or Leave a Message if this is what you are looking for or if you have any question/comment/suggestion/request.

RC4 is the most widely used symmetric cypher algorithm, especially given its performances.

The Key is generally between 5 and 16 bytes, equivalent to 40-128 bits.

Initialisation

To initialise the algorithm it is used a permutation of all 256 possible byte values using the Key-Scheduled algorithm.

The procedure is quite simple. Assuming that we have our key stored in an array that we can access (let’s call this array simply “key”), we have to:

  • Initialise an array with the identity permutation of the 256 values (let’s name this array simply as “buffer” for now)
  • Loop through each array element (let’s assume that “i” is the index of the array for the element currently processed) in this way:
    • Use another index “j” (initialised to 0) and add to this index the element in the i-th position (buffer[i])
    • Add to the result the content of the key buffer in the i-th mod key-length position (or “i % keylength” if you prefer). This essentially means the value in: key[i % keylength]
    • Ensure that we never end outside our buffer boundaries. Take the value of j % 256 (or j & 255 if it sounds cooler to you)
    • Swap buffer[i] with buffer[j]

The code sample shows this algorithm in action:

Encryption

Once initialised the algorithm using our key we are ready to encode the message.

This algorithm could seem a little bit more convoluted, but it is actually quite simple.
Let’s assume that the message to protect is stored in an array called “message”. The steps are those:

  • Reset i and j to 0
  • For each byte of the message that we want to encode do the following:
    • Increment i and keep it in our buffer boundaries: i = (i + 1) % 256
    • Add buffer[i] to j keeping the result in the array as well: j = (j + buffer[i]) % 256
    • Swap buffer[i] with buffer[j]
    • Add the values in buffer[i] and buffer[j], keep the result in the buffer array range: (buffer[i]+buffer[j]) % 256
    • Use it (let’s name it “encryptionByteIndex”) as an index in buffer itself: encryptionByte = buffer[encryptionByteIndex]
    • Use the value of the buffer in this position to xor the current byte of the message: encryptedMessageByte = message[currentIndex] ^ encryptionByte
    • Store this in an encryptedMessage buffer: encryptedMessage[currentIndex] = encryptedMessageByte

At the end of this algorithm the message will be encrypted in the buffer encryptedMessageBuffer. In order to decrypt it we can follow the same procedure using this buffer as our input buffer.

This is one code sample (in this code I will use only one buffer for the message and its encryption):

If you want to see where this could be useful have a look at my other blog entry here: Crypt in C++ and Decrypt in C# (and C++).