What is the difference between mono_assembly_open and mono_image_open_from_data_with_name? - unity3d

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;

Related

In socket programming exe file memory increasing gradually and also socket remain open

When received sting from multiple client at time some socket remain open so created mis file size increasing gradually so at time exe file become 2 GB from 35 kb so how can i reduce open sockect
private void Server_Load(object sender, EventArgs e)
{
try
{
this.tcpListener = new TcpListener(IPAddress.Any, port);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
catch (Exception ex)
{ }
finally
{
if (this.tcpListener != null)
{
this.tcpListener.Stop();
}
}
}
Mangae Client request by server continuously from load method
private void ListenForClients()
{
TcpClient client = null;
try
{
this.tcpListener.Start();
while (true)
{
client = this.tcpListener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClientComm),
client);
}
}
catch (Exception ex)
{
LogHelperISPL.Logger.Info("ListenForClients: " + ex.Message);
this.tcpListener.Stop();
}
finally
{
if(this.tcpListener != null)
{
this.tcpListener.Stop();
}
if (client != null)
{
client.Close();
}
}
}
Take data from client and insert into table and mange pass tcpclient and networkstream with close connection
private void HandleClientComm(object client)
{
TcpClient tcpClient = null;
NetworkStream clientStream = null;
try
{
tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
string InsertedRecord = string.Empty;
byte[] messageBytes = new byte[4096];
int bytesRead;
bool end = false;
while (!end)
{
bytesRead = 0;
try
{
if (clientStream != null)
{
bytesRead = clientStream.Read(messageBytes, 0,
messageBytes.Length);
}
}
catch (SocketException ex)
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
break;
}
catch (Exception ex)
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
break;
}
if (bytesRead <= 0)
{
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
string Datareceived = encoder.GetString(messageBytes, 0, bytesRead);
if (!string.IsNullOrEmpty(Datareceived))
{
string[] Multistrings = Datareceived.Split('!');
for (int i = 0; i < Multistrings.Length; i++)
{
if (!string.IsNullOrEmpty(Multistrings[i]))
{
if (Multistrings[i].Length >= 90)
{
InsertedRecord = InsertRawData(Multistrings[i]);
}
else
{
InsertedRecord =
InsertRawDataGarbage(Multistrings[i]);
}
}
}
}
}
}
catch (Exception ex)
{
LogHelperISPL.Logger.Info("While loop: " + ex.Message);
}
finally
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
}
}

Data is null when capturing photo with camera (Nexus 7)

