Add library into cascades - blackberry-10

Hi I am developing an application to unzip files in blackberry10. For unzipping files I am using quazip library code I get from github. But I dont know how to add this library to my project can anybody please let me know how to add library to blackbery cascades.

To add a library to your BlackBerry 10 project in Momentics you just need to right click on the project and go to Configure->Add Library...
This will start the Add Library wizard where you can specify the path to your library. Just remember to update your .pro file. Instructions for doing this are in the wizard. If you're dynamically linking it you'll also need to update your bar-descriptor.xml so that the library is packaged in your BAR file as an asset.

I have successful experience in using quazip library in my project. Here are the steps you need to follow in order to get it working in your app:
1. Download a copy of zip archive from QuaZip home page
2. Copy the following files across into your project source folder:
qioapi.cpp
quazip.cpp
quazipfile.cpp
quazipnewinfo.cpp
unzip.c
zip.c
crypt.h
ioapi.h
quazipdir.h
quazipfile.h
quazipfileinfo.h
quazip_global.h
quazip.h
quazipnewinfo.h
unzip.h
zip.h
3. Create an utility class for handling archives:
Header file:
#ifndef ZIPPER_H_
#define ZIPPER_H_
#include <QObject>
#include <QDir>
#include "quazip.h"
#include "quazipfile.h"
class Zipper : public QObject {
Q_OBJECT
public:
Zipper() {}
virtual ~Zipper() {}
static bool extract(const QString & filePath, const QString & extDirPath, const QString & singleFileName = QString(""));
static bool archive(const QString & filePath, const QDir & dir, const QString & comment = QString(""));
Q_DISABLE_COPY(Zipper)
};
Source file:
#include <QFile>
#include <QDir>
#include "Zipper.h"
bool Zipper::extract(const QString & filePath, const QString & extDirPath, const QString & singleFileName) {
QuaZip zip(filePath);
if (!zip.open(QuaZip::mdUnzip)) {
qWarning("testRead(): zip.open(): %d", zip.getZipError());
return false;
}
zip.setFileNameCodec("IBM866");
qWarning("%d entries\n", zip.getEntriesCount());
qWarning("Global comment: %s\n", zip.getComment().toLocal8Bit().constData());
QuaZipFileInfo info;
QuaZipFile file(&zip);
QFile out;
QString name;
char c;
for (bool more = zip.goToFirstFile(); more; more = zip.goToNextFile()) {
if (!zip.getCurrentFileInfo(&info)) {
qWarning("testRead(): getCurrentFileInfo(): %d\n", zip.getZipError());
return false;
}
if (!singleFileName.isEmpty())
if (!info.name.contains(singleFileName))
continue;
if (!file.open(QIODevice::ReadOnly)) {
qWarning("testRead(): file.open(): %d", file.getZipError());
return false;
}
name = QString("%1/%2").arg(extDirPath).arg(file.getActualFileName());
if (file.getZipError() != UNZ_OK) {
qWarning("testRead(): file.getFileName(): %d", file.getZipError());
return false;
}
//out.setFileName("out/" + name);
qWarning ("using %s for output fileName", qPrintable(name));
out.setFileName(name);
// this will fail if "name" contains subdirectories, but we don't mind that
out.open(QIODevice::WriteOnly);
// Slow like hell (on GNU/Linux at least), but it is not my fault.
// Not ZIP/UNZIP package's fault either.
// The slowest thing here is out.putChar(c).
while (file.getChar(&c)) out.putChar(c);
out.close();
if (file.getZipError() != UNZ_OK) {
qWarning("testRead(): file.getFileName(): %d", file.getZipError());
return false;
}
if (!file.atEnd()) {
qWarning("testRead(): read all but not EOF");
return false;
}
file.close();
if (file.getZipError() != UNZ_OK) {
qWarning("testRead(): file.close(): %d", file.getZipError());
return false;
}
}
zip.close();
if (zip.getZipError() != UNZ_OK) {
qWarning("testRead(): zip.close(): %d", zip.getZipError());
return false;
}
return true;
}
bool Zipper::archive(const QString & filePath, const QDir & dir, const QString & comment) {
QuaZip zip(filePath);
zip.setFileNameCodec("IBM866");
if (!zip.open(QuaZip::mdCreate)) {
qDebug("testCreate(): zip.open(): %d", zip.getZipError());
return false;
}
if (!dir.exists()) {
qDebug("dir.exists(%s)=FALSE", qPrintable(dir.absolutePath()));
return false;
}
QFile inFile;
QStringList sl;
// what's this ??
// recurseAddDir(dir, sl);
QFileInfoList files;
foreach (QString fn, sl) files << QFileInfo(fn);
QuaZipFile outFile(&zip);
char c;
foreach(QFileInfo fileInfo, files) {
if (!fileInfo.isFile())
continue;
QString fileNameWithRelativePath = fileInfo.filePath().remove(0, dir.absolutePath().length() + 1);
inFile.setFileName(fileInfo.filePath());
if (!inFile.open(QIODevice::ReadOnly)) {
qDebug("testCreate(): inFile.open(): %s", qPrintable(inFile.errorString()));
return false;
}
if (!outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(fileNameWithRelativePath, fileInfo.filePath()))) {
qDebug("testCreate(): outFile.open(): %s", qPrintable(outFile.getZipError()));
return false;
}
while (inFile.getChar(&c) && outFile.putChar(c));
if (outFile.getZipError() != UNZ_OK) {
qDebug("testCreate(): outFile.putChar(): %d", outFile.getZipError());
return false;
}
outFile.close();
if (outFile.getZipError() != UNZ_OK) {
qDebug("testCreate(): outFile.close(): %d", outFile.getZipError());
return false;
}
inFile.close();
}
if (!comment.isEmpty())
zip.setComment(comment);
zip.close();
if (zip.getZipError() != 0) {
qDebug("testCreate(): zip.close(): %d", zip.getZipError());
return false;
}
return true;
}
4. Then use it in your project like that:
bool rc = Zipper::extract(filePath, pathToUnpack);
qDebug("extracting %s", rc ? "success" : "failure");

