connecting MS Access through VC++ - visual-c++

I am new to VC++, I am trying to write a program(after lots of googling) which connects to ms access, but its showing connection error. What am I missing or doing something wrong.
Error: [Microsoft][ODBC Driver Manager] Invalid String or Buffer Length.
Here is what I am tring
Clearn_dbView::Clearn_dbView()
: COleDBRecordView(Clearn_dbView::IDD)
{
setUpODBC();
}
Clearn_dbView::~Clearn_dbView()
{
if(hDbConn != SQL_NULL_HANDLE)
{
// Free Connection.
SQLFreeHandle(SQL_HANDLE_DBC,hDbConn);
}
if(hOdbcEnv != SQL_NULL_HANDLE)
{
SQLFreeHandle(SQL_HANDLE_ENV, hOdbcEnv);
}
}
void Clearn_dbView::setUpODBC()
{
SQLRETURN sr; //Return call for ODBC
//Allocate Environment.
sr = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&hOdbcEnv);
if( sr != SQL_SUCCESS && sr != SQL_SUCCESS_WITH_INFO)
AfxMessageBox(_T("Error in Allocating Environment."));
// Set the App's ODBC Version
sr = SQLSetEnvAttr(hOdbcEnv,SQL_ATTR_ODBC_VERSION,(SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);
if(sr != SQL_SUCCESS && sr != SQL_SUCCESS_WITH_INFO)
AfxMessageBox(_T("Error in Setting ODBC Version."));;
// Allocate Connection
sr = SQLAllocHandle(SQL_HANDLE_DBC, hOdbcEnv, &hDbConn);
//sr = SQLAllocConnect(hOdbcEnv, &hDbConn);
if(sr != SQL_SUCCESS && sr != SQL_SUCCESS_WITH_INFO)
AfxMessageBox(_T("Error in Allocating Connection."));;
// Set Connect Timeout
sr = SQLSetConnectAttr(hDbConn, SQL_ATTR_LOGIN_TIMEOUT, (void*)5, 0);
if(sr != SQL_SUCCESS && sr != SQL_SUCCESS_WITH_INFO)
AfxMessageBox(_T("Error in Setting Login Timeout."));
}
void Clearn_dbView::displayODBCError(SQLRETURN sr, char *inMessage)
{
if(sr != SQL_SUCCESS && sr != SQL_SUCCESS_WITH_INFO) {
SQLWCHAR SqlState[6];
SQLINTEGER NativeError;
SQLWCHAR ErrMsg[SQL_MAX_MESSAGE_LENGTH];
int i = 1;
char message[1000];
strcpy (message, "");
if (inMessage) {
strcpy(message, inMessage);
strcat(message, " — ");
}
sprintf(message, "%sError in SQLConnect(): %d.",message, sr);
MessageBoxA(NULL,message,"Error",MB_OK);
while(SQLGetDiagRec(SQL_HANDLE_DBC, hDbConn, i,SqlState, &NativeError,ErrMsg, sizeof(ErrMsg), NULL)
!= SQL_NO_DATA) {
sprintf(message,"Diag: %d, SQLSTATE: %s NativeError: %d ErrMsg: %s",i++, SqlState, NativeError, ErrMsg);
MessageBoxA(NULL,message,"Error",MB_OK);
}
}
}
void Clearn_dbView::connectwithdb()
{
SQLRETURN sr;
SQLCHAR szDSN[] = "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DSN=D:\\Avi\\P\\mydb.mdb.dsn";
SQLCHAR szUID[] = "";
SQLCHAR szAuthStr[] = "";
if(hDbConn == NULL) {
MessageBox(_T("hDbConn IS NULL"));
return;
}
sr = SQLConnectA(hDbConn, (UCHAR *)szDSN, SQL_NTS,
(UCHAR *)szUID, SQL_NTS,
(UCHAR *) szAuthStr, SQL_NTS);
if(sr != SQL_SUCCESS && sr != SQL_SUCCESS_WITH_INFO)
{
displayODBCError(sr, "Error in OnViewConnectwithsqlconnect");
}
else
{
MessageBox(_T("else executed"));
MessageBox(_T("Connected OK"));
}
}
void Clearn_dbView::OnBnClickedConnect()
{
connectwithdb();
}

