dao property from vb to mfc - mfc

i have implemented vb functionality in c++ i have replace below logic in c++ but it is giving issue :
i have to convert from VB to c++ and the code in c++ is crashing when getting property.
Original VB code:
For Each loTDef In aoDBUser.TableDefs
Set loProp = Nothing
On Error Resume Next
Set loProp = loTDef.Properties("Description")
If Not loProp Is Nothing Then
If loProp.Value = TEMP_TABLE Then
End If
End If
Next
New C++ code:
CString test::Property()
{
//
// OVERVIEW:
// Get the value for the given Custom Property
//
DAOProperties *pColProp = NULL;
DAOProperty *pProp = NULL;
CDaoDatabase cDBase;
cDBase.Open(CV_GetUserDatabasePath(_T("TEST.mdb")));
CString strDbVer;
DAOProperties* pPrp = 0;
DAOProperty* pRev = 0;
try
{
if ( !cDBase.IsOpen() )
return(_T(""));
DAO_CHECK(cDBase.m_pDAODatabase->get_Properties(&pPrp));
if ( pPrp != 0 )
{
COleVariant varRevVal;
COleVariant varName(_T("Description"), VT_BSTRT);
DAO_CHECK(pPrp->get_Item(varName, &pRev));//crashing going to catch
if (pRev != 0)
{
DAO_CHECK(pRev->get_Value(&varRevVal));
pRev->Release();
pRev = 0;
}
pPrp->Release();
pPrp = 0;
strDbVer = V_BSTRT(&varRevVal);
}
}
catch (...)
{
}
cDBase.Close();
}
some how it is crashing in DAO_CHECK(pPrp->get_Item(varName, &pRev));
But I cannot figure out why this occurs.

Related

If else not working in android inside for and while loop

public void LoadRoutine() {
TableRow tbrow0 = new TableRow(getActivity());
//String[] mStrings = new String[9];
tbrow0.setBackgroundColor(Color.parseColor("#FFFFFF"));
tbrow0.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (String c : TimeSlotSummer) {
TextView tv0 = new TextView(getActivity());
tv0.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv0.setGravity(Gravity.CENTER);
tv0.setTextSize(12);
tv0.setHeight(40);
tv0.setWidth(76);
tv0.setBackgroundColor(Color.parseColor("#FFFFFF"));
tv0.setTextColor(Color.parseColor("#000000"));
tv0.setPadding(1, 1, 1, 1);
tv0.setText(c);
tv0.setBackgroundColor(R.id.tableRowid);
tbrow0.addView(tv0);
}
tableLayout.addView(tbrow0);
String dept = GlobalClass.userDepartment;
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getActivity());
databaseAccess.Open();
String faccode = GlobalClass.faculty_code;
Cursor cRoutine = databaseAccess.getRoutine("Sunday",dept);
if (cRoutine.getCount() == 0) {
Toast.makeText(getActivity(),"No Data in Table",Toast.LENGTH_LONG).show();
}
else{
while (cRoutine.moveToNext())
{
String[] mStrings = new String[10];
mStrings[0] = cRoutine.getString(2);
mStrings[1] = cRoutine.getString(4);
mStrings[2] = cRoutine.getString(5);
mStrings[3] = cRoutine.getString(6);
mStrings[4] = cRoutine.getString(7);
mStrings[5] = cRoutine.getString(8);
mStrings[6] = cRoutine.getString(9);
mStrings[7] = cRoutine.getString(10);
mStrings[8] = cRoutine.getString(11);
TableRow tbrow1 = new TableRow(getActivity());
tbrow1.setBackgroundColor(Color.parseColor("#FFFFFF"));
tbrow1.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (String cls:mStrings) {
TextView tv1 = new TextView(getActivity());
tv1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv1.setGravity(Gravity.CENTER);
tv1.setTextSize(12);
tv1.setWidth(75);
tv1.setHeight(37);
tv1.setBackgroundColor(Color.parseColor("#FFFFFF"));
tv1.setPadding(1, 1, 1, 1);
tv1.setBackgroundColor(R.id.tableRowid);
tv1.setText(cls);
tv1.setTextColor(Color.parseColor("#FF0000"));
if(cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));
tbrow1.addView(tv1);
}
tableLayout.addView(tbrow1);
}
}
}
Inside the last for loop, without if-else, it works properly, but with if-else it is not working, that is apps shut down and mobile restart again.
Any one help me, I want to check some substring, then text color will change, otherwise color normal.
It would help if you posted a stack trace but if the crash occurs here:
if(cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));
The only explanation is that you get a NullPointerException on cls because tv1 is obviously not null if it did not crash before.
Use this code instead:
if(cls != null && cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));

