Configuring Multi node Cassandra Cluster on Windows

Cassandra is a distributed open source (Apache Licensed) stable DBMS which is widely used by many big organizations like Google. I like Cassandra because it fits my organizational needs and has a very flexible storage structure.

Configuring a single node for testing purpose is very easy and a good tutorial is available at In said tutorial you’ll find Linux-style paths but there’s no need to worry. You can specify Windows-style paths as well. It works fine so and really easy to understand so I am not going to discuss those basics here again. However I would suggest you to first go through the above link and test a single node on your machine then move on.

In this tutorial I am going to make a cluster of two nodes for simplicity. One node is hosted on Machine-A (having IP address and other on Machine-B (having IP address However following these steps you may add as many nodes as you want.

The game of making cluster revolves all around Cassandra.yaml configuration file which you may find under Cassandra Installation directory\conf\Cassandra.yaml.

Let’s start from Machine-A. Open Cassandra.yaml file and start editing. You need to edit cluster_name, listen_address, rpc_address and seeds values as following:

cluster_name: ‘MyCluster’

listen_address: # IP of Machine-A



Start this node using cassandra –f command. Hopefully it will start successfully.

Now come to Machine-B. Open Cassandra.yaml and make sure that cluster_name is same as of cluster_name on Machine-A. Write IP address of Machine-B in listen_address and rpc_address while write IP address of Machine-A against seeds i.e. your configuration file will have following lines.

cluster_name: ‘MyCluster’

listen_address: # IP of Machine-B


seeds:           # IP of Machine-A.

Start this node and it should also start successfully. Once started open command prompt, navigate to Cassandra bin directory and write the following command to test that you’ve two nodes in your cluster:

nodetool – host –p  7199 ring

The above said link states that you should set initial_token value in Cassandra.yaml. But its optional and setting this value falls in advance configuration so we’re not going to discuss it here.

There’s a good open source administration tool for Cassandra clusters: You may find it usefull.

For further reading or troubleshooting you can visit

Best of luck with Cassandra!



Embedded MySQL — Part 3

In previous part we wrote some basic functions related to embedded MySQL.

In this part we’ll integrate these functions to demonstrate a working application.

Here’s the main() I wrote to demonstrate the use of those functions:

int _tmain(int argc, _TCHAR* argv[])
 MYSQL *sql = NULL;
 sql = initialize(sql);
 if(sql == NULL)
  return -1;
 if(connect(sql) == false)
  return -1;
 bool failure = false;
 // Create and populate database
 const short statementsCount = 5;
 const char *statements[statementsCount] = { "Create database testdb",
           "Create table (id int, name varchar(20))",
           "Insert into values(1, \'Mian\')",
           "Insert into values(2, \'Zeshan\')",
           "Insert into values(3, \'Farooqi\')"};
 for(short i=0; i<5; i++)
  if(executeStatement(sql, statements[i]) == false)
   return -1;
 /* Read Data */
 MYSQL_RES *result = executeStatementAndReturnResult(sql, "Select * from");
 if(result == NULL)
  cout<<"Nothing was returned!"<<endl;

 return 0;

You can find the complete C++ prject here.
Please provide me with your valuable feedbacks and contact me if you need any sort of help related to this article.

, , , , , ,


Embedded MySQL — Part 2

In previous part we took an introduction to “Embedded MySQL” and also prepared our toolkit.

In this part we’ll write some basic functions related to embedded MySQL that we’ll use in future.
First of all include the required header file and declare server options/configuration:

#include "mysql.h"

/* Embedded MySQL configuration parameteres */
char *mySqlOptions[] =
 "--console", NULL

int numberOfMySqlOptions = sizeof(mySqlOptions)/ sizeof(char*) - 1;

char *serverGroups[] = { "TestServer", NULL };

The above configuration is alternate of MySQL’s configuration file commonly named as My.ini.

Now lets write a general purpose function to log our errors. Currently we’ll display the log on console, you may change the implementation of this function later.

void log(const char * methodName, const char* msg)

Here’s the function that will initialize embedded MySQL instance. You need to call this function once in begining of your application.

MYSQL* initialize(MYSQL *sql)
 if(mysql_library_init(numberOfMySqlOptions, mySqlOptions, (char **)serverGroups) != NULL)
  log("initialize", "Error initializing embedded MySQL server...!");
  return NULL;
 else if((sql = mysql_init(NULL)) == NULL)
  log("initialize", "Memory allocation error while initializing embedded MySQL...!");
  return NULL;
 /* Everything goes well till we reach here */
 return sql;

Once the above call succeedes, now its time to connect to MySQL.

bool connect(MYSQL *sql)
 /* Set MySQL connection-secific options */
 if(mysql_real_connect(sql, NULL, NULL ,NULL, "mysql", 0, NULL, 0) == NULL)
  log("initialize", mysql_error(sql));
  log("initialize", "Error connecting embedded MySQL...!");
  return false;
 /* Everything goes well till we reach here */
 return true;

When you connect to MySQL successfully, now you can create/view/edit databases, tables and their records.

Let’s write a function to execute simple MySQL statements that does not return resultset:

bool executeStatement(MYSQL* sql, const char* query)
  mysql_query executes a query and returns 0
  if succeeded otherwise returns a non-zero value
 if(mysql_query(sql, query) == 0)
  return true;
  log("executeSimpleQuery", mysql_error(sql));
  return false;

We may also need to write a function that executes a SQL statement and returns its results:

MYSQL_RES* executeStatementAndReturnResult(MYSQL *sql, const char* query)
 if(mysql_query(sql, query) != 0)
  log("executeStatementAndReturnResult", mysql_error(sql));
  return NULL;
 MYSQL_RES* result = mysql_store_result(sql);
 if(result == NULL)
  log("executeStatementAndReturnResult", "NULL ResultSet");
  return NULL;
  return result;

Here I am going to write a method that will display the values returned in result set. You may change the display formatting accroding to your own requirements:

void displayResultSet(MYSQL_RES *result)
 if(result == NULL)
  log("displayResultSet", "ResultSet is NULL");

 cout<<"There are "<<result->row_count<<" rows in result set!"<<endl;

 while((row = mysql_fetch_row(result)))
  int columnCount = result->field_count;
  for(int i=0; i<columnCount; i++)


After playing with MySQL you need to disconnect now:

void disconnect(MYSQL *sql)
 if(sql != NULL)

Atlast uninitialize MySQL:

void uninitialize()

In next part we’ll use all of these functions to demonstrate a working application.

, , , , , ,

1 Comment

Embedded MySQL — Part 1

Have you ever heard that you can embed MySQL server in your application? Atleast I never heard anything like this during my student life, even during the course of Databases.

For me, MySQL used to be simply an open source client-server DBMS. The server runs either as a process or a service in background while client can take many forms ranging from command-line client (provided with server) or any user-build Java/C/.Net application which communicates with server using provided APIs (also known as connectors).

However getting know that the world famous MySQL can be embedded in my application was a big surprise for me. By embedding in application I mean that MySQL will work as a plugged “component” in your application and you don’t need to install it separately i.e. the MySQL server will run in address space of your own application’s process.

The term ‘Embedded MySQL’ may somehow mislead if you search it on MySQL’s website ( They take this term in some other way (ISV,  OEMs and VARs) which I am not going to discuss here. But still if you want to read more about it then you can search ‘libmysqld’ which is the same thing that I’m talking about.

Here I’m only going to demonstrate how to load MySQL in your own address space and how to use it (i.e. embedding it in your application). Though MySQL works on several platforms but here I’ll demonstrate it using Microsoft platform because it’s a widely used platform around the world. 

Note that embeddable MySQL is not distributed with standard MySQL distributions so you need to download its complete source code; compile it to get required libmysqld.lib or alternatively you can download it from here which I’ve already compiled for you.

Once you get libmysqld.lib you’ll need:

  1. Microsoft Visual Studio 2010.
    We’ll code in C++ so you may download Visual C++ Express edition from here
  2. Include files of MySQL
  3. Library files of MySQL (libmysqld.lib)
  4. Resource file (errmsg.sys)
  5. Data directory (for storing databases)

For your convenience I’ve uploaded the bundle of all required files here.

MySQL developers who are familiar with MySQL native C API will find libmysqld similar to that API. But it only looks like that. They’re not the same thing i.e. function names are same but their implementations are different.

Let’s start from unpacking the files that I’ve uploaded. I’m assuming that you unpack the files in a folder named D:\e-mysql\. So please make sure that this folder contains the following files and folders:

  • D:\e-mysql\system\errmsg.sys
  • D:\e-mysql\include\           (directory contains header files)
  • D:\e-mysql\lib\                     (directory with two subdirectories)
  • D:\e-mysql\lib\debug\      (contains four files having extensions pdb, lib, dll, exp)
  • D:\e-mysql\lib\release\    (contains four file with similar names as of above)
  • D:\e-mysql\data\                 (this would be our data directory)

I’m assuming that you’re well familiar with Visual Studio IDE, if you aren’t then don’t worry you’ll understand the basics and may ask me if you need any sort of help.

Now open Visual Studio and create a Win32 Console application. Right click your project in solution explorer then -> Properties -> C/C++ ->Additional Include Directories. Write the path of header files here (in our case its D:\e-mysql\include).

Now proceed to Linker setting.  Properties -> Linker ->Additional Library Directories. Here you may either specify D:\e-mysql\lib\debug (if you’re in debugging mode) or D:\e-mysql\lib\release.

In same properties window navigate to Linker -> Input ->Additional Dependencies. Simply write libmysqld.lib here.

Taking a bird’s eye view we need to call following functions in sequence:

  • mysql_libraray_init()      (should be called prior to calling other libmysqld functions)
  • mysql_thread_init()       (should be called at start of each thread that accessed MySQL)
  • mysql_init()                        (should be called before creating new connections)
  • mysql_real_connect()   (should be called to establish a new connection to MySQL)
  • mysql_close()                    (should be called when connection is no longer needed)
  • mysql_thread_end()      (should be called before a thread exits)
  • mysql_library_end()       (should be called before your program exits)

mysql_thread_init() and mysql_thread_end() are need to be called only if your application is multi-threaded.

We will create a simple single-threaded application in next part.

, , , , , ,

1 Comment

Consuming Web Services in Java using JAX-WS


I had been using Axis2 in my project to consume web services. Everything was going well but unfortunately one of the service’s message conflicted with Axis2 and I started getting exception of ‘Unexpected sub element…”. I modified my services messages and tried everything that came to my mind but the exception was still there. After searching I found that this issue was first time logged in 2008 and still many people are facing this issue in 2011. So it was the time to move ahead and I found JAX-WS.


JAX-WS works with Java Standard Edition (J2SE) 5 or later[1]. If you don’t already have JAX-WS then follow the following steps otherwise you can directly move to “Creating service client” section:

  1. Download it from
  2. Double click the jar or extract it some other way (let’s say at C:\jax-ws)
  3. Now you need to set an environment variable JAXWS_HOME and give the root folder of JAX-WS as value of this variable e.g. JAXWS_HOME = C:\jax-ws
  4. Add %JAXWS_HOME%\bin in your Path variable. (optional)


Let’s consume the “Currency Convertor” web service provided by You may find this service at

This service defines an operation ConversionRate that take two parameters FromCurrency and ToCurrency and returns a type double value. FromCurrency and ToCurrency are of type strings. In java code we’ll pass two strings and expect a double value from this service. Let’s see how we can do this.

Creating Service Client:

Open command prompt and use wsimport command by passing it the URL of service you want to consume. In our case we’ll use it like this:

wsimport -Xnocompile

-Xnocompile is used when you don’t want to compile the generated java classes. You may also need to use -Xendorsed parameter at the end of this command (if required).[2]

This command will create source files of the web service client in a package.

Import this package in your Java Project and enjoy yourself!

Using created service client:

I am currently using eclipse but you can use any other IDE of your choice.

  1. Create a java project
  2. Import the generated source code in this project (net.webservicex.*)
  3. Create a Driver class (any java class that will execute the code)
  4. Now simply create objects of genereated service classes and assemble them togather to use the service. The questions like Which objects are to be created” and “How to assemble them” can be answered by reading the WSDL file through which we have created the source code.
  5. For this particular example (and also for general guideline) please see the following piece of code that will use the service:
import net.webservicex.*;

public class Driver {
	public static void main(String[] arg){

		// Create an instance of service stub
		CurrencyConvertor service = new CurrencyConvertor();

		// Create an instance of SOAP message specific to this service
		CurrencyConvertorSoap msg = service.getCurrencyConvertorSoap();

		// Invoke the method
		double rate = msg.conversionRate(Currency.USD, Currency.PKR);

		// Any java code to manipulate the reuslts
		System.out.println("USD to PKR rate = " + rate);

[1] I’ve tested it on J2SE 6
[2] Type wsimport and press enter to see the detailed help

Feedbacks are highly appreciated!

, , , , , , , ,


Difference between TrueType, PostScript, and OpenType Fonts

TrueType fonts can be scaled to any size and are clear and readable in all sizes. They can be sent to any printer or other output device that is supported by Windows.

OpenType fonts are related to TrueType fonts, but they incorporate a greater extension of the basic character set, including small capitalization, old-style numerals, and more detailed shapes, such as glyphs and ligatures. OpenType fonts can also be scaled to any size, are clear and readable in all sizes, and can be sent to any printer or other output device that is supported by Windows.

PostScript fonts are smooth, detailed, and of high quality. They are often used for printing, especially professional-quality printing, such as books or magazines.

Which font format will work best for me?

It depends. If you want a font that prints well and is easy to read on the screen, then consider using a TrueType font.  If you need a large character set for language coverage and fine typography, then you might want to use an OpenType font. If you need to print professional-quality print publications, such as glossy magazines or commercial printing, PostScript is a good choice.


Source: Microsft Windows 7 Help

Leave a comment

Make Bootable USB Flash Disk

You might need a bootable USB disk for many reasons out of which the most popular ones are:

  • Installation of an Operating System
  • Repairing your system

Here I’m going to state everything specifically to Microsoft Windows ® 7.

Note: Before reading further please make sure that your system supports USB booting and this feature is enabled in your BIOS setup.

Installing Windows 7:

Suppose that you have installation files of Windows 7 at the following path on your hard disk.


Now you need to follow the following steps in order to prepare a bootable USB installation disk.

  1. Insert a USB flash drive (assuming it has assigned the drive letter F)
  2. Format it on FAT32 file system
  3. Open command prompt (see starting command prompt notes below) and type the following commands:
    cd win7setup
    cd boot
    bootsect /nt60 F:

    NOTE: Be careful while writing the drive letter of USB in above command. If your USB has a drive letter other than F then type that specific letter in the last command.

  4. Copy all files from E:\win7setup to F:\
  5. Restart your computer and enjoy yourself!

Repairing your system:

If you have the Windows 7 installation files then follow the steps given in extracting boot files section otherwise follow the following steps.

  1. Download the given file bootable.doc
  2. Rename the downloaded file from bootable.doc to
  3. Extract the zip file on your hard disk (say C:\bootable)
  4. Insert a flash drive and format it using FAT32 file system
  5. Open command prompt (see starting command prompt notes below)
  6. Move to the directory (using commands) where the files are extracted, I’m assuming that you’ve extracted files at C:\bootable, then type following commands:
    cd bootable
    cd boot
  7. Now type the following command (assuming that your flash drive is F drive in your computer):

    bootsect /nt60 F:

  8. If your flash has some other letter (D, E, G, …) in My Computer then replace that letter in the above command
  9. Copy all extracted files (c:\bootable) and paste them in your flash drive
  10. Restart your computer and enjoy!

Starting Command Prompt:

If you’re using Windows 7 then:

  1. Go to Start menu –> Programs –> Accessories –> Command Prompt
  2. Right click the Command Prompt icon and click Run as Administrator

If you’re using some older version of Windows then simply click the command prompt icon in step-2.

Shortcut: Press Windows Key(WinKey) + R to open RUN dialog box; type cmd and press Enter.

Extracting boot files:

Assuming that you’ve placed the installation files at E:\win7setup then before continuing it would better to copy the following files and folders at C:\bootable\:

  1. E:\win7setup\bootmgr
  2. E:\win7setup\setup.exe
  3. E:\win7setup\boot
  4. E:\win7setup\support
  5. E:\win7setup\sources     Only copy boot.wim from this folder

Go to step-4 in ‘Repairing your System’ section above.

1 Comment

Service Oriented Architecture (SOA)

SOA is a software architecture which refers to application development using services. A service can be considered as a standalone functional entity. An application may use different services to accomplish a task. Let’s say that an IT organization has developed following three services:

  • Service-A: Fetches records from database (e.g. each record/row contains information of a person)
  • Service-B: Take two parameters i.e. A dataset (collection of records gained by executing a query on db server) and a column name then extract the respective column (of each record) from dataset and write all data in a file.
  • Service-C: Takes a file which contains list of email addresses and other text file which contains some message then sends the given message at all emails addresses provided in list

Now the organization writes an application for executing their marketing campaign by using these services. Let’s see how!
Here’s the execution flow of that application:

  1. Call Service-A and store its output somewhere (say some variable Var_A)
  2. Call Service-B by passing “VAR_A” and “email” as input parameters
  3. Call Service-C by passing the file generated by Service-B and path to a file on local hard disk which contains the advertisement message.

Now if the same organization wants to prepare a telephone directory of their clients (whose data is stored in database) then it can use the same services again in the following way:

  1. Call Service-A and store its output somewhere (say some variable Var_A)
  2. Call Service-B by passing “VAR_A” and “telephone” as input parameters

This is a rough and simple scenario which I’ve described here to make you understand ‘SOA’ but the real benefits of SOA are too more than these.

If I need to describe the reasons of adopting SOA then I would say “reusability” (results in cost saving) and “flexibility”. By flexibility here I mean that the utilization of application can be enhanced by integrating it with other applications.

If a SOA built application expose some of its services for other applications then it would be really too good and easy to utilize that application with some other applications in order to achieve the desired task. I would talk about Software Integration in next articles.

1 Comment

Easter Eggs and Logic Bomb

This is one of my favorite article which I wrote in 6th edition of E-MAG. I still remember that it was a great fun for me to find easter eggs and put them in my article. I hope you’ll enjoy it too.

Easter egg is a hidden feature or a message which a creator puts in his creation. Easter Eggs are found in movies, books, machines, video or computer games and computer programs. This article would cover the computer programs’ Easter eggs.

In context of computer programs Easter eggs refers to a hidden feature or a hidden action which in executed in result of some set of commands, key combinations or mouse clicks. Easter egg is such a feature of software which is kept hidden by the programmer. Some feature which should not be logically a part of your program is also considered as an Easter egg. Such features are never documented.

Mostly the Easter eggs are entertaining. Easter eggs never harm your PC or data. The hidden features of a program which harm your PC or data are known as Logic Bombs which will be discussed later in this article.

Programmers put Easter eggs in their programs for their own recreation during development or there also might be some other reasons. People are never told about Easter eggs officially by the creator because it is an undocumented feature of their program. Easter eggs are found in many operating systems, application softwares and web pages.

In Microsoft Excel 95 there was a hidden game named as “The Hall of Tortured Souls”. Same like that MS Office 97 and 2000 also had some hidden games. A very popular Easter eggs of Microsoft Windows (earlier versions then XP) was in screensaver ‘3D Text’. When you write volcano in the Settings of this screensaver, it displays the names of different volcanoes instead of the word volcano. These are the old Easter eggs so I’m not going to discuss them in detail.

In MS Word 2007 write =rand(X,Y) or =lorem(X,Y) (replace X and Y with some digit) and press Enter key. It will show you X random sentences in Y random paragraphs. This Easter egg is also found in earlier versions of MS Word.

In MS Paint only 5 different line widths are available. While drawing some shape press Ctrl key with + or – key to increase/decrease the width of line as much as you want. Select the pencil tool; by holding Shift key you can draw straight or diagonal lines. Select some portion of an image in MS Paint; hold Ctrl key and drag the selected area. It will create a trail of image.

In notepad type bush hid the facts and save the file with any name. Now open the saved file see that the text would be replaced by small squares. If you’ve installed the Chinese fonts and language then you’ll see some funny Chinese characters instead of small squares.

In Ubuntu press Alt + F2 and type gegls from outer space. You’ll see some funny cows.

Open Run in Windows XP and type telnet to watch an ASCII Movie. This animated film is created in ASCII and it’s a fun to watch it.

In Mozilla Firefox web browser go to the address bar and type about:mozilla and press Enter. It will show you a page from “The Book of Mozilla” telling you about the birth of Mozilla. In address bar type about:robots and read the message of Robots for human beings. In address bar type chrome://browser/content/browser.xul and see what happens. Type about:credits to see credits. This Easter egg is also found in Google Chrome.

Open Microsoft Visual Basic 6. Right click in empty region in menu bar or standard toolbar and click Customize. Go to Commands tab. In Categories section select Help. In Commands section Click About Microsoft Visual Basic… and drag it to the menu bar or standard toolbar. Now right click the newly inserted item and replace its Name with Show VB Credits and press Enter key. Close the Customize dialog box. Now click the button/item which you renamed as Show VB Credits. It will show you the animated credits of VB Team.

Open Microsoft Visual C++ 6. Go to File > New (or press Ctrl + N). Go to Projects tab; select ATL COM AppWizard; give the Project some name and click OK. Now simply click Finish then OK. Click on Insert (menu bar) and select New ATL Object (or simply press Alt + I + A). In objects section (right hand side) click each object one by one from left to right and top to bottom. Now hold Ctrl Key and Double Click the left mouse button in Gray region of this dialog box. You’ll see the pictures and names of ATL Team.

In Borland C++ V.3.1 Click Help and then click About. It will open the About Dialog box. Now press Alt + I to see the credits of this compiler.

Open WinRAR; click on Help (menu bar) then click on About WinRAR….Click the WinRAR logo to animate the ocean waves. Clicking the books in same dialog box will cause their downward motion.

Secrete codes in games which are commonly known as Game Cheats are also considered as Easter eggs.

In Windows XP open Pinball game. When the ball appears, type hidden test and enjoy the game. Now you can control the ball with your mouse and make as many scores as you want.

In Solitaire (a cards game in Windows) press Alt + Shift + 2. You’ll see the winning animation. It not only shows the animation but you also win the game.

Hidden emotions in messengers are also Easter eggs of that messenger. Here are some hidden emotions of Yahoo! Messenger.  These emotions were Easter eggs in earlier versions but now they are documented by Yahoo! but still hidden. Try these cute and funny emotions and have fun:

8-X @};- 3:-0 b-( ~o) [-o< >-) @-) $-) :-" :^o [-x \:D/ ~:>

%%- :-L o-> (%) (*) :-j :-# :-@ :-> (~~) **== :(|) :@) =:)

Open and type Recursion in search box and click search button. It will again prompt you with the same spelling: Did you mean Recursion.

There’re some smilies in Facebook chat. Here’re the Easter eggs of chat. Try and enjoy:

:) :( :P :D :O ;) 8) 8| >:( :\ :’( 3:) O:) :-*