It appears that the DSN being specified in the following line is not valid:
SQLCHAR szDSN[] = "D:\\Avi\\P\\mydb.mdb";
Based on the string "D:\\Avi\\P\\mydb.mdb", it looks like the database file and path are being specified instead of the DSN.
You will need to be sure to create an ODBC DSN using the ODBC Administrator. You will provide a string for the Data Source Name field of the configuration. That string is what you will need to specify in your code for SQLCHAR szDSN[] = "".
Here is a link that explains the error in more general details, however; if you follow what is mentioned above, that should resolve the error.

Related

arduino uno if string cotains a word

I very new to Arduino Uno and need some advice....so here we go.
I want to use my Arduino to:
1. read my serial data --received as plain text
2. look for a specific word within a line of data received
3. only transmit/print the complete string if it contains the specific "word"
I found this sketch and it works only if I'm looking for char
// Example 3 - Receive with start- and end-markers
const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
void setup() {
Serial.begin(9600);
Serial.println("<Arduino is ready>");
}
void loop() {
recvWithStartEndMarkers();
showNewData();
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.println(receivedChars);
newData = false;
}
}
I think it is better to use String class methods.
you can get the Data using Serial.readString()
then use the String methods for looking for a specific word.
Here are some useful links
https://www.arduino.cc/en/Serial/ReadString
https://www.arduino.cc/en/Reference/StringObject

redirect CreateProcess output to Shared Memory created Using CreateFileMapping VC++

I have a Main VC++ application which is creating the shared memory as in below code:
if (m_hMapFile == NULL)
{
SECURITY_ATTRIBUTES structSecurityAttr = { 0 };
m_hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, &structSecurityAttr, PAGE_READWRITE | SEC_COMMIT, 0, BUF_SIZE, (LPCSTR)(LPCTSTR)szName);
if (m_hMapFile == NULL)
{
DWORD dwError = GetLastError();
CString strError;
strError.Format(_T("%lu"), dwError);
return FALSE;
}
pSharedMemBuf = (LPTSTR)MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
if (pSharedMemBuf == NULL)
{
return FALSE;
}
//Initialize the Shared Memory.
ZeroMemory((void *)pSharedMemBuf, BUF_SIZE);
}
From a thread of this main process I am mapping to the shared memory as below:
if (m_hMapFile == NULL)
{
//Open the Named Shared Memory
m_hMapFile = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE | FILE_MAP_COPY, TRUE, (LPCSTR)(LPCTSTR)szName); //FILE_MAP_ALL_ACCESS
if (m_hMapFile == NULL)
{
return FALSE;
}
//Get the Shared Memory Buffer Pointer.
pSharedMemBuf = (LPTSTR)MapViewOfFile(m_hMapFile, FILE_MAP_READ | FILE_MAP_WRITE | FILE_MAP_COPY/*FILE_MAP_ALL_ACCESS*/, 0, 0, BUF_SIZE);
DWORD error = GetLastError();
//If Shared Memory Buffer is NULL then return the control
if (pSharedMemBuf == NULL)
{
CString strSize;
strSize.Format(_T("Error is %d"), error);
return FALSE;
}
}
Now, I want to redirect the output of the CreateProcess call to this shared memory. I am giving the FileMapping's STARTUPINFO as below:
si.hStdOutput = m_hMapFile;
si.hStdError = m_hMapFile;
Then creating the process as below:
CreateProcess( NULL, szCombinedCmd, &saAttr, NULL, TRUE,
dwCreateFlags, NULL, pszCurrentDirectory, &si, &pi );
But, When I am trying to read the shared memory I am not getting the output into the buffer. Please help me how to achieve this.

Command Timeout, longer to get response back