Related

How to host a html using sd card

i wanna host a webserver from a sd card using ESP8266. i look through the github library SDWebServer, and i tried the code it came out following error
error: 'class String' has no member named 'clear' and the line of code "path.clear();" is causing this error
Can anyone help to solve or anyone has better example code to share with me?
/* SDWebServer - Example WebServer with SD Card backend for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the ESP8266WebServer library for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Have a FAT Formatted SD Card connected to the SPI port of the ESP8266
The web root is the SD Card root folder
File extensions with more than 3 charecters are not supported by the SD Library
File Names longer than 8 charecters will be truncated by the SD library, so keep filenames shorter
index.htm is the default index (works on subfolders as well)
upload the contents of SdRoot to the root of the SDcard and access the editor by going to http://esp8266sd.local/edit
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <SD.h>
#define DBG_OUTPUT_PORT Serial
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "esp8266sd";
ESP8266WebServer server(80);
static bool hasSD = false;
File uploadFile;
void returnOK() {
server.send(200, "text/plain", "");
}
void returnFail(String msg) {
server.send(500, "text/plain", msg + "\r\n");
}
bool loadFromSdCard(String path) {
String dataType = "text/plain";
if (path.endsWith("/")) {
path += "index.htm";
}
if (path.endsWith(".src")) {
path = path.substring(0, path.lastIndexOf("."));
} else if (path.endsWith(".htm")) {
dataType = "text/html";
} else if (path.endsWith(".css")) {
dataType = "text/css";
} else if (path.endsWith(".js")) {
dataType = "application/javascript";
} else if (path.endsWith(".png")) {
dataType = "image/png";
} else if (path.endsWith(".gif")) {
dataType = "image/gif";
} else if (path.endsWith(".jpg")) {
dataType = "image/jpeg";
} else if (path.endsWith(".ico")) {
dataType = "image/x-icon";
} else if (path.endsWith(".xml")) {
dataType = "text/xml";
} else if (path.endsWith(".pdf")) {
dataType = "application/pdf";
} else if (path.endsWith(".zip")) {
dataType = "application/zip";
}
File dataFile = SD.open(path.c_str());
if (dataFile.isDirectory()) {
path += "/index.htm";
dataType = "text/html";
dataFile = SD.open(path.c_str());
}
if (!dataFile) {
return false;
}
if (server.hasArg("download")) {
dataType = "application/octet-stream";
}
if (server.streamFile(dataFile, dataType) != dataFile.size()) {
DBG_OUTPUT_PORT.println("Sent less data than expected!");
}
dataFile.close();
return true;
}
void handleFileUpload() {
if (server.uri() != "/edit") {
return;
}
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
if (SD.exists((char *)upload.filename.c_str())) {
SD.remove((char *)upload.filename.c_str());
}
uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE);
DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename);
} else if (upload.status == UPLOAD_FILE_WRITE) {
if (uploadFile) {
uploadFile.write(upload.buf, upload.currentSize);
}
DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize);
} else if (upload.status == UPLOAD_FILE_END) {
if (uploadFile) {
uploadFile.close();
}
DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
}
}
void deleteRecursive(String path) {
File file = SD.open((char *)path.c_str());
if (!file.isDirectory()) {
file.close();
SD.remove((char *)path.c_str());
return;
}
file.rewindDirectory();
while (true) {
File entry = file.openNextFile();
if (!entry) {
break;
}
String entryPath = path + "/" + entry.name();
if (entry.isDirectory()) {
entry.close();
deleteRecursive(entryPath);
} else {
entry.close();
SD.remove((char *)entryPath.c_str());
}
yield();
}
SD.rmdir((char *)path.c_str());
file.close();
}
void handleDelete() {
if (server.args() == 0) {
return returnFail("BAD ARGS");
}
String path = server.arg(0);
if (path == "/" || !SD.exists((char *)path.c_str())) {
returnFail("BAD PATH");
return;
}
deleteRecursive(path);
returnOK();
}
void handleCreate() {
if (server.args() == 0) {
return returnFail("BAD ARGS");
}
String path = server.arg(0);
if (path == "/" || SD.exists((char *)path.c_str())) {
returnFail("BAD PATH");
return;
}
if (path.indexOf('.') > 0) {
File file = SD.open((char *)path.c_str(), FILE_WRITE);
if (file) {
file.write((const char *)0);
file.close();
}
} else {
SD.mkdir((char *)path.c_str());
}
returnOK();
}
void printDirectory() {
if (!server.hasArg("dir")) {
return returnFail("BAD ARGS");
}
String path = server.arg("dir");
if (path != "/" && !SD.exists((char *)path.c_str())) {
return returnFail("BAD PATH");
}
File dir = SD.open((char *)path.c_str());
path.clear();
if (!dir.isDirectory()) {
dir.close();
return returnFail("NOT DIR");
}
dir.rewindDirectory();
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(200, "text/json", "");
WiFiClient client = server.client();
server.sendContent("[");
for (int cnt = 0; true; ++cnt) {
File entry = dir.openNextFile();
if (!entry) {
break;
}
String output;
if (cnt > 0) {
output = ',';
}
output += "{\"type\":\"";
output += (entry.isDirectory()) ? "dir" : "file";
output += "\",\"name\":\"";
output += entry.name();
output += "\"";
output += "}";
server.sendContent(output);
entry.close();
}
server.sendContent("]");
server.sendContent(""); // Terminate the HTTP chunked transmission with a 0-length chunk
dir.close();
}
void handleNotFound() {
if (hasSD && loadFromSdCard(server.uri())) {
return;
}
String message = "SDCARD Not Detected\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
DBG_OUTPUT_PORT.print(message);
}
void setup(void) {
DBG_OUTPUT_PORT.begin(115200);
DBG_OUTPUT_PORT.setDebugOutput(true);
DBG_OUTPUT_PORT.print("\n");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
DBG_OUTPUT_PORT.print("Connecting to ");
DBG_OUTPUT_PORT.println(ssid);
// Wait for connection
uint8_t i = 0;
while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds
delay(500);
}
if (i == 21) {
DBG_OUTPUT_PORT.print("Could not connect to");
DBG_OUTPUT_PORT.println(ssid);
while (1) {
delay(500);
}
}
DBG_OUTPUT_PORT.print("Connected! IP address: ");
DBG_OUTPUT_PORT.println(WiFi.localIP());
if (MDNS.begin(host)) {
MDNS.addService("http", "tcp", 80);
DBG_OUTPUT_PORT.println("MDNS responder started");
DBG_OUTPUT_PORT.print("You can now connect to http://");
DBG_OUTPUT_PORT.print(host);
DBG_OUTPUT_PORT.println(".local");
}
server.on("/list", HTTP_GET, printDirectory);
server.on("/edit", HTTP_DELETE, handleDelete);
server.on("/edit", HTTP_PUT, handleCreate);
server.on("/edit", HTTP_POST, []() {
returnOK();
}, handleFileUpload);
server.onNotFound(handleNotFound);
server.begin();
DBG_OUTPUT_PORT.println("HTTP server started");
if (SD.begin(SS)) {
DBG_OUTPUT_PORT.println("SD Card initialized.");
hasSD = true;
}
}
void loop(void) {
server.handleClient();
MDNS.update();
}
The code compiles without warnings and errors. Used environment:
Arduino IDE v 1.8.13
ESP8266 community edition v 2.6.3
windows machine
My guess is old ESP or Arduino libs - versions above.
The code is ok as a starter for own projects.
One starting tip:
Replace all Strings with char functionsor you will have stability problems later on (Heap fragmentation)
you have to remove "hasSD &&" from void handleNotFound function.
it worked for me.

MongoDB Atlas connection from mongoc (C) driver fails intermittently with 'No suitable servers found'

I'm using the MongoDB C driver (1.9.2) to connect to my Atlas Cluster (M5 using AWS).
My requests often succeeds, but I get this error about half the time. The longer I wait between requests, the more often the request succeeds.
I am always able to create a mongoc_client_t, but when the request fails, the drop, insert or read operation gets this error;
2019-12-30 23:10:50::dropCollection(): mongoc_collection_drop() failed code(13053)::
No suitable servers found: serverSelectionTimeoutMS expired: [Failed to receive length header from server. calling ismaster on 'xxxxx-shard-00-01-xxxxx.mongodb.net:27017'] [Failed to receive length header from server. calling ismaster on 'xxxxx-shard-00-00-xxxxx.mongodb.net:27017']
This is my (simplified) code;
I tried using a client pool, then switched to 'serverSelectionTryOnce=false' - they both get the error after timing out.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <mongoc.h>
#include <bson.h>
#include <bcon.h>
#define ERROR -1
#define GOOD 0
typedef struct _MongoContext
{
mongoc_uri_t* uri;
mongoc_client_t* client;
mongoc_database_t* database;
mongoc_collection_t* collection;
bson_error_t error;
char* uriStr;
} MongoContext;
static const char* DEFAULT_URI = "mongodb+srv://<user>:<psswd>#<host>.mongodb.net/test?retryWrites=true&w=majority&serverSelectionTryOnce=false";
int getMongoContext(MongoContext* mctx, const char* dbname, const char* collname)
{
bson_error_t error;
mctx->uriStr = strdup(DEFAULT_URI);
mctx->uri = mongoc_uri_new_with_error(mctx->uriStr, &error);
if(!mctx->uri) {
fprintf(stderr, "getMongoContext(): Unable to parse URI(%s)\n(%s)", mctx->uriStr, error.message);
return ERROR;
}
// mongoc_client_pool_t *pool = mongoc_client_pool_new(mctx->uri);
// mongoc_client_pool_set_appname(pool, "my-mongo");
// mongoc_client_pool_set_error_api(pool, MONGOC_ERROR_API_VERSION_2);
// mctx->client = mongoc_client_pool_pop(pool);
mctx->client = mongoc_client_new_from_uri(mctx->uri);
if(!mctx->client) {
fprintf(stderr, "getMongoContext(): mongoc_client_new_from_uri() failed(%s)", error.message);
return ERROR;
}
mongoc_client_set_appname(mctx->client, "my-mongo");
mctx->database = mongoc_client_get_database(mctx->client, dbname);
if(mctx->database == NULL) {
fprintf(stderr, "getMongoContext(): invalid database(%s)", dbname);
return ERROR;
}
mctx->collection = mongoc_client_get_collection(mctx->client, dbname, collname);
if(mctx->collection == NULL) {
fprintf(stderr, "getMongoContext(): invalid collection(%s)", collname);
}
char* ptr = strchr(mctx->uriStr, '#');
fprintf(stderr, "getMongoContext(): connection made for host(%s), db(%s), collection(%s)\n", (ptr+1), dbname, collname);
return GOOD;
}
void closeMongoContext(MongoContext* mctx)
{
mongoc_collection_destroy(mctx->collection);
mongoc_database_destroy(mctx->database);
mongoc_uri_destroy(mctx->uri);
mongoc_client_destroy(mctx->client);
mongoc_cleanup();
free(mctx->uriStr);
}
/**
* read the collection in the given MongoContext
*/
int readCollection(MongoContext* mctx)
{
mongoc_cursor_t* cursor;
const bson_t* doc;
char* str;
bson_t* query = bson_new();
cursor = mongoc_collection_find_with_opts(mctx->collection, query, NULL, NULL);
if(cursor == NULL) {
fprintf(stderr, "readCollection(): Unable to retrieve a cursor for collection(%s)",
mongoc_collection_get_name(mctx->collection));
return ERROR;
}
while(mongoc_cursor_next(cursor, &doc)) {
str = bson_as_canonical_extended_json(doc, NULL);
printf("%s\n", str);
bson_free(str);
}
bson_destroy(query);
mongoc_cursor_destroy(cursor);
return GOOD;
}
int insertIntoCollection(MongoContext* mctx, const char* jsondata)
{
bson_t* doc;
bson_t reply;
bson_error_t error;
doc = bson_new_from_json((const uint8_t*)jsondata, -1, &error);
if(!doc) {
fprintf(stderr, "insertIntoCollection(): bson_new_from_json() failed (%s)\n", error.message);
return ERROR;
}
fprintf(stderr, "insertIntoCollection(): insert into collection(%s)\n", mongoc_collection_get_name(mctx->collection));
bool b = mongoc_collection_insert_one(mctx->collection, doc, NULL, &reply, &error);
if(!b) {
fprintf(stderr, "insertIntoCollection(): mongoc_collection_insert_one() failed (%s)\n", error.message);
}
bson_destroy(doc);
return GOOD;
}
int dropCollection(MongoContext* mctx)
{
bson_error_t error;
bool rval = mongoc_collection_drop(mctx->collection, &error);
if(!rval) {
fprintf(stderr, "dropCollection(): mongoc_collection_drop() failed code(%d)::%s", error.code, error.message);
fprintf(stderr, "dropCollection(): mongoc_collection_drop() failed on collection(%s) for(%s)",
mongoc_collection_get_name(mctx->collection), mctx->uriStr);
return (error.code == 26) ? GOOD : ERROR;
}
return GOOD;
}
int main(int argc, char* argv[])
{
mongoc_init();
MongoContext mctx = {0};
getMongoContext(&mctx, "my-db", "my-collection");
if(dropCollection(&mctx) == ERROR) {
exit(1);
}
printf("collection dropped...\n");
if(insertIntoCollection(&mctx, "{ \"hello\" : \"world\" }") == ERROR) {
exit(1);
}
printf("inserted into collection...\n");
if(readCollection(&mctx) == ERROR) {
exit(1);
}
closeMongoContext(&mctx);
}
In my case it was a version issue. I had to upgrade my C driver version to be compatible with the server.