On some phones when I use the camera to load a new photo into an ImageView, the data I get back is null. On other phones it works fine. It works on most Kitkat phone's, but not on a Nexus 7 (4.4.2) and who know's on what else.
Works on HTC M8 (5.0.1), HTC Desire X (4.1.1), Samsung Galaxy S4 (4.4.2), Samsung Galaxy S5 (5.0).
I share only the code for capturing images on Kitkat, but I handle them differently when I am working with bitmap conversions and upload to server.
btn_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("INTENT0", "PICK_FROM_CAMERA_KITKAT");
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentPicture,PICK_FROM_CAMERA_KITKAT);
dialog_newimg.dismiss();
}
});
#SuppressLint("NewApi")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA_KITKAT:
if (data != null) {
Log.i("data.getData()", data.getData() + ""); //null
[...many things..]
}
...
}
}
I read some similar questions and I highlight that I don't use EXTRA_OUTPUT in any way.
Any ideas?
I did something like this. Actually the key is to handle the Uri differently:
if (data.getData() == null) {
selectedImageUri = Uri.fromFile(imageFileForCamera_);
} else {
selectedImageUri = data.getData();
}
After this it's also important to handle the path differently with the helper functions getRealPathFromURI() for above Kitkat and getPath() for below Kitkat.
I post my whole code here as a reference for others. This code has been working for 2 months now in all kinds of devices of hundreds of users without force closes.
case PICK_FROM_CAMERA_COMPLETE:
if(resultCode == RESULT_OK) {
if (data != null) {
if (data.getData() == null) {
selectedImageUri = Uri.fromFile(imageFileForCamera_);
} else {
selectedImageUri = data.getData();
}
} else {
selectedImageUri = Uri.fromFile(imageFileForCamera_);
}
complete_dialog.filename = getRealPathFromURI(selectedImageUri);
Bitmap bitmapSelectedImage;
try {
bitmapSelectedImage = getSampleBitmapFromFile(getRealPathFromURI(selectedImageUri), 400, 400);
ExifInterface exifInterface = new ExifInterface(getRealPathFromURI(selectedImageUri));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(orientation);
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f) {
matrix.preRotate(rotationInDegrees);
bitmapSelectedImage = Bitmap.createBitmap(bitmapSelectedImage, 0, 0, bitmapSelectedImage.getWidth(), bitmapSelectedImage.getHeight(), matrix, true);
}
Bitmap d = new BitmapDrawable(getApplicationContext().getResources(), bitmapSelectedImage).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
complete_dialog.iv_bucket2.setImageBitmap(scaled);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if(resultCode == RESULT_CANCELED){
//DELETE FILE THAT WE CREATED FROM CAMERA
}
break;
case PICK_FROM_CAMERA_COMPLETE_KITKAT:
if(resultCode == RESULT_OK) {
if (data != null) {
if (data.getData() == null) {
selectedImageUri = Uri.fromFile(imageFileForCamera_);
} else {
selectedImageUri = data.getData();
}
} else {
selectedImageUri = Uri.fromFile(imageFileForCamera_);
}
Bitmap bitmapSelectedImage2;
try {
bitmapSelectedImage2 = getSampleBitmapFromFile(getPath(BucketProfileActivity.this, selectedImageUri), 400, 400);
ExifInterface exifInterface = new ExifInterface(getPath(BucketProfileActivity.this, selectedImageUri));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(orientation);
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f) {
matrix.preRotate(rotationInDegrees);
bitmapSelectedImage2 = Bitmap.createBitmap(bitmapSelectedImage2, 0, 0, bitmapSelectedImage2.getWidth(), bitmapSelectedImage2.getHeight(), matrix, true);
}
Bitmap d = new BitmapDrawable(getApplicationContext().getResources(), bitmapSelectedImage2).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
complete_dialog.iv_bucket2.setImageBitmap(scaled);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if(resultCode == RESULT_CANCELED){
//DELETE FILE THAT WE CREATED FROM CAMERA
}
break;
case LOAD_FROM_GALLERY_COMPLETE: //before KitKat
if(resultCode == RESULT_OK) {
if (data != null) {
complete_dialog.show();
Uri imageuri = data.getData();
complete_dialog.filename = getRealPathFromURI(imageuri);
Bitmap bitmapSelectedImage3;
try {
bitmapSelectedImage3 = getSampleBitmapFromFile(getRealPathFromURI(imageuri), 400, 400);
ExifInterface exifInterface = new ExifInterface(getRealPathFromURI(imageuri));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(orientation);
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f) {
matrix.preRotate(rotationInDegrees);
bitmapSelectedImage3 = Bitmap.createBitmap(bitmapSelectedImage3, 0, 0, bitmapSelectedImage3.getWidth(), bitmapSelectedImage3.getHeight(), matrix, true);
}
Bitmap d = new BitmapDrawable(getApplicationContext().getResources(), bitmapSelectedImage3).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
complete_dialog.iv_bucket2.setImageBitmap(scaled);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if(resultCode == RESULT_CANCELED){
//DELETE FILE THAT WE CREATED FROM CAMERA
}
break;
case LOAD_FROM_GALLERY_KITKAT_COMPLETE: //after KitKat if(resultCode == RESULT_OK) {
if (data != null) {
complete_dialog.show();
Uri imageuri = data.getData();
complete_dialog.filename = getPath(BucketProfileActivity.this, imageuri);
Bitmap bitmapSelectedImage4;
try {
bitmapSelectedImage4 = getSampleBitmapFromFile(getPath(BucketProfileActivity.this, imageuri), 400, 400);
ExifInterface exifInterface = new ExifInterface(getPath(BucketProfileActivity.this, imageuri));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(orientation);
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f) {
matrix.preRotate(rotationInDegrees);
bitmapSelectedImage4 = Bitmap.createBitmap(bitmapSelectedImage4, 0, 0, bitmapSelectedImage4.getWidth(), bitmapSelectedImage4.getHeight(), matrix, true);
}
Bitmap d = new BitmapDrawable(getApplicationContext().getResources(), bitmapSelectedImage4).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
complete_dialog.iv_bucket2.setImageBitmap(scaled);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if(resultCode == RESULT_CANCELED){
//DELETE FILE THAT WE CREATED FROM CAMERA
}
break;
Helper functions:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, "", null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//Log.i("IDX", idx + "");
// Log.i("RESULT", cursor.getString(idx) + "");
result = cursor.getString(idx); //force close here
cursor.close();
}
return result;
}
#TargetApi(Build.VERSION_CODES.KITKAT) #SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

Eclipse Plugin Creating a IJavaLineBreakpoint programmatically does not show method info in Breakpoints view

I'm creating a Eclipse plugin and I'm trying to create JavaLineBreakpoint using JDIDebugModel.
However, when a line breakpoint is created from the Java editor, it displays the Class name, the line number and the method name as the following image:
When the line breakpoint is created in the plugin the method name is replaced by the class name as follows:
The following is the code used to create the breakpoint.
Thank you.
IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints();
if (breakpoints.length == 0) {
return null;
}
IJavaLineBreakpoint oldBreakpoint = null;
for (int i = 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint = breakpoints[i];
if (breakpoint instanceof IJavaLineBreakpoint) {
oldBreakpoint = (IJavaLineBreakpoint)breakpoint;
break;
}
}
if (oldBreakpoint != null) {
Map newAttrMap = null;
IResource resource = null;
try {
IMarker marker = oldBreakpoint.getMarker();
if (marker != null && marker.exists()) {
newAttrMap = marker.getAttributes();
resource = marker.getResource();
}
} catch (CoreException ce) {
Activator.logError("SinfoniaCloudBreakpointItem - Contructor - Marker attributes not found", ce);
}
int lineNumber = -1;
try {
lineNumber = (Integer)newAttrMap.get(IMarker.LINE_NUMBER);
} catch (ClassCastException cce) {
} catch (NullPointerException ne) {
}
try {
JDIDebugModel.createLineBreakpoint(
resource,
oldBreakpoint.getTypeName(),
lineNumber, -1, -1, 0, true, newAttrMap);
oldBreakpoint.delete();
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

contacts insert ,app died ,no save state

this is log:
08-28 13:50:47.648: A/libc(1010): ### ABORTING: INVALID HEAP ADDRESS IN dlfree addr=0x2a26bc90
08-28 13:50:47.648: A/libc(1010): Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 1020 (FinalizerDaemon)
08-28 13:50:48.698: W/ActivityManager(149): Scheduling restart of crashed service com.android.KnowingLife/.PushNotification.NotificationService in 5000ms
08-28 13:50:48.698: W/ActivityManager(149): Force removing ActivityRecord{412a2c70 com.android.KnowingLife/.PhoneSynActivity}: app died, no saved state
08-28 13:50:48.807: W/GpsLocationProvider(149): Unneeded remove listener for uid 1000
08-28 13:50:49.257: E/Trace(1064): error opening trace file: No such file or directory (2)
08-28 13:50:50.017: W/GpsLocationProvider(149): Duplicate add listener for uid 10044
08-28 13:50:52.827: W/InputMethodManagerService(149): Got RemoteException sending setActive(false) notification to pid 1010 uid 10044
I run it in my emulator( version 4.1),and I am bulk inserting contacts to local .It works well usual,but I got 600 more contacts to
insert to local ,it doesn't work when insert to about 6%.I don't know
how to show it to you ,this is my code ,look this, you will see the
problem,thank
/**
* insert
*/
class InsertContactsTask extends AsyncTask<Void, Integer, Integer> {
String detail;
public InsertContactsTask(String detail) {
this.detail = detail;
}
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(PROGRESS_DIALOG);
}
#Override
protected Integer doInBackground(Void... params) {
String[] itemRecord = detail.split(ParseData.getInstance()
.getRecordSplitFalg(), -1);
int count = itemRecord.length;
wait_Dialog.setMax(count);
ArrayList<ContentProviderOperation> contentOper = null;
contentOper = new ArrayList<ContentProviderOperation>();
for (int i = 0; i < itemRecord.length; i++) {
int rawContactInsertIndex = contentOper.size();
String[] item = null;
try {
item = itemRecord[i].split(ParseData.getInstance()
.getFiledSplitFlag(), -1);
contentOper.add(ContentProviderOperation
.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
contentOper.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, item[0])
.build());
for (int j = 1; j < item.length; j++) {
if (item[j].startsWith("1")) {
String phoneType = item[j].substring(1, 2);
int iType;
String label = null;
if (phoneType.compareToIgnoreCase("a") >= 0)
iType = phoneType.compareToIgnoreCase("a") + 10;
else
iType = Integer.parseInt(phoneType);
if (iType == 0)
label = item[j + 1];
contentOper
.add(ContentProviderOperation
.newInsert(
android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER,
item[j].substring(2))
// "data1"
.withValue(Phone.TYPE, iType)
.withValue(Phone.LABEL, label)
.build());
if (iType == 0)
j++;
} else {
String emailType = item[j].substring(1, 2);
int iEmailType = Integer.parseInt(emailType);
String emailLabel = null;
if (iEmailType == 0)
emailLabel = item[j + 1];
contentOper
.add(ContentProviderOperation
.newInsert(
android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
Email.CONTENT_ITEM_TYPE)
.withValue(Email.DATA,
item[j].substring(2))
.withValue(Email.TYPE, iEmailType)
.withValue(Email.LABEL, emailLabel)
.build());
if (iEmailType == 0)
j++;
}
}
int iUpdate = i + 1;
if (iUpdate % 20 == 0 || iUpdate == itemRecord.length) {
try {
#SuppressWarnings("unused")
ContentProviderResult[] results = PhoneSynActivity.this
.getContentResolver().applyBatch(
ContactsContract.AUTHORITY,
contentOper);
contentOper.clear();
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
publishProgress(i);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return count;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
wait_Dialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer count) {
super.onPostExecute(count);
wait_Dialog.dismiss();
txt_count.setText( count+ "");
Toast.makeText(PhoneSynActivity.this,
R.string.string_download_suc, Toast.LENGTH_LONG).show();
}
}

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..