I am executing large query,so my app throwing time out error. Some of the thread suggested to added command time out but after adding those lines it take longer to get response back, any idea why or what am i missing in my code?
public int CreateRecord(string theCommand, DataSet theInputData)
{
int functionReturnValue = 0;
int retVal = 0;
SqlParameter objSqlParameter = default(SqlParameter);
DataSet dsParameter = new DataSet();
int i = 0;
try
{
//Set the command text (stored procedure name or SQL statement).
mobj_SqlCommand.CommandTimeout = 120;
mobj_SqlCommand.CommandText = theCommand;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
for (i = 0; i <= (theInputData.Tables.Count - 1); i++)
{
if (theInputData.Tables[i].Rows.Count > 0)
{
dsParameter.Tables.Add(theInputData.Tables[i].Copy());
}
}
objSqlParameter = new SqlParameter("#theXmlData", SqlDbType.Text);
objSqlParameter.Direction = ParameterDirection.Input;
objSqlParameter.Value = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + dsParameter.GetXml();
//Attach to the parameter to mobj_SqlCommand.
mobj_SqlCommand.Parameters.Add(objSqlParameter);
//Finally, execute the command.
retVal = (int)mobj_SqlCommand.ExecuteScalar();
//Detach the parameters from mobj_SqlCommand, so it can be used again.
mobj_SqlCommand.Parameters.Clear();
functionReturnValue = retVal;
}
catch (Exception ex)
{
throw new System.Exception(ex.Message);
}
finally
{
//Clean up the objects created in this object.
if (mobj_SqlConnection.State == ConnectionState.Open)
{
mobj_SqlConnection.Close();
mobj_SqlConnection.Dispose();
mobj_SqlConnection = null;
}
if ((mobj_SqlCommand != null))
{
mobj_SqlCommand.Dispose();
mobj_SqlCommand = null;
}
if ((mobj_SqlDataAdapter != null))
{
mobj_SqlDataAdapter.Dispose();
mobj_SqlDataAdapter = null;
}
if ((dsParameter != null))
{
dsParameter.Dispose();
dsParameter = null;
}
objSqlParameter = null;
}
return functionReturnValue;
}

How i can destroy playerObj?