Open file Error permission denied on macOS

hi I use bridging header include a hpp
but always output "Error permission denied"
My Derived Data is relative
I tried to key "chmod -R 777 ./" in Debug-iPhonesimulator
show the code:
bool CheckPath()
{
FILE *pfile = fopen("./__viewtest.txt","w");
if(pfile){
fclose(pfile);
return true;
}
printf("Error %s\n",strerror(errno));
return false;
}
it is always output "Error permission denied"
thanks a lot
I solved it
#include <unistd.h>
#include<iostream>
std::string GetCurrentWorkingDir( void ) {
char buff[FILENAME_MAX];
getcwd( buff, FILENAME_MAX );
std::string current_working_dir(buff);
return current_working_dir;
}
bool CheckPath()
{
std::string sPath = GetCurrentWorkingDir();
sPath += "Users/My/Desktop/WorkSpace/View/DerivedData/View/Build/Products/Debug-iphonesimulator/__viewtest.txt";
FILE *pfile = fopen(sPath.c_str(),"w");
if(pfile){
fclose(pfile);
return true;
}
printf(" %s, Path %s\n",strerror(errno), GetCurrentWorkingDir().c_str());
return false;
}

What is the difference between mono_assembly_open and mono_image_open_from_data_with_name?

I want load a .net assembly module, when i use mono_assembly_open is fine. But when i use mono_image_open_from_data_with_name, it's not work, can't traverse the module I want to load.
void *load_image_from_file(const char *full_file_path)
{
if (full_file_path == NULL)
{
return NULL;
}
if (!PathFileExistsA(full_file_path))
{
return NULL;
}
HANDLE file = CreateFileA(full_file_path, FILE_READ_ACCESS, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
{
return NULL;
}
DWORD file_size = GetFileSize(file, NULL);
if (file_size == INVALID_FILE_SIZE)
{
CloseHandle(file);
return NULL;
}
byte *file_data = reinterpret_cast<byte *>(malloc(file_size));
if (file_data == NULL)
{
CloseHandle(file);
return NULL;
}
DWORD read = 0;
ReadFile(file, file_data, file_size, &read, NULL);
if (file_size != read)
{
free(file_data);
CloseHandle(file);
return NULL;
}
MonoImageOpenStatus status;
void *image = mono_image_open_from_data_with_name(reinterpret_cast<char *>(file_data), file_size, MONO_TRUE, &status, MONO_FALSE, full_file_path);
free(file_data);
return image;
}
After call mono_image_open_from_data_with_name, you should call mono_assembly_load_from_full.
if (status != MONO_IMAGE_OK)
{
RPCS_ERROR("Open Image Failed %s", full_file_path);
return NULL;
}
void *assembly = mono_image_get_assembly_(image);
if (assembly == NULL)
{
assembly = mono_assembly_load_from_full_(image, full_file_path, &status, MONO_FALSE);
}
mono_image_close_(image);
return assembly;

Debug Assertion Failed while using ActiveX control

Am newbie to this forum & MFC... Am getting Debug Assertion Failed
while using ActiveX control. Please guide me on this..My code looks
like this:
//CMyProjectDlg.h
class CMyProjectDlg: public CDialog
{
public:
CMyProject(CWnd* pParent = NULL);
enum { IDD = IDD_CMYPROJECT_DIALOG };
CMiDocView m_MIDOCtrl;
//Here CMiDocView is the class defined in other header file
protected:
BOOL bReadOCRByMODIAXCtrl(CString csFilePath, CString &csText);
};
//CMyProjectDlg.cpp
BOOL CMyProjectDlg::bReadOCRByMODIAXCtrl(CString csFilePath, CString &csText)
{
BOOL bRet = TRUE;
HRESULT hr = 0;
csText.Empty();
IUnknown *pVal = NULL;
IDocument *IDobj = NULL;
ILayout *ILayout = NULL;
IImages *IImages = NULL;
IImage *IImage = NULL;
IWords *IWords = NULL;
IWord *IWord = NULL;
try{
pVal = (IUnknown *) m_MIDOCtrl.GetDocument();
//After Executing this statement, I used to Debug Assertion failed...
if ( pVal != NULL )
{
hr = pVal->QueryInterface(IID_IDocument,(void**) &IDobj);
if ( SUCCEEDED(hr) )
{
hr = IDobj->OCR(miLANG_SYSDEFAULT,1,1);
if ( SUCCEEDED(hr) )
{
IDobj->get_Images(&IImages);
long iImageCount=0;
IImages->get_Count(&iImageCount);
for ( int img =0; img<iImageCount;img++)
{
IImages->get_Item(img,(IDispatch**)&IImage);
IImage->get_Layout(&ILayout);
long numWord=0;
ILayout->get_NumWords(&numWord);
ILayout->get_Words(&IWords);
IWords->get_Count(&numWord);
for ( long i=0; i<numWord;i++)
{
IWords->get_Item(i,(IDispatch**)&IWord);
CString csTemp;
BSTR result;
IWord->get_Text(&result);
char buf[256];
sprintf(buf,"%S",result);
csTemp.Format("%s",buf);
csText += csTemp;
csText +=" ";
//Release all objects
IWord->Release();
IWords->Release();
ILayout->Release();
IImage->Release();
}
IImages->Release();
} else {
bRet = FALSE;
}
} else {
bRet = FALSE;
}
IDobj->Close(0);
IDobj->Release();
pVal->Release();
} else {
bRet = FALSE;
}
pVal = NULL;
IDobj = NULL;
ILayout = NULL;
IImages = NULL;
IImage = NULL;
IWords = NULL;
IWord = NULL;
}
catch(...)
{
}
return bRet;
}
void CMyProjectDlg::OnBnClickedOCR()
{
//Dynamic object creation:
CMyProjectDlg *ob = new CMyProjectDlg;
((CMiDocView *)GetDlgItem(IDC_MIDOCVIEW1))->SetFileName("E:\\aaa.tiff");
//IDC_MIDOCVIEW is the ID for the ActiveX control..
((CMiDocView *) GetDlgItem( IDC_MIDOCVIEW1 ))->SetFitMode(1);
CString cs;
ob->bReadOCRByMODIAXCtrl("E:\\aaa.tiff",cs);
//Release the memory:
delete ob;
}
After clicking OCR button, I used to get Debug assertion failed on the line:
pVal = (IUnknown *) m_MIDOCtrl.GetDocument();
When i press retry, the control goes to
ASSERT(m_pCtrlsite != NULL ) in winocc.cpp
while Debugging i came to know that {CMIDOCView hWnd = 0x0000000}.
Please can anyone suggest me what am doing wrong here ??
Thank you all..