Why is this Haxe try-catch block still crashing, when using Release mode for C++ target

I have a HaxeFlixel project, that is working OK in Debug mode for misc targets, including flash, neko and windows. But Targeting Windows in Release mode, I'm having an unexpected crash, and surprisingly it's happening inside a try-catch block. Here's the crashing function:
/**
* Will safely scan a parent node's children, search for a child by name, and return it's text.
* #param parent an Fast object that is parent of the `nodeNamed` node
* #param nodeName the node's name or a comma-separated path to the child (will scan recursively)
* #return node's text as String, or null if child is not there
*/
public static function getNodeText(parent:Fast, nodeName:String):String {
try {
var _node : Fast = getNodeNamed(parent, nodeName);
//if (_node == null)
// return null;
// next line will crash if _node is null
var it :Iterator<Xml> = _node.x.iterator();
if ( it == null || !it.hasNext() )
return null;
var v = it.next();
var n = it.next();
if( n != null ) {
if( v.nodeType == Xml.PCData && n.nodeType == Xml.CData && StringTools.trim(v.nodeValue) == "" ) {
var n2 = it.next();
if( n2 == null || (n2.nodeType == Xml.PCData && StringTools.trim(n2.nodeValue) == "" && it.next() == null) )
return n.nodeValue;
}
//does not only have data (has children)
return null;
}
if( v.nodeType != Xml.PCData && v.nodeType != Xml.CData )
//does not have data";
return null;
return v.nodeValue;
}catch (err:Dynamic) {
trace("Failed parsing node Text [" + nodeName+"] " + err );
return null;
}
}
By enabling if (_node == null) return null; line, It's working safely again. By catching errors as Dynamic I thought I was supposed to catch every possible error type! Why is this happening? And why is it appearing in release mode?
My IDE is FlashDevelop, and I'm using HaxeFlixel 3.3.6, lime 0.9.7 and openFL 1.4.0, if that makes any difference
EDIT: I suspect this has to do with how the translated C++ code missed the Dynamic Exception. The equivalent generated C++ code is:
STATIC_HX_DEFINE_DYNAMIC_FUNC2(BaxXML_obj,_getNodeNamed,return )
::String BaxXML_obj::getNodeText( ::haxe::xml::Fast parent,::String nodeName){
HX_STACK_FRAME("bax.utils.BaxXML","getNodeText",0x4a152f07,"bax.utils.BaxXML.getNodeText","bax/utils/BaxXML.hx",56,0xf6e2d3cc)
HX_STACK_ARG(parent,"parent")
HX_STACK_ARG(nodeName,"nodeName")
HX_STACK_LINE(56)
try
{
HX_STACK_CATCHABLE(Dynamic, 0);
{
HX_STACK_LINE(57)
::haxe::xml::Fast _node = ::bax::utils::BaxXML_obj::getNodeNamed(parent,nodeName); HX_STACK_VAR(_node,"_node");
HX_STACK_LINE(63)
Dynamic it = _node->x->iterator(); HX_STACK_VAR(it,"it");
// ... Let's skip the irrelevant code
}
catch(Dynamic __e){
{
HX_STACK_BEGIN_CATCH
Dynamic err = __e;{
HX_STACK_LINE(82)
::String _g5 = ::Std_obj::string(err); HX_STACK_VAR(_g5,"_g5");
HX_STACK_LINE(82)
::String _g6 = (((HX_CSTRING("Failed parsing node Text [") + nodeName) + HX_CSTRING("] ")) + _g5); HX_STACK_VAR(_g6,"_g6");
HX_STACK_LINE(82)
::haxe::Log_obj::trace(_g6,hx::SourceInfo(HX_CSTRING("BaxXML.hx"),82,HX_CSTRING("bax.utils.BaxXML"),HX_CSTRING("getNodeText")));
HX_STACK_LINE(83)
return null();
}
}
}
HX_STACK_LINE(56)
return null();
}
What haxedefs do you have defined?
Adding these to your project.xml might help:
<haxedef name="HXCPP_CHECK_POINTER"/> <!--makes null references cause errors-->
<haxedef name="HXCPP_STACK_LINE" /> <!--if you want line numbers-->
<haxedef name="HXCPP_STACK_TRACE"/> <!--if you want stack traces-->
You might also try the crashdumper library:
https://github.com/larsiusprime/crashdumper
(Crashdumper will turn on HXCPP_CHECK_POINTER by default as part of it's include.xml, and will set up hooks for both hxcpp's errors and openfl/lime's uncaught error events)
I guess this boils down to how C++ handles null-pointer Exceptions. It doesn't!
More info here or here
That seems odd, some questions that may help solving it.
It looks like you are doing quite some assumptions on how the xml looks (doing some manual it.next()), why is that?
Why are you using this big-ass try-catch block?
How does getNodeNamed look, it seems it can return null.
Do you have an example xml to test with?

Marshal error when RegisterStreamReadCallback

I'm using C# to call methods from an dll file to record video.
This is the Marshal methods file
http://pastebin.com/YrVvBfZ9
This is my CameraUtilities file
http://pastebin.com/0AZNtnhk
This is my camera file
http://pastebin.com/ZE3HD1zq
When I call StartRecord method (in camera file) to start Record video.
public void StartRecord()
{
if (this.ListCameras != null)
{
bool bRes = true;
try
{
int tmpError = -1;
m_tmpContext = new IntPtr();
m_handle = new GCHandle();
m_callBackChannels = new ulong[m_ListCameras.Length];
for (int i = 0; i < m_ListCameras.Length; i++)
{
m_callBackChannels[i] = 10;
cameraCurrentIndex = 0;
IntPtr channelHandle = T1800.T18_ChannelOpen(cameraCurrentIndex);
m_ListCameras[cameraCurrentIndex].ChannelHandle = channelHandle;
T1800.T18_CaptureIFrame(m_ListCameras[i].ChannelHandle);
m_ListCameras[i].BeginRecord();
if (AllowRecordVideo)
{
m_del = new T1800.STREAM_READ_CALLBACK(StreamReadCallBack);
m_tmpContext = m_ListCameras[i].ChannelHandle;
tmpError = T1800.T18_RegisterStreamReadCallback(m_del, ref m_tmpContext);
}
}
if (tmpError == -1) bRes = false;
}
catch (Exception ex)
{
Log.Logger.Error(ex);
bRes = false;
}
}
}
It throw an exception
- System.Runtime.InteropServices.MarshalDirectiveException: Invalid PInvoke calling convention.
Thiscall requires that the first parameter is present and can be enregistered.
at System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegateInternal(Delegate d)
at System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(Delegate d)
at TH.Parking.Wrapper.HBCamera.T1800.dll_T18_RegisterStreamReadCallback(STREAM_READ_CALLBACK STREAM_READ_CALLBACK, IntPtr& context)
at TH.Parking.Wrapper.HBCamera.CameraUtilities.StartRecord() in d:\TH.Parking\TH.Parking\Wrapper\HBCamera\CameraUtilities.cs:line 93
I can't find any reason for this error. Can somebody help me to fix this.
I think the callback you pass to create the STREAM_READ_CALLBACK object should be static. Otherwise, the thispointer is lost during the marshalling.
Instead of:
private int StreamReadCallBack(ulong channelHandle, IntPtr context)
{
...
}
try:
private static int StreamReadCallBack(ulong channelHandle, IntPtr context)
{
...
}
And you'll need to somehow put your instance of CameraUtility into the context parameter.

Segmentation fault occurs only under release configuration

For some odd reason, my application likes to break on me when I switch to release and run it outside of my debugger. Here's what works for me, and here's what doesn't
(Qt Creator is the IDE)
Debugging with debug configuration - ok
Running with debug configuration - ok
Debugging with release configuration - ok
Running with release configuration - application crash
My UI is one project, and the core for some stuff as a separate dependency. On Windows (compiling with MSVCC), I hit a menu button, which eventually calls down to a function. In that function, the app breaks on adding a new element to a vector. e.g:
str *x = new str();
str *y = new str();
/* ...set some of x & y's members... */
vector.push_back(x); // works fine
vector.push_back(y); // causes crash
If I comment out the line vector.push_back(y);, the app continues no problem until the app leaves the event scope (i.e. the end of OnMenuButtonClick). On OS X, it's similar to the issue of adding an element to a vector, except I have:
std::vector<foo *> SomeFunction()
{
std::vector<foo *> returningVector;
/* do stuff */
std::vector<foo *> goo = GetFooObjects();
for (int i = 0; i < goo.size(); i++)
{
returningVector.push_back(goo[i]); // breaks here
}
}
So what are some causes of this strange behavior without a debugger attached and not under debug configuration? I've checked to make sure all of my variables are initialized, so I'm stumped. If you want to view the code above, the first part can be located here, and the second part here. Please forgive anything you see as "bad", and if you have suggestions that you just can't contain, then please do message me on GitHub.
Edit:
I looked more into it, and found out exactly what's causing the problem, but don't know how to fix it. This is the function where my app crashes (on OS X):
vector<Drive *> Drive::GetFATXDrives( bool HardDisks )
{
vector<Drive *> Return;
if (HardDisks)
{
vector<DISK_DRIVE_INFORMATION> Disks = GetPhysicalDisks();
for (int i = 0; i < (int)Disks.size(); i++)
{
DISK_DRIVE_INFORMATION ddi = Disks.at(i);
// First, try reading the disk way
Streams::xDeviceStream* DS = NULL;
try
{
char path[0x200] = {0};
wcstombs(path, ddi.Path, wcslen(ddi.Path));
DS = new Streams::xDeviceStream(ddi.Path);
}
catch (xException& e)
{
continue;
}
if (DS == NULL || DS->Length() == 0 || DS->Length() < HddOffsets::Data)
{
// Disk is not of valid length
continue;
}
DS->SetPosition(HddOffsets::Data);
// Read the FATX partition magic
int Magic = DS->ReadInt32();
// Close the stream
DS->Close();
// Compare the magic we read to the *actual* FATX magic
if (Magic == FatxMagic)
{
Drive *d = new Drive(Disks.at(i).Path, Disks.at(i).FriendlyName, false);
Return.push_back(d);
}
}
}
vector<Drive *> LogicalDisks = GetLogicalPartitions();
for (int i = 0; i < (int)LogicalDisks.size(); i++)
{
Return.push_back(LogicalDisks.at(i));
}
return Return;
}
If I change if (HardDisks) to if (HardDisks = false), the app works just fine. So, I looked into that scope and discovered that after vector<DISK_DRIVE_INFORMATION> Disks = GetPhysicalDisks();, the heap gets corrupt or something like that. I noticed this because in the debugger, after that function is called, my HardDisks bool changes to "false", which wasn't what it was before.
Here is GetPhysicalDisks:
vector<Drive::DISK_DRIVE_INFORMATION> Drive::GetPhysicalDisks( void )
{
// RIGHT AFTER this vector is initialized, everything goes to hell
vector<Drive::DISK_DRIVE_INFORMATION> ReturnVector;
DIR *dir;
dirent *ent;
dir = opendir("/dev/");
if (dir != NULL)
{
// Read the shit
while ((ent = readdir(dir)) != NULL)
{
// Check the directory name, and if it starts with "disk" then keep it!
QRegExp exp("disk*");
exp.setPatternSyntax(QRegExp::Wildcard);
exp.setCaseSensitivity(Qt::CaseInsensitive);
if (exp.exactMatch(ent->d_name))
{
DISK_DRIVE_INFORMATION curdir;
memset(curdir.FriendlyName, 0, sizeof(curdir.FriendlyName));
memset(curdir.Path, 0, sizeof(curdir.Path));
char diskPath[0x50] = {0};
sprintf(diskPath, "/dev/r%s", ent->d_name);
mbstowcs(curdir.Path, diskPath, strlen(diskPath));
int device;
if ((device = open(diskPath, O_RDONLY)) > 0)
{
#ifdef __linux
hd_driveid hd;
if (!ioctl(device, HDIO_GET_IDENTITY, &hd))
{
swprintf(curdir.FriendlyName, strlen(hd) * 2, L"%hs", hd.model);
}
#elif defined __APPLE__
mbstowcs(curdir.FriendlyName, ent->d_name, strlen(ent->d_name));
#endif
ReturnVector.push_back(curdir);
}
}
}
}
return ReturnVector;
}
While this isn't a real answer as to what happened, I did find a way to fix the problem. Looking at my edit above, I edited my Drive::GetFATXDrives function like so:
vector<Drive *> Drive::GetFATXDrives( bool HardDisks )
{
// Initialize Disks vector up here
vector<DISK_DRIVE_INFORMATION> Disks;
// Call the function to get the hard disks
if (HardDisks)
Drive::GetPhysicalDisks(Disks);
vector<Drive *> ReturnVector;
if (HardDisks)
{
Streams::xDeviceStream* DS = NULL;
for (int i = 0; i < (int)Disks.size(); i++)
{
/* ... */
}
if (DS)
{
DS->Close();
delete DS;
}
}
vector<Drive *> LogicalDisks = GetLogicalPartitions();
for (int i = 0; i < LogicalDisks.size(); i++)
{
ReturnVector.push_back(LogicalDisks[i]);
}
return ReturnVector;
}
And my Drive::GetPhysicalDisks function now takes a vector<DISK_DRIVE_INFORMATION> reference instead of returning one. Seemed to make my program work just fine after that.

Erasing a pointer from a vector

I'm trying to erase a pointer to an object, but I keep crashing the console (PS2), I don't get any errors due to the way the console is set up, so I'm not quite sure what is going on.
I've listed the two lines that error, this didn't error until I added these lines.
for(listIter = m_downDirectionList.begin(); listIter != m_downDirectionList.end(); listIter++)
{
Projectile* proj = dynamic_cast<Projectile*>(*listIter);
if (proj->getZWorldCoord() >= (defaultLevelDepth + zOffset))
{
proj->getPoolOwner()->releaseAProjectile(proj);
//(*listIter) = NULL; // THIS ERRORS, also tried = 0.
//listIter = m_downDirectionList.erase(listIter); // THIS ALSO ERRORS
}
else
{
(*listIter)->update(camera, zOffset);
}
}
What am I doing wrong?
Thanks.
EDIT:
Clarification, just having this line.
listIter = m_downDirectionList.erase(listIter);
this also errors.
for(listIter = m_downDirectionList.begin(); listIter != m_downDirectionList.end(); )
{
Projectile* proj = dynamic_cast<Projectile*>(*listIter);
if (proj->getZWorldCoord() >= (defaultLevelDepth + zOffset))
{
proj->getPoolOwner()->releaseAProjectile(proj);
listIter = m_downDirectionList.erase(listIter);
}
else
{ //m_downDirectionList[p]->update(camera, zOffset);
(*listIter)->update(camera, zOffset);
listIter++
}
}
m_downDirectionList.erase (listIter);