i'm trying creating engine and output Mix:
// create engine
this->res = slCreateEngine(&this->engineObject, 0, NULL, 0, NULL, NULL);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Create Engine.");
this->Free();
return;
}
this->res = (*this->engineObject)->Realize(this->engineObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Realize Engine.");
this->Free();
return;
}
this->res = (*this->engineObject)->GetInterface(this->engineObject, SL_IID_ENGINE, &this->engineEngine);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't GetInterface Engine.");
this->Free();
return;
}
// create output mix
this->res = (*this->engineEngine)->CreateOutputMix(this->engineEngine, &this->outputmixObject, 0, NULL, NULL);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Create Output Mix.");
this->Free();
return;
}
this->res = (*this->outputmixObject)->Realize(this->outputmixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Realize Output Mix.");
this->Free();
return;
}
that is successful!
Start playing mp3 stream from IceCast
(example "http://example.com/stream320"):
SLDataLocator_URI loc_uri = {SL_DATALOCATOR_URI, filename};
SLDataFormat_MIME format_mime = {SL_DATAFORMAT_MIME, (SLchar*)NULL, SL_CONTAINERTYPE_UNSPECIFIED};
SLDataSource audioSrcuri = {&loc_uri, &format_mime};
SLDataLocator_OutputMix dataLocatorOut = {SL_DATALOCATOR_OUTPUTMIX,this->outputmixObject};
SLDataSink audioSnk = {&dataLocatorOut, NULL};
const SLInterfaceID pIDs[3] = {SL_IID_PLAY, SL_IID_SEEK, SL_IID_PREFETCHSTATUS};
const SLboolean pIDsRequired[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
this->res = (*this->engineEngine)->CreateAudioPlayer(this->engineEngine, &this->player, &audioSrcuri, &audioSnk, 3, pIDs, pIDsRequired);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Create Audio Player.");
return;
}
this->res = (*this->player)->Realize(this->player, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Realize Audio Player.");
return;
}
this->res = (*this->player)->GetInterface(this->player, SL_IID_PLAY, &this->playerInterface);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Get Interface \"SL_IID_PLAY\" from Audio Player.");
return;
}
this->res = (*this->player)->GetInterface(this->player, SL_IID_SEEK, &this->seekInterface);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Get Interface \"SL_IID_SEEK\" from Audio Player.");
return;
}
this->res = (*this->player)->GetInterface(this->player, SL_IID_PREFETCHSTATUS, &this->prefetchInterface);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Get Interface \"SL_IID_PREFETCHSTATUS\" from Audio Player.");
return;
}
this->res = (*this->playerInterface)->SetPlayState(this->playerInterface, SL_PLAYSTATE_PAUSED);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Set Play State \"SL_PLAYSTATE_PAUSED\".");
return;
}
this->LastPlayState = SL_PLAYSTATE_PAUSED;
/*SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
while (prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA)
{
LOGI("Wait until there's data to play...");
usleep(1 * 1000);
(*this->prefetchInterface)->GetPrefetchStatus(this->prefetchInterface, &prefetchStatus);
}
LOGI("Data OK.");
/* Get duration */
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
this->res = (*this->playerInterface)->GetDuration(this->playerInterface, &durationInMsec);
if (SL_RESULT_SUCCESS != this->res)
{
LOGI("Can't Get Duration.");
return;
}
if (durationInMsec == SL_TIME_UNKNOWN) {
LOGI("durationInMsec = SL_TIME_UNKNOWN");
//durationInMsec = 5000;
}
(*this->seekInterface)->SetLoop(this->seekInterface,SL_BOOLEAN_FALSE,0,SL_TIME_UNKNOWN);
filename = "http://example.com/stream320";
LogCat began print a Error msg...:
E/libOpenSLES(16432): MEDIA_BUFFERING_UPDATE -491520000% < 0
E/libOpenSLES(16432): MEDIA_BUFFERING_UPDATE -655360000% < 0
E/libOpenSLES(16432): MEDIA_BUFFERING_UPDATE -819200000% < 0
...
but stream is playing!
Ok, so i'm trying stop playing:
this->res = (*this->playerInterface)->SetPlayState(this->playerInterface, SL_PLAYSTATE_STOPPED);
if (SL_RESULT_SUCCESS != this->res)
LOGI("Can't Set Play State \"SL_PLAYSTATE_STOPPED\".");
OK! Play really is stopped, but player continues downloading stream.
???
So i'm try destroy PlayerObj:
(*this->player)->Destroy(this->player);
LogCat printed Error msg:
A//system/bin/app_process(16690): stack corruption detected: aborted
and app process terminated.
What is wrong?

J2ME, Nokia, HttpConnection

