Setting TFDConnection to MongoDB - mongodb

In the empty project after you open TFDConnection->Open() the connection to Mongodb upon completion of the program crashes error 'Bluetooth: unable to clean up Winsock'.

This error appears to occur during the TWinBluetoothSocket.Destroy routine in System.Win.Bluetooth. For some reason, the TWinBluetoothSocket destructor is called in a C++ application, even though Bluetooth is not used.
The problem is that WSACleanup() is being called by the TWinBluetoothSocket destructor, but WSAStartup() had never been called, so WSACleanup() returns an error.
This occurs when the Mongo driver is used in a C++ application, even when the TFDConnection is in a Delphi unit, as long as the Mongo driver is selected and Connected is set to true in design or runtime.
No MongoDB server is needed to reproduce this; just set Connected to be true in a button click handler. Of course, an error will occur because there is no MongoDB server, but this error will occur when the application exits.
The workaround is to put this in the Constructor (from https://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx)
WORD wVersionRequested;
WSADATA wsaData;
int err;
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
{
ShowMessage("err nonzero");
}
Now, WSAStartup() is called, so WSACleanup() does not return an error, and the application can close.

Related

JBoss 7.1.0: executor.submit() how to debug (no exception but task not started)

I have an issue with JBoss EAP 7.1.0 GA. On one server (my DEV) this works like a charm while on the other (TEST environment) the Callable executed using executor.submit() does not seem to be started (I do not see that "This is call" message in log), but no exception or any other clue is given.
The question is - where should I look like / how should I debug this issue?
The calling code:
#Resource(name = "DefaultManagedExecutorService")
ManagedExecutorService executor;
try {
DownloadPlayers dp = new DownloadPlayers();
Future<Queue<PlayerForDownload>> f = executor.submit(dp);
Queue<PlayerForDownload> q = f.get();
L.info(q.size());
} catch (Exception e) {
L.error("EXCEPTION" + e.getMessage());
}
The class it calls:
public class DownloadPlayers implements Callable<Queue<PlayerForDownload>> {
// the constructor gets called, I'm sure as it writes to log
// the call is as simple as this
#Override
public Queue<PlayerForDownload> call() {
L.info("This is call()");
try {
return this.getPlayersForDownload();
} catch (WorkerException e) {
L.error(e);
return null;
}
}
}
As stated above, the code itself seems to be OK as it works in one server but does not work on the other. Both are
7.1.0GA standalone.
Any advice how to debug the ManagedExecutorService?
Thanks.
In this particular case the problem was that on the TEST environment it was only allowed to run two threads which we already running (by some completely different part of application I didn't realize). So the problem is solved now by setting the "Core threads" parameter in ManagerExecutorService to higher value, the tasks are running.
However the tricky part was that there was no obvious visible difference between the JBoss servers (I compared the standalone.xml configs...) just because the ManagerExecutorService in JBoss has some default (blank) values that actually depend on the system config (v-CPU cores in my case). So despite the config being the same, the "Core threads" seem to default to 2 on TEST and some higher (unknown to me) value on my DEV.
So never depend on default settings in ManagerExecutorService if comparing two environments.
I have also rewritten the logic, instead of using blocking Future.get() or checking for Future.isDone() in a loop a do Future.get() with timeout and in the exception handler I decide whether to keep waiting or fail.

Simple UDP socket in VC++ MFC

I have been trying to write a working program that takes in data from a UDP socket and displays it in an edit control box as you receive the data (My exposure to c++ is also only about a week :P have only done embedded C code before). I have a working program that can send and output data on a button click but I want something that can do it in real time. The aim is scale this up into a larger GUI program that can send control data to hardware and get responses from them.
I have run into various problems including:
The program just not executing my OnReceivefunction (derived from
CAsyncSocket)
Getting the OnReceive function to run on a separate thread so that it can still run after a button has been clicked sending a control packet to the client then waiting for a response in a while loop
Not being able to output the data in the edit box (tried using both CEdit and CString)
ReplaceSel error saying that the type char is incompatible with LPCTSTR
My code is based on this codeproject.com tutorial, being almost exactly what I want but I get the error in 4.
EDIT: the error in 4. disappears when I change it to a TCHAR but then it outputs random chinese characters. The codeproject.com tutorial outputs the correct characters regardless of char or TCHAR declaration. When debugged my code has type wchar_t instead type char like the other code.
Chinese output
In the working program echoBuffer[0] the character sent and displayed was a 1
UINT ReceiveData(LPVOID pParam)
{
CTesterDlg *dlg = (CTesterDlg*)pParam;
AfxSocketInit(NULL);
CSocket echoServer;
// Create socket for sending/receiving datagrams
if (echoServer.Create(12345, SOCK_DGRAM, NULL) == 0)
{
AfxMessageBox(_T("Create() failed"));
}
for (;;)
{ // Run forever
// Client address
SOCKADDR_IN echoClntAddr;
// Set the size of the in-out parameter
int clntAddrLen = sizeof(echoClntAddr);
// Buffer for echo string
char echoBuffer[ECHOMAX];
// Block until receive message from a client
int recvMsgSize = echoServer.ReceiveFrom(echoBuffer, ECHOMAX, (SOCKADDR*)&echoClntAddr, &clntAddrLen, 0);
if (recvMsgSize < 0)
{
AfxMessageBox(_T("RecvFrom() failed"));
}
echoBuffer[recvMsgSize] = '\0';
dlg->m_edit.ReplaceSel(echoBuffer);
dlg->m_edit.ReplaceSel(_T("\r\n"));
}
}
After reading the link that #IInspectable provided about working with strings and checking the settings differences between the two programs it became clear that the issue lay with an incorrect conversion to UNICODE. My program does not require it so I disabled it.
This has cleared up the issue in 4. and provided solutions for 2 and 3.
I also think I know why another instance of my program would not run OnReceivein 1. because that file was not being defined by one that was already being run by the program, but that is now irrelevant.

Use unregister_chrdev_region in case registration failed

I am learning how to write kernel drivers, and I have a doubt about the proper
usage of the function unregister_chrdev_region.
Right now I have a simple test module with just the init and
exit functions:
static dev_t devn;
int __init my_dev_init(void)
{
devn = MKDEV(0,0);
if(alloc_chrdev_region(&devn,0,1,"my_dev") != 0)
{
return -EBUSY;
}
else
{
return 0;
}
}
void __exit my_dev_exit(void)
{
unregister_chrdev_region(devn,1);
}
My question: is it safe to call unregister_chrdev_region if the registration failed ? I would assume no, but pretty much all example code that I have seen calls unregister_chrdev_region no matter what happened during the initialization.
Registration rarely fails. If registration fails, init function fails, thus insmod command will not succeed in loading the kernel module i.e. test.ko and device node will not be created. So there is no question of unregistration (rmmod). If registration is successful then only we can unregister the driver i.e. unloading the kernel, removal of device node etc... using rmmod. If in init function registration is successful and some other API fails then need to add goto statements, jump to appropriate goto label to unregister and return the appropriate error value. Hope I have cleared your doubt :-)

Confusion about CFNetwork, CFReadStreamOpen, and CFRunLoopRun

That sinking feeling when you realize you have no idea what's going on...
I've been using this code in my network code for almost two years without problems.
if (!CFReadStreamOpen(myReadStream)) {
CFStreamError myErr = CFReadStreamGetError(myReadStream);
if (myErr.error != 0) {
// An error has occurred.
if (myErr.domain == kCFStreamErrorDomainPOSIX) {
// Interpret myErr.error as a UNIX errno.
strerror(myErr.error);
} else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) {
OSStatus macError = (OSStatus)myErr.error;
}
// Check other domains.
}
}
I believe it was originally based on the code samples given here:
http://developer.apple.com/library/mac/#documentation/Networking/Conceptual/CFNetwork/CFStreamTasks/CFStreamTasks.html
I recently noticed, however, that some connections are failing, because CFReadStreamOpen returns false but the error code is 0. After staring at the above link some more, I noticed the CFRunLoopRun() statement, and added it:
if (!CFReadStreamOpen(myReadStream)) {
CFStreamError myErr = CFReadStreamGetError(myReadStream);
if (myErr.error != 0) {
// An error has occurred.
if (myErr.domain == kCFStreamErrorDomainPOSIX) {
// Interpret myErr.error as a UNIX errno.
strerror(myErr.error);
} else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) {
OSStatus macError = (OSStatus)myErr.error;
}
// Check other domains.
} else
// start the run loop
CFRunLoopRun();
}
This fixed the connection problem. However, my app started showing random problems - interface sometimes not responsive, or not drawing, text fields not editable, that kind of stuff.
I've read up on CFReadStreamOpen and on run loops (specifically, that the main run loop runs by itself and I shouldn't run a run loop unless I'm setting it up myself in a secondary thread - which I'm not, as far as I know). But I'm still confused about what's actually happening above. Specifically:
1) Why does CFReadStreamOpen sometimes return FALSE and error code 0? What does that actually mean?
2) What does the CFRunLoopRun call actually do in the above code? Why does the sample code make that call - if this code is running in the main thread I shouldn't have to run the run loop?
I guess I'll answer my own question, as much as I can.
1) In my code, at least, CFReadStreamOpen always seems to return false. The documentation is a bit confusing, but I read it to mean the stream wasn't opened yet, but will be open later in the run loop.
2) Most of the calls I was making were happening in the main thread, where the run loop was already running, so calling CFRunLoopRun was unnecessary. The call that was giving me problems was happening inside a block, which apparently spawned a new thread. This new thread didn't start a new run loop - so the stream would never open unless I explicitly ran the new thread's run loop.
I'm still not 100% clear on what happens if I call CFRunLoopRun() on a thread with an already running run loop, but it's obviously not good.
I ended up ditching my home-brewed networking code and switching to ASIHTTPRequest, which I was considering to do anyway.

IWebBrowser2 Quit method fails with a E_FAIL result

I am hosting the web browser control in my own window. Here are the pertinent steps:
CoGetClassObject(CLSID_WebBrowser,
CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER,
NULL, IID_IClassFactory, (void **)&pClassFactory);
pClassFactory->CreateInstance(0, IID_IOleObject, (void **)&pObject);
pClassFactory->Release();
pObject->SetClientSite((IOleClientSite *)impl)
OleSetContainedObject((struct IUnknown *)pObject, true)
pObject->DoVerb(OLEIVERB_SHOW, NULL, (IOleClientSite *)impl, 0, hHpsWnd, &rect);
pWB->put_Visible(VARIANT_FALSE);
hr=pWB->Quit();
At the last statement above the hr return value is E_FAIL. The end result of this failure in my code is leaking of a bunch of resources. What am I doing incorrectly?
Reading the documenation here it states the WebBrowser object (i.e. CLSID_WebBrowser) returns an error from the Quit method because it does not make sense in context. The Quit method will quit the out of process version of IE which also uses the same interface to communicate.
Only thing I can suggest is double check you are releasing all COM object relating to the browser.