Friday, February 24, 2012

Setup connection to MySQL in VS 2010

Author: 
Source: http://arunasujith.blogspot.com/2012/02/mysql-c-connection-example-in-visual_10.html


Creating a MySQL database connection using C++ is  really easy. But for a beginner it can be really hard to find the correct procedure cause it will gave really troubles. At the first time when I'm doing it it took me quite some time to make it work. So I'm going to explain how to make a connection to the MySQL database using C++ code. We use the library called boost to make the connection. 

Step 1 (Download the boost library)
First step is to download the boost library. You can download it from here from the official download page Or you can download the one I've compressed and uploaded which is smaller in size from here.

Step 2 (Create the project using Visual Studio 2008)
First go  to File --> New --> Project and you'll get a screen like this. 

mysql c++ connection example

Select Visual C++ --> Win 32 --> Win 32 Console Application  and give a name to the project and press OK. 
Then set Application Type to Console Application and remember to tick the empty project. and click finish.

Then Right Click the project and add new Item a cpp source file called Connect.cpp.

// Standard includes
#include 
#include 
#include 
using namespace std;

// Connector Includes

#include "cppconnection/driver.h"
#include "cppconnection/exception.h"
#include "cppconnection/resultset.h"
#include "cppconnection/statement.h"


// Link to the Connector/C++ library
#pragma comment(lib, "mysqlcppconn.lib")

// Connection details
string server   = "localhost";
string username = "root";
string password = "123"; //