This code works fine on SonyEricsson and Motorola cellphones, but on Nokia it either fails at the beginnig not making any request at all or returns empty response, depending on model.
HttpConnection hc = null;
InputStream is = null;
InputStreamReader isr = null;
String result = "";
try
{
hc = (HttpConnection) Connector.open(url);
int rc = hc.getResponseCode();
if (rc != HttpConnection.HTTP_OK)
{
throw new IOException(hc.getResponseMessage());
}
is = hc.openInputStream();
isr = new InputStreamReader(is, "utf-8");
int ch;
while ((ch = is.read()) != -1)
{
result += (char) ch;
}
}
finally
{
if (is != null)
{
is.close();
}
if (hc != null)
{
hc.close();
}
}
return result;
Tried different codes with byte buffers, streams, etc, result is always the same. What's the problem?
try it
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class Transport {
public static int BUFFER_LENGTH = 100;//1024;
public static boolean USE_FLUSH = false;
static {
if (DeviceDetect.getDeivice() == DeviceDetect.SAMSUNG) {
BUFFER_LENGTH = 1024;
USE_FLUSH = true;
}
}
public static String SESSION_COOKIE = null;
private static int rnd = 1;
private static final String request(String url, String method, Hashtable params) throws IOException {
HttpConnection conn = null;
DataOutputStream dos = null;
InputStream in = null;
try {
String encodedParams = null;
if (params != null && params.size() > 0) {
encodedParams = getEncodedParams(params);
}
if (method == null) {
if (encodedParams.length() < 2000) {
method = "GET";
} else {
method = "POST";
}
}
method = method != null && method.equalsIgnoreCase("POST") ? HttpConnection.POST : HttpConnection.GET;
if (method.equalsIgnoreCase(HttpConnection.GET)) {
if (encodedParams != null) {
url += (url.indexOf("?") == -1 ? "?" : "&") + encodedParams;
encodedParams = null;
}
url += (url.indexOf("?") == -1 ? "?" : "&") + "_rnd=" + rnd++;
}
conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
if (conn == null) {
throw new IOException("HttpConnection is null, please check Access Point configuration");
}
conn.setRequestMethod(method);
conn.setRequestProperty("User-Agent", UserAgent.getUserAgent());
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (SESSION_COOKIE != null) {
conn.setRequestProperty("Cookie", SESSION_COOKIE);
}
byte[] buff = new byte[BUFFER_LENGTH];
if (encodedParams != null) {
byte[] bytes = encodedParams.getBytes("UTF-8");
String lengthStr = bytes.length + "";
conn.setRequestProperty("Content-Length", lengthStr);
dos = conn.openDataOutputStream();
if (dos == null) {
throw new IOException("OutputStream is null, please check Access Point configuration");
}
for (int i = 0, l = bytes.length; i < l; i += Transport.BUFFER_LENGTH) {
if (Transport.BUFFER_LENGTH == 1) {
dos.writeByte(bytes[i]);
} else {
int count = Math.min(Transport.BUFFER_LENGTH, l - i);
System.arraycopy(bytes, i, buff, 0, count);
dos.write(buff, 0, count);
}
if (Transport.USE_FLUSH) {
dos.flush();
}
}
dos.flush();
try {
dos.close();
} catch (IOException ex) {
}
}
String setCookie = conn.getHeaderField("Set-Cookie");
if (setCookie != null) {
int ind1 = setCookie.indexOf("JSESSIONID=");
if (ind1 > -1) {
int ind2 = setCookie.indexOf(";", ind1);
SESSION_COOKIE = ind2 == -1 ? setCookie.substring(ind1) : setCookie.substring(ind1, ind2 + 1);
}
}
in = conn.openInputStream();
if (in == null) {
throw new IOException("InputStream is null, please check Access Point configuration");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = in.read(buff);
while (n > -1) {
baos.write(buff, 0, n);
n = in.read(buff);
}
baos.flush();
baos.close();
String response = new String(baos.toByteArray(), "UTF-8");
try {
in.close();
} catch (Exception ex) {
}
try {
conn.close();
} catch (Exception ex) {
}
return response;
} finally {
try {
dos.close();
} catch (Exception ex) {
}
try {
in.close();
} catch (Exception ex) {
}
try {
conn.close();
} catch (Exception ex) {
}
}
}
public static String getEncodedParams(Hashtable params) throws IOException {
String str = "";
Enumeration keys = params.keys();
while (keys.hasMoreElements()) {
String name = (String) keys.nextElement();
Object value = params.get(name);
if (value == null || name == null) {
continue;
}
str += "&" + URLEncoder.encode(name.toString(), "UTF-8") + "=" + URLEncoder.encode(value.toString(), "UTF-8");
}
if (str.length() > 1) {
str = str.substring(1);
}
return str;
}
}
I am not sure if this will work for you but I had a similar problem and found that specifying a port number made it work (on some older Nokia models). i.e convert:
http://www.mysite.com/my_page.html
to:
http://mysite.com:80/my_page.html

Resources