Events – fire that event

An event will be fired when something has happened and then you can link to that event and do something else if you wanted to. To start of with you have to link a event with a delegate function which will be the event handler.

To setup a delegate you can have the object and also any event arguments ( you can add in more if you want to, but these are the basics to include)

	// setup a delegate for the event to fire with.
	public delegate void ChangedEventHandler(object sender, EventArgs e);

here is the class that will actual fire the event, to start with I link the “event” to a virtual method as such called Changed (with the delegate from above ChangedEventHander).

	// this is the MyEvent class that will create the event fired.
	public class MyEvent 
	{
		private int x;
 
		// the event for this internal class
		public event ChangedEventHandler Changed;

here is the event firing function, this will call the Changed “virtual” method as such when ever you call this function.

		protected virtual void ThisHasChanged(EventArgs e)
		{
			// try and call the delegate ChangedEventHandler
			// make sure that there is something to call for the event to fire.
			if (Changed != null)
				Changed(this, e);
		}

and here is the get/set for the internal X variable and in the set I call the ThisHasChanged function above.

		// call the ThisHasChanged event when you set the internal value of X.
		public int xValue
		{
			get { return x;}
			set { x = value;ThisHasChanged(EventArgs.Empty); }
		}
	}

So that is the event firing, but you will need to have a listener that will listen to any events and call something that will deal with the fired event, so here is the listener class.

So the listener, is just like any other class, but you will need to have a internal reference to the class above so that you can link to the event fired, so here is the MyEvent internal class for the listener.

	// the listener for the event firing
	class EventListener
	{
		// MyEvent class
		private MyEvent ThisIsMyEvent;

and then the constructor for the EventListener, you pass in the MyEvent class that you want to “link” (the one that you will create within the running part of the program). and from within the MyEvent, there was a “virtual” method as such called “Changed”, well now we can create a link so that when that event “Changed” has been called from within the MyEvent Class I can link to a function within this class EventListener with using a new delegate ChangedEventHandler and the ValueHadChanged is within the EventListener class.

		// the class constructor and you need to pass the MyEvent class to link to the listener.
		public EventListener(MyEvent SetUpTheEventLink)
		{
			// Create a link to the MyEvent class passed in to the internal MyEvent Class
			ThisIsMyEvent = SetUpTheEventLink;
			// this is the link to the listern function.
			ThisIsMyEvent.Changed += new ChangedEventHandler(ValueHadChange);
		}

here is the ValueHadChange, same setup as the delegate parameters since we are basically passing event details between them both and can pass in more details is you want to, but you really only want to have the object (the MyEvent class) and any event arguments e.g. errors etc. at present it just says , “Oh yeah.. I have altered”.

		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
		}

since there was a Changed link attached to the above function, to clean up you can detach the link with using something similar to the constructor of this class, but instead of using += (to add) you just need to subtract from the Change virtual method -=

		// detach the listener function from the event MyEvent 
		public void Detach()
		{
			// take the event linked from the MyEvent class.
			ThisIsMyEvent.Changed -= new ChangedEventHandler(ValueHadChange);
			ThisIsMyEvent = null;
		}
	}

Here is the full code

using System;
 
// when alter a number in the internal part of the class.
namespace codingfriendsEvents
{
	// setup a delegate for the event to fire with.
	public delegate void ChangedEventHandler(object sender, EventArgs e);
 
	// this is the MyEvent class that will create the event fired.
	public class MyEvent 
	{
		// the event for this internal class
		public event ChangedEventHandler Changed;
 
		private int x;
 
		protected virtual void ThisHasChanged(EventArgs e)
		{
			// try and call the delegate ChangedEventHandler
			// make sure that there is something to call for the event to fire.
			if (Changed != null)
				Changed(this, e);
		}
 
		// call the ThisHasChanged event when you set the internal value of X.
		public int xValue
		{
			get { return x;}
			set { x = value;ThisHasChanged(EventArgs.Empty); }
		}
	}
 
	// the listener for the event firing
	class EventListener
	{
		// MyEvent class
		private MyEvent ThisIsMyEvent;
 
		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
		}
 
		// the class constructor and you need to pass the MyEvent class to link to the listener.
		public EventListener(MyEvent SetUpTheEventLink)
		{
			// Create a link to the MyEvent class passed in to the internal MyEvent Class
			ThisIsMyEvent = SetUpTheEventLink;
			// this is the link to the listern function.
			ThisIsMyEvent.Changed += new ChangedEventHandler(ValueHadChange);
		}
 
		// detach the listener function from the event MyEvent 
		public void Detach()
		{
			// take the event linked from the MyEvent class.
			ThisIsMyEvent.Changed -= new ChangedEventHandler(ValueHadChange);
			ThisIsMyEvent = null;
		}
	}
 
	class TestMyEvent
	{
		public static void Main()
		{
			// create a new MyEvent class
			MyEvent MyEventToCheck = new MyEvent();
 
			// link in with the EventLister , passing in the class of MyEvent
			EventListener TheListener = new EventListener(MyEventToCheck);
 
			// should fire of a event !! because I am changing the internal x value.
			MyEventToCheck.xValue = 10;
 
			// will not fire a event because I have not changed it.
			Console.WriteLine("X = " + MyEventToCheck.xValue);
 
			// will fire of another event.
			MyEventToCheck.xValue = 5;
 
			TheListener.Detach();
		}
	}
}

and here would be the output

Oh yeah.. I have been altered
X = 10
Oh yeah.. I have been altered

If you want to gain access to the object sender within the EventListener class to the function that was listening to the event fired, if you alter it as below, but also since because the MyEvent was also linked within the constructor you also have that link as well.

		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
			Console.WriteLine("New value of X = " + ((MyEvent)sender).xValue);
			Console.WriteLine("Internal MyEvent class x = " + ThisIsMyEvent.xValue);
		}

then you can gain access to the MyEvent from within the object sender and the output would be

Oh yeah.. I have been altered
New value of X = 10
Internal MyEvent class x = 10
X = 10
Oh yeah.. I have been altered
New value of X = 5
Internal MyEvent class x = 5

enum – what are they

A enum type is basically a array on constant elements that you can assign to words a integer value.

To give a example, lets say that you have a different type of car

enum cars { VAUX, FORD, LAND };

which in turn mean that VAX = 0 and FORD = 1 and LAND = 2, arrays start from 0 of course.

So you can use the code as

enum cars car = VAUX;
if (car == VAUX) printf("Vauxhall car\n");

which would make more sense than saying

int car = 0;
if (car == 0) printf("Vauxhall car\n");

struct – what are they for

A struct (structure) is a defined type that the user can define at compile time, for example if you want to have a user defined type that holds details of a database connection you could hold the hostname, username, password of the database connection within a structure (struct) without having to define 3 different variables you only have one that you need to fill in.

For the above example of a database struct

struct database_connection
{
   char *username;
   char *hostname;
   char *password;
};

then within the code you could create a new structure of this type and also fill in the details as

database_connection mydatabase;
mydatabase.username = "usernamebob";
mydatabase.hostname = "localhost";
mydatabase.password = "userpassword";

and you just need to pass that struct to a function if you wanted to to do the connections e.g.

bool dummyconnection(database_connection conn)
{
   createdatabase( conn.hostname, conn.username, conn.password);
}

saves passing in three different parameters.

typedef – what are they for

The typedef is to shorten the naming of some types e.g. is you want to have short unsigned called SHORTUN for quicker typing you can use the type definition syntax of

typedef <old type> <new type>

so regarding the example of short unsigned to SHORTUN

typedef short unsigned SHORTUN

a probably better example would be if you wanted to have a apple as a type (which would be a integer value) then you could

typedef in APPLE

now you could use the code

APPLE apple = 1;

root password reset

Within the standard ubuntu or the derviertives (kubuntu/edubuntu etc) the root password is not set and the way to gain access to the root commands is via the command line

sudo command here

I personally prefer to have root password set because then I can use the root admin rights on the desktop without having to constantly type in sudo all of the time, so to set the root password to something that I will use you can use this

sudo set password root

this will set the password to something that you can remember and thus any time that you want to have a console open as root just type in

su

and then the password and you are in the root console 🙂

mysql – connection example

Mysql is a database, and to gain access to the data within C++ you will need to be able to “talk” to the database via queries (just like on the mysql command line interface e.g. select * from tablename), the connection process is very similar to the command line interface you will need to supply connection details as in hostname (localhost normally), username, password, database to use and also there are other details that you can pass e.g port number more information can be gained from the MYSQL API pages

To start with I created a struct that will hold the username, host etc details.

struct connection_details
{
    char *server;
    char *user;
    char *password;
    char *database;
};

In essence to connect to a database I have created a function that 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;
}

That is it, you are connected now, now you can perform some sql queries, once again I have created a function to accomplish this and it returns a MYSQL_RES (mysql result pointer)

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);
}

since you are now connected and also preformed a query, lets say the query was

SHOW TABLES;

You can traverse the results with 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.

MYSQL_ROW row;
  while ((row = mysql_fetch_row(res)) !=NULL)
      printf("%s\n", row[0]);

Here is the full code that will display all of the tables within the mysql database database, you will need to alter the username and password for the mysql access details.

#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
 
// just going to input the general details and not the port numbers
struct connection_details
{
    char *server;
    char *user;
    char *password;
    char *database;
};
 
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;
}
 
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);
}
 
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 = "mysqlusername";		// the root user of mysql	
  mysqlD.password = "mysqlpassword"; // the password of the root user in mysql
  mysqlD.database = "mysql";	// 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, "show tables");
 
  printf("MySQL Tables in mysql database:\n");
  while ((row = mysql_fetch_row(res)) !=NULL)
      printf("%s\n", row[0]);
 
  /* clean up the database result set */
  mysql_free_result(res);
  /* clean up the database link */
  mysql_close(conn);
 
  return 0;
}

To compile up this program you will need to link to the mysql libraries and headers that are used within the program, e.g. mysql.h at the top of the program. To gain access to these, there is a nice mysql_config (you may need to install it via your package manager system if you do not have it already).

Here are my outputs of what is required on the command line for the g++ compiler

mysql_config --cflags
-I/usr/include/mysql  -DBIG_JOINS=1  -fno-strict-aliasing   -DUNIV_LINUX
mysql_config --libs
-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql -lmysqlclient

These are the g++/c++ switches that tell the compiler where the libraries (-L) are and the headers (-I) and to insert into the g++/c++ compiler line within linux you can do something like

g++ -o mysqlconnect $(mysql_config --cflags) mysqlconnect.cpp $(mysql_config --libs)

Where the mysqlconnect.cpp is the c++ file of the above program and the output would be

./mysqlconnect
MySQL Tables in mysql database:
columns_priv
db
event
func
general_log
help_category
help_keyword
help_relation
help_topic
host
ndb_binlog_index
plugin
proc
procs_priv
servers
slow_log
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_transition
time_zone_transition_type
user

Equals why ? and why not ==

In Object oriented programming languages, there is a nice keyword that is “new” what this does is create a new instance of a object and run the objects constructor method and setup up the internal variables, for example.

class classA 
{
	private int x;
 	public	classA() { x= 0;}
	public	classA(int value) { x = value;}
}
...
classA a = new classA();

this will create a new instance of A with the constructor (same name as the class) setting x equal to 0. What is happening is that the variable “a” is pointing to a memory location of the newly created object on the memory heap for example.

Local variables

Object Memory location / value
a 0x0102

which the 0x0102 memory location is pointing to a newly constructed classA space

Memory location Object values
0x0102 classA – a instance over head (garage collection etc)
0x0104 x value 0

There is over head details associated with the classA (a instance) for the garage collection/polymorphism for example. So the actual “a” variable is just pointing to this place in memory, if you created a new classA instance then another place in memory will be created, for example lets create classA a2 as

classA a2 = new classA();

and now a example of the memory locations / values would be similar to

Local variables

Object Memory location / value
a 0x0102
a2 0x0108

with the memory heap as such.

Memory location Object values
0x0102 classA – a instance over head (garage collection etc)
0x0104 x value 0
0x0108 classA – a2 instance over head (garage collection etc)
0x010a x value 0

so you would have thought that if you did,

if (a == a2)

then they would be equal, since both have a value of 0 ? well this is not the case, since the == is just comparing the value within the variable and thus the a = 0x0102 and a2 = 0x0108 which are not equal. To compare two different instances of a class you need to override the Equals function within the class (all classes are derived from object class)

So the code would be

		// override the inhertant object object Equals function
		public override bool Equals(object obj)
		{
			// cast the obj into a classA and then compare the x values
			if (x == ((classA)obj).x)
				return true;
			else
				return false;
		}

and now you can compare the two classA instances with

if (a.Equals(a2))

since the Equals function is actually comparing the values within the class instance and not the a/a2 variable values (which point to memory locations).

Here is the full code

using System;
 
namespace equaltest
{
	class classA 
	{
		private int x;
	 	public	classA() { x= 0;}
		public	classA(int value) { x = value;}
 
		public int xValue {
			get { return x;}
			set { x = value;}
		}
 
		// override the inhertant object object Equals function
		public override bool Equals(object obj)
		{
			// cast the obj into a classA and then compare the x values
			if (x == ((classA)obj).x)
				return true;
			else
				return false;
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			classA a = new classA();
			a.xValue = 10;
			Console.WriteLine("A x value = " + a.xValue);
 
			classA a2 = new classA();
			a2.xValue = 10;
			Console.WriteLine("A2 x value = " +a2.xValue);
			//so they are the same in x values, but are they the same !! ==
 
			if (a == a2)
				Console.WriteLine("a does equal a2");
			else
				Console.WriteLine("a does not equal a2");
 
			// of course they are NOT the same value, because the equals is comparing there actual object values
			// and not there x value inside them, and with the "new" keyword they are both pointing to different 
			// places on the heap of storage, thus they are NOT the same..
			// a may equal heap storage = 0x1010
			// a2 may equal heap storage= 0x1020
			// both have the same x value but different memory location values.
 
			// but implementing a Eqauls comparsion function you can compare the two variables internals 
			// as you see fit.
			if (a.Equals(a2))
				Console.WriteLine("a does equal a2");
			else
				Console.WriteLine("a does not equal a2");
 
		}
	}
}

and the output would be

A x value = 10
A2 x value = 10
a does not equal a2
a does equal a2

since I am overriding the Equals from the base object class, the compiler may warn that I am not overriding the GetHaseCode(), but that is k for this example.

Example of the compiler warning message

Description=`equaltest.classA' overrides Object.Equals(object) but does not override Object.GetHashCode()(CS0659)]