int main(){
    sql::Driver     *driver; // MySQL Driver Object
    sql::Connection *connection; // MySQL connection Object
    sql::Statement  *statement;   // Statement which holds SQL commands
    sql::ResultSet  *resultSet;    // ResultSet to hold the results
    //Here is the connection
    try{
        driver = get_driver_instance();
        connection = driver->connect(server, username, password);
        statement = connection->createStatement();
        statement->execute("USE performance_schema");
        resultSet = statement->executeQuery("show tables");
        while (resultSet->next()){
            // Iterating the result set
            cout << resultSet->getString(1) << endl;               
        }
    }
    catch (sql::Exception e){
        cout << "Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }

    //Clear resources
    delete res;
    delete statement;
    delete connection;

    system("pause");
    return 0;
}

Copy the boost folder into the project folder. In this example the folder is Visual Studio 2008\Projects\MySQLConnection\MySQLConnection folder.

Then download this header and dll files and extract them into the same folder Visual Studio 2008\Projects\MySQLConnection\MySQLConnection folder.

Then the final step is right cilck on the Project and go to 
Properties --> Configuration Properties --> C/C++ --> General . 
On the right hand side set the "Additional Include Directories" value to ".\" value. (with out the quotes)

That's it build your project and run the project. And one more final thing when you run the project set the  "Solution Configuration" to Release mode. In the Debug Mode I had some error which I still don't no why.

So that's it now I think you got a clear idea about creating a connection for MySQL using C++ in Visual Studio 2008. See you around with another exciting post... :)

Tuesday, January 31, 2012

get ForwardingTable size in tinyos


entry = call ForwardingTable.getTable(&n);
while(entry[cur_entry].valid)
cur_entry++;
    printf("\t\tthe length of ForwardingTable is %i\n", cur_entry);

Monday, January 30, 2012

Printf in tinyos


To see the output generated by the Printf tutorial application you need to start the PrintfClient by running
the following command:


java net.tinyos.tools.PrintfClient -comm serial@/dev/ttyUSBXXX:telosb


A few points are worthy of note before jumping in and writing your own applications that use the functionality
provided by the printf library.
1. In order to use the printf library, the tos/lib/printf directory must be in your include path. The
easiest way to include it is by adding the following line directly within the Makefile of your top level
application:
CFLAGS += -I$(TOSDIR)/lib/printf
2. Remember that changing the printf buffer size is done similarly:
CFLAGS += -DPRINTF_BUFFER_SIZE=XXX3. You MUST be sure to #include "printf.h" header file in every component in which you would like to
call the printf() command. Failure to do so will result in obscure error messages making it difficult to
identify the problem

Monday, January 16, 2012

Allow user to access mysql database from anywhere

GRANT ALL ON *.* TO USERNAME@'%' IDENTIFIED BY 'PASSWORD';

Thursday, January 5, 2012

Connect to MySQL using C++ on Ubuntu

Source:  http://blog.trilabs.co.tz/2011/09/connect-to-mysql-using-c-on-ubuntu.html


Someone asked on Facebook how to connect to a MySQL Database Using C++. So I thought it will be cool to just share it here for everyone.

Ground Work

Here is how things look like on my computer.
  • OS:  Ubuntu 11.04  ( Linux legacy 2.6.38-11-generic #48-Ubuntu SMP Fri Jul 29 19:05:14 UTC 2011 i686 i686 i386 GNU/Linux)
  • DB: MySQL 5.1 ( mysql Ver 14.14 Distrib 5.1.54, for debian-linux-gnu (i686) using readline 6.2)
  • Compiler:  GCC 4.5 (g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2)
I had to install some C++ MySQL Connector and other helpers, actually after trying the textbook way and it did not work, I did a bit of googling and asking dev here and there.
?View Code SHELL
sudo apt-get install libmysqlcppconn4 libmysqlcppconn-dev libmysqlclient-dev

Code

To illustrate this, I am going to connect to the development database of one of the project I am working on show a list of products against store they can be bought. I am assuming your database knowledge in order. I have also added as much details as I could on the code itself.
?View Code CPP
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
 
/**
 * This structure will be used to store all cessary inforamtion to connect to the database
 */
struct connection_details
{
    char *server;
    char *user;
    char *password;
    char *database;
};
 
/**
 * Sets up connection to the database, this depends on the functions from mysql.h.
 * This function will connect and return a MYSQL pointer to the new connection using the
 * structure above connection_details.
 */
MYSQL* mysql_connection_setup(struct connection_details mysql_details)
{
     // first of all create a mysql instance and initialize the variables within
    MYSQL *connection = mysql_init(NULL);
 
    // connect to the database with the details attached.
    if (!mysql_real_connect(connection,mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0, NULL, 0)) {
      printf("Conection error : %s\n", mysql_error(connection));
      exit(1);
    }
    return connection;
}
 
/**
 * Performs the query.
 * This function perform the SQL quert and returns a pointer of MYSQL_RES
 */
MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
   // send the query to the database
   if (mysql_query(connection, sql_query))
   {
      printf("MySQL query error : %s\n", mysql_error(connection));
      exit(1);
   }
 
   return mysql_use_result(connection);
}
 
/**
 * Main function
 */
int main()
{
  MYSQL *conn;  // the connection
  MYSQL_RES *res; // the results
  MYSQL_ROW row; // the results row (line by line)
 
  struct connection_details mysqlD;
  mysqlD.server = "localhost";  // where the mysql database is
  mysqlD.user = "jikoni";  // the root user of mysql
  mysqlD.password = "ugalinakuku"; // the password of the root user in mysql
  mysqlD.database = "discounts"; // the databse to pick
 
  // connect to the mysql database
  conn = mysql_connection_setup(mysqlD);
 
  // assign the results return to the MYSQL_RES pointer
  res = mysql_perform_query(conn, "SELECT products.product,stores.name  FROM products, stores WHERE products.sto_id = stores.id");
 
  printf("\n\t Product -> Store:\n\n\n");
 
  //To traverse the results we use a while loop in C++ and use the mysql_fetch_row function from within the mysql library set
  //where a row is a type of MYSQL_ROW.
 
  while ((row = mysql_fetch_row(res)) !=NULL)
      printf("\t-> %s -> %s \n", row[0],row[1]);
 
  /* clean up the database result set */
  mysql_free_result(res);
  /* clean up the database link */
  mysql_close(conn);
 
  return 0;
}

Compiling the code

Compile this program is a bit tricky as we need to link to the mysql libraries and headers that we have  used within the program, in our case the  mysql.h.  Luckly for us we can make use of the mysql_config, you may need to install it via your package manager system if you do not have it already. I already had it installed.
mysql_config provides you with useful information for compiling your MySQL client and connecting it to MySQL.
See what information it has by simply running it.
?View Code SHELL
# mysql_config
Usage: /usr/bin/mysql_config [OPTIONS]
Options:
        --cflags         [-I/usr/include/mysql  -DBIG_JOINS=1  -fno-strict-aliasing   -DUNIV_LINUX -DUNIV_LINUX]
        --include        [-I/usr/include/mysql]
        --libs           [-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql -lmysqlclient]
        --libs_r         [-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql -lmysqlclient_r]
        --plugindir      [/usr/lib/mysql/plugin]
        --socket         [/var/run/mysqld/mysqld.sock]
        --port           [0]
        --version        [5.1.54]
        --libmysqld-libs [-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql -lmysqld -ldl -lwrap -lrt]
So to compile it run
?View Code SHELL
# g++ -o cmysql $(mysql_config --cflags) cmysql.cpp $(mysql_config --libs)
cmysql.cpp: In function ‘int main()’:
cmysql.cpp:60:19: warning: deprecated conversion from string constant to ‘char*’
cmysql.cpp:61:17: warning: deprecated conversion from string constant to ‘char*’
cmysql.cpp:62:21: warning: deprecated conversion from string constant to ‘char*’
cmysql.cpp:63:21: warning: deprecated conversion from string constant to ‘char*’
cmysql.cpp:69:129: warning: deprecated conversion from string constant to ‘char*’
Ignore the warring for now,  if there errors then fix them and run the executable, cmysql, that would have been generated. I will look into the warnings in time.
?View Code SHELL
# ./cmysql 
 
  Product -> Store:
 
 -> USB Flash Disk -> Brand Computers Ltd
 -> Dell 65-Watt 3-Prong Slim AC Adapter -> Brand Computers Ltd
 -> Dell Streak 7 Android Tablet -> Brand Computers Ltd
 -> Nokia 701 -> Brand Computers Ltd
 -> Dell Inspron 1240 -> Just Computers
 -> HP Photosmart D110A -> Just Computers
 -> Web Hosting -> Tri Labs Limited
 -> Bulk SMS -> Tri Labs Limited
 -> EVDO USB Modem -> Tri Labs Limited
 -> EVDO USB Modem -> Tri Labs Limited
 -> Joomla We Template -> Tri Labs Limited
 -> Night Gear -> Viatuzi
 -> Tech Sports Bra -> Viatuzi
 -> Women's Fiona Bra -> Viatuzi
 -> VRV Color Tank -> Viatuzi
I hope this help someone out there.

Sunday, December 25, 2011

How to convert LPWSTR to string in VC++

Author: ArkM
Source: http://www.daniweb.com/software-development/cpp/threads/155420



C++ Syntax (Toggle Plain Text)
  1. bool cvtLPW2stdstring(std::string& s, const LPWSTR pw,
  2. UINT codepage = CP_ACP)
  3. {
  4. bool res = false;
  5. char* p = 0;
  6. int bsz;
  7.  
  8. bsz = WideCharToMultiByte(codepage,
  9. 0,
  10. pw,-1,
  11. 0,0,
  12. 0,0);
  13. if (bsz > 0) {
  14. p = new char[bsz];
  15. int rc = WideCharToMultiByte(codepage,
  16. 0,
  17. pw,-1,
  18. p,bsz,
  19. 0,0);
  20. if (rc != 0) {
  21. p[bsz-1] = 0;
  22. s = p;
  23. res = true;
  24. }
  25. }
  26. delete [] p;
  27. return res;
  28. }
  29.  
  30. int main()
  31. {
  32. wchar_t msg[] = L"Hello, world!";
  33. std::string s("\?");
  34.  
  35. cvtLPW2stdstring(s,msg);
  36. std::cout << s << std::endl;
  37.  
  38. return 0;
  39. }


Tuesday, December 20, 2011

Private Web Browsing with SSH Tunneling and Putty By Corey on March 9th, 2010


Private Web Browsing with SSH Tunneling and Putty

Web browsing through SSH tunneling gives you the ability to browse the web privately by encrypting all web traffic out of your computer.  This gives you privacy to know that anyone eavesdropping on your connection using something like Wireshark. It also allows you to by-pass any internet content restrictions that may be in place where you are, such as a workplace or public connection.  I personally use this because I don’t like the idea of someone else listening in, and I don’t like being restricted.
What we will do is use a free program called Putty to connect to an SSH server that we have set up home. Then we will configure the machine that we are on to pass all web traffic through this encrypted connection and out through our home connection. Anyone listening in will only see one connection to your home IP, and the rest will be encrypted traffic.
Note: There is now an update to this post that also Passes all DNS Queries Through SOCKS in Firefox. Be sure to read that after you finish this tutorial for added privacy.

What You Will Need

  • An SSH server, or access to one.  (Note: Free shell providers don’t take kindly to people doing this through their servers, so check with them before you do this)  Setup of SSH server not covered here.
  • Putty client downloaded to the machine you will be working on.
  • Ability to connect outbound from your location.  Many work places limits or prevents outbound SSH connections.  You may need to run yours on a different port.

Step 1 – Configure Putty

After downloading Putty, launch it and in the left menu, go toConnection -> SSH -> Tunnels .  On the right side, enter any port above 1024 in the Source Port and select Dynamic from the radio buttons directly below it, then click Add.
It should now say D7070 in the box above.
Next, on the left side, go back to Session, and add a session profile for your home server by entering in the address underHost Name, ensure that SSH is selected underneath.  Next, create a name for your profile, and enter it in Saved Sessionsbox and then click save.  Finally, click Open at the bottom and log into your SSH server.

Step 2 – Configure Web Browser

Firefox
If you’re using the Mozilla Firefox web browser, you can configure it by going to Tools -> Options menu and then clicking Advanced on top and then select the Network tab and then Settings under Connection section.
On the Connection Settings windows, enter in 127.0.0.1 in the SOCKS Host box, and your port you selected earlier, in this case 7070.  Ensure that SOCKSv5 is selected underneath.  That’s it, now press OK until you are back at your browser window.  You’re done.
Internet Explorer
If you are using Microsoft Internet Explorer then you can go to theTools -> Internet Options menu.  Click on the Connections tab and then LAN Settings down below. Now, on the Local Area Network (LAN) Settings page, but a check mark in the Use aproxy server for your LAN and in Bypass proxy server for local addresses and then click the Advanced button.
In the Proxy Settings page, enter 127.0.0.1 in the Socks box, and the port you selected in the box next to it, in our case 7070. Now, click OK until you are back at the web browser window.
Google Chrome
Unfortunately there is no native way of setting this up in Google Chrome.  However, someone has created an extension for it that you will have to add yourself called Proxy Switchy! which you will have to add yourself. I don’t currently have Google Chrome installed so I can’t provide step-by-step instructions.

Testing

The good thing about this setup is that you don’t have to configuration anything on the SSH Server side.  To test your tunnel, just go to http://www.whatismyip.com and it should display the IP address of your home server and not your current physical location.
That’s it, enjoy, and happy private browsing!

Sunday, December 4, 2011

Thursday, December 1, 2011

make blip 2.0 error: region `rom' overflowed by 6806 bytes

mkdir -p build/telosb
    compiling PppRouterC to a telosb binary
ncc -o build/telosb/main.exe  -Os -O -DRPL_ROUTING -DRPL_STORING_MODE -I/opt/tinyos/tos/lib/net/rpl -I/opt/tinyos/tos/lib/ppp -I/opt/tinyos/tos/lib/fragpool -DPPP_HDLC_RX_FRAME_LIMIT=1 -DPPP_HDLC_TX_FRAME_LIMIT=8 -DIN6_PREFIX=\"fec0::\" -DBLIP_DERIVE_SHORTADDRS -DCC2420_HW_ACKNOWLEDGEMENTS  -DCC2420_HW_ADDRESS_RECOGNITION -DPACKET_LINK -DTOSH_DATA_LENGTH=112 -I/opt/tinyos/tos/lib/net/ -I/opt/tinyos/tos/lib/printf/ -I/opt/tinyos/support/sdk/c/blip/ -I/opt/tinyos/tos/lib/net/blip/ -I/opt/tinyos/tos/lib/net/blip/interfaces/  -I/opt/tinyos/tos/lib/net/blip/nwprog/ -I/opt/tinyos/tos/lib/net/blip/shell/ -I/opt/tinyos/tos/lib/net/blip/serial/ -I/opt/tinyos/tos/lib/net/blip/platform/ -I/opt/tinyos/tos/lib/net/blip/icmp/ -I/opt/tinyos/tos/lib/net/blip/dhcp/ /opt/tinyos/support/sdk/c/blip/lib6lowpan/iovec.c /opt/tinyos/support/sdk/c/blip/lib6lowpan/in_cksum.c /opt/tinyos/support/sdk/c/blip/lib6lowpan/ip_malloc.c /opt/tinyos/support/sdk/c/blip/lib6lowpan/utility.c /opt/tinyos/tos/lib/net/blip/table.c -fnesc-separator=__ -Wall -Wshadow -Wnesc-all -target=telosb -fnesc-cfile=build/telosb/app.c -board= -DDEFINED_TOS_AM_GROUP=0x22 -DIDENT_APPNAME=\"PppRouterC\" -DIDENT_USERNAME=\"ubuntu\" -DIDENT_HOSTNAME=\"ubuntu\" -DIDENT_USERHASH=0xf67b89f7L -DIDENT_TIMESTAMP=0x4ed7f4e0L -DIDENT_UIDHASH=0x839cc16fL  PppRouterC.nc -lm 
/opt/tinyos/tos/platforms/telosa/PlatformHdlcUartC.nc:40:2: warning: #warning Enabling DMA on UART1RX
/opt/tinyos/tos/chips/cc2420/lpl/DummyLplC.nc:39:2: warning: #warning "*** LOW POWER COMMUNICATIONS DISABLED ***"
/opt/tinyos/tos/chips/cc2420/link/PacketLinkC.nc:38:2: warning: #warning "*** USING PACKET LINK LAYER"
/opt/tinyos/tos/lib/net/blip/shell/UDPShellP.nc:260: warning: call via function pointer
/opt/tinyos/tos/platforms/telosa/PlatformHdlcUartP.nc:181: warning: `HdlcUart.receivedByte' called asynchronously from `UsartInterrupts.rxDone'
/usr/bin/../lib/gcc/msp430/4.5.3/../../../../msp430/bin/ld: build/telosb/main.exe section `.text' will not fit in region `rom'
/usr/bin/../lib/gcc/msp430/4.5.3/../../../../msp430/bin/ld: section .vectors loaded at [0000ffe0,0000ffff] overlaps section .text loaded at [00004000,00011993]
/usr/bin/../lib/gcc/msp430/4.5.3/../../../../msp430/bin/ld: region `rom' overflowed by 6806 bytes
collect2: ld returned 1 exit status
make: *** [exe0] Error 1


Using latest tools from http://tinyprod.net/debian-dev/ 
However it did not compile with stanford version either, so I guess it is not question of toolchain.
Comment 1 by project member marku...@gmail.com, Today (12 hours ago)


Fix is commenting
#OPTFLAGS += -O
in support/make/telosb.target.

Tuesday, November 1, 2011

How to use Unix/Linux commands at the Windows command prompt

source: http://www.root777.com/security/how-to-use-unixlinux-commands-at-the-windows-command-prompt/


A lot of us who use Linux at work/school or have always grown up using unix commands for years and more often than not, there might have been instances where a ls command comes more naturally than the dir command at the command prompt in Windows. For the most part, a lot of us work around this drawback using the excellent tool: Cygwin. Cygwin is available for windows users here.The Cygwin tools are ports of the popular GNU development tools for Microsoft Windows. They run thanks to the Cygwin library which provides the UNIX system calls and environment these programs expect.
With these tools installed, it is possible to write Win32 console or GUI applications that make use of the standard Microsoft Win32 API and/or the Cygwin API. As a result, it is possible to easily port many significant Unix programs without the need for extensive changes to the source code. This includes configuring and building most of the available GNU software . Even if the development tools are of little to no use to you, you may have interest in the many standard Unix utilities provided with the package. They can be used both from the bash shell (provided) or from the standard Windows command shell.
While Cygwin would be an obvious choice for many Unix/Linux power users, there is an excellent and a much simpler alternative to using Cygwin. In this article, we will show you how to run your Unix commands right in the windows command prompt.
For this, we will be using CoreUtils. CoreUtils is available through Sourceforge and is available for download here. If you look in here, there are a number of GNUWin32 packages available, the one we would be using is the CoreUtils package. CoreUtils is a collection of basic file, shell and text manipulation utilities of the GNU operating system. These are the core utilities which are expected to exist on every OS. And when I talk about File utilities, they include chgrp, chmod, cp, dd, du, ln, ls, mkdir, mv, rm, touch, vdir among others. A sample of the text utilities include cat, cksum, cut, join, md5sum, shasum, sort, split etc. The shell root commands include echo, chroot, hostname, nice, pathchk, tty, who, whoami and yes su. So it is pretty much the whole nine yards here… The direct link for download of the CoreUtils package available through SourceForge is available here.
Once installed, you will need to add the path to the utilities to your PATH environment variable. Follow the steps below to achieve this
1. Click on Start –> Run and enter sysdm.cpl to bring up the system properties Dialog
2. Click on the Advanced tab –> Environment variables button Path to environment variable
3. In the System Variables pane, scroll down to Path and then click on edit.
4. Under Edit System Variable, in the variable value, at the end of the line , type the following including the semicolon which separates the individual elements in the path variable. ;C:\Program Files\GnuWin32\bin
env variable properties
Congratulations !! You have now added the GNUWin directory to your path and Unix commands can now be executed directly from the command line and run natively on the Win32 command prompt without the need for any emulation layer as shown below using the example of dir vs ls
command prompt comparing dir vs lsDownloads and Sources
1. Download CYGWIN
2. Download CoreUtils