#include "StdAfx.h"
#include "dbClass.h"

using namespace System;
using namespace System::Data;
using namespace System::Data::OleDb;

dbClass::dbClass()
{
	// Build Connection string for this project database
	String ^connString = gcnew String("");
	connString += "Provider=Microsoft.ACE.OLEDB.12.0;";
	connString += "Data Source=projectDB.accdb;";

	// Create Connection
	cn = gcnew OleDbConnection(connString);
}

// Execute a non-select sql query
void dbClass::query( String ^strSQL ) {

	// Create new command
	OleDbCommand ^cm = gcnew OleDbCommand(strSQL, cn);

	// Run the command
	cm->ExecuteNonQuery();
}

// Execute select statement
void dbClass::select( String ^strSQL ) {

	// Create new command
	OleDbCommand ^cm = gcnew OleDbCommand(strSQL, cn);

	// Set the reader in the class to the rows returned.
	reader = cm->ExecuteReader();
}

/************************************************************************/
/* Opens the connection to the access database                  */
/************************************************************************/
void dbClass::openConnection() {
	cn->Open();
}

/************************************************************************/
/* Closes the connection to the access database                         */
/************************************************************************/
void dbClass::closeConnection() {
	cn->Close();
}

/************************************************************************/
/* This method escapes any unwanted characters in the given string for the database.*/
/************************************************************************/
String ^dbClass::escape( String ^input ) {
	// Create blank output string
	String ^output = gcnew String("");

	// Convert the system::string to a char array.
	array<wchar_t,1>^oldCharArray = input->ToCharArray();

	// Loop through each element of the array and look for
	// characters that could be used to exploit the database
	// or corrupt the input data.
	for( int i = 0; i < input->Length; i++ ) {
		switch ( oldCharArray[i] )
		{
		case '\'':
			output += "\\'" + oldCharArray[i];
			break;
		case '"':
			output += "\\\"" + oldCharArray[i];
			break;
		case '*':
			output += "\\*" + oldCharArray[i];
			break;
		default:
			output += oldCharArray[i];
			break;
		}
	}

	// Return cleaned string
	return output;
}