<3 ^_^ -_- O.o >:o :v :3 :|] :putnam:

In Facebook chat if your write your message between two sterik signs than it will be displayed as bold text. For example *Hello my dear!* would appear as Hello my dear! to the other person.

Open in your web browser. Click on the exclamation sign of Yahoo logo i.e.! You’ll hear a nice voice singing Yahoo!

Open and Press the given key combination: up up down down left right left right b a Enter. You’ll see that the background of the website would be changed.

You’ve seen that Easter eggs are usually entertaining. We can say that Easter eggs are the Good eggs. Where there is something good, there would be something bad too. There’re also some Rotten eggs in softwares. We call them ‘Logic Bombs’. A logic bomb is such a hidden feature of a program which harms your system or data. For example a program with a logic bomb works properly on your computer without any disturbance but on meeting some specific condition it deletes all the files and documents on your disk. It is usually very hard to find out a logic bomb in some program.

Logic bomb has a brother named as Time Bomb. Time bomb is such a hidden feature of a program or a virus which explodes (executes) itself at some specific time. For example a virus names as ‘INIT 1984’ used to infect the startup files of Mac OS whenever the 13th of any month falls on Friday.

Michelangelo virus was a boot sector virus which used to sleep (remain inactive) until March 6. It used to explode on March 6 and performs several actions on the basis of certain conditions of your system. Another virus Nyxem destroys the files of Microsft Office and tries to stop the security and sharing related services on your computer on 3rd of each month.

The famous Chernobyl virus which caused damage of millions of computers all around the word was written one year before its execution. It was delivered to the systems by a firmware update of Yamaha Inc. It exploded (executed) itself exactly on April 26, 1999 in the computers of all over the world and caused a historic damage.

1 Comment


Get every new post delivered to your Inbox.

%d bloggers like this: