Startup program has intermittant problems connecting to local database - c#-4.0

I'm writing an application that runs from the start-up folder, and tries to connect to a local SQLServer2008-r2 database as part of the startup process of the application. The database i'm connecting to is set to use windows authentication, and my connection string in the application is your standard old connection string:
Data Source=localhost\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True
The code to actually establish the connection looks like this:
String connectionstring = "Data Source=localhost\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True";
SqlConnection cn = new SqlConnection(connectionstring);
bool databaseUp = false;
void Start()
{
CheckSQLService();
for (int i = 0; i < 600; i++)
{
if (ConnectToDB())
{
Console.WriteLine("Database is up and running.");
databaseUp = true;
}
else
{
Console.WriteLine("Database Connection Failed");
CheckSQLService();
Console.WriteLine("Trying again");
Thread.Sleep(1000);
}
}
if(!databaseUp)
{
Console.WriteLine("Database Not Connected: exited loop.");
}
}
bool ConnectToDB()
{
try
{
cn.Open();
return true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
}
void CheckSQLService()
{
System.ServiceProcess.ServiceController SC = new System.ServiceProcess.ServiceController("MSSQL$SQLEXPRESS");
Console.WriteLine(" = = = Checking SQL Service Status: = = = "
+ "\n ServiceName : " + SC.ServiceName
+ "\n State : " + SC.Status
+ "\n Stoppable : " + SC.CanStop
+ "\n Pausable : " + SC.CanPauseAndContinue
+ "\n Can Shutdown: " + SC.CanShutdown);
}
Basically I loop until I get a connection, and if it fails, I sleep and try again.
Most of the time (about 60%) I am able to successfully establish a connection with no problem on first try. Sometimes, it takes several attempts for this to be successful, and the application waits for some time. I will also note that the read-out of CheckSQLService() verifies every time I call it that the SQL service is running - Only sometimes it rejects my windows credentials apparently.
Anybody have ideas why this might be happening intermittently? Again this is part of an application that runs when windows first starts up, so there could may understandably be many factors at play (e.g. other processes or services not fully loaded, or starting at same time etc).

Just because the SQL Server service is running does not mean it is ready to accept connections.
Since you are always able to connect eventually, and your program runs as the computer is booting, I strongly suspect that you sometimes run before SQL Server is fully initialized and ready for connections.
Many things happen during a typical boot sequence. It is not surprising that your program is sometimes running before SQL Server is ready, and vice-versa.

Related

Worker stuck in a Sandbox?

Trying to figure out why I can login with my rest API just fine on the main thread but not in a worker. All communication channels are operating fine and I am able to load it up no problem. However, when it tries to send some data it just hangs.
[Embed(source="../bin/BGThread.swf", mimeType="application/octet-stream")]
private static var BackgroundWorker_ByteClass:Class;
public static function get BackgroundWorker():ByteArray
{
return new BackgroundWorker_ByteClass();
}
On a test script:
public function Main()
{
fBCore.init("secrets", "my-firebase-id");
trace("Init");
//fBCore.auth.addEventListener(FBAuthEvent.LOGIN_SUCCES, hanldeFBSuccess);
fBCore.auth.addEventListener(AuthEvent.LOGIN_SUCCES, hanldeFBSuccess);
fBCore.auth.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
fBCore.auth.email_login("admin#admin.admin", "password");
}
private function handleIOError(e:IOErrorEvent):void
{
trace("IO error");
trace(e.text); //Nothing here
}
private function hanldeFBSuccess(e:AuthEvent):void
{
trace("Main login success.");
trace(e.message);//Complete success.
}
When triggered by a class via an internal worker channel passed from Main on init:
Primordial:
private function handleLoginClick(e:MouseEvent):void
{
login_mc.buttonMode = false;
login_mc.play();
login_mc.removeEventListener(MouseEvent.CLICK, handleLoginClick);
log("Logging in as " + email_mc.text_txt.text);
commandChannel.send([BGThreadCommand.LOGIN, email_mc.text_txt.text, password_mc.text_txt.text]);
}
Worker:
...
case BGThreadCommand.LOGIN:
log("Logging in with " + message[1] + "::" + message[2]); //Log goes to a progress channel and comes to the main thread reading the outputs successfully.
fbCore.auth.email_login(message[1], message[2]);
fbCore.auth.addEventListener(AuthEvent.LOGIN_SUCCES, loginSuccess); //Nothing
fbCore.auth.addEventListener(IOErrorEvent.IO_ERROR, handleLoginIOError); //Fires
break;
Auth Rest Class: https://github.com/sfxworks/FirebaseREST/blob/master/src/net/sfxworks/firebaseREST/Auth.as
Is this a worker limitation or a security sandbox issue? I have a deep feeling it is the latter of the two. If that's the case how would I load the worker in a way that also gives it the proper permissions to act?
Completely ignored the giveAppPrivelages property in the createWorker function. Sorry Stackoverflow. Sometimes I make bad questions when I get little (or none in this case) sleep the night before.

Problems reading stdin in node child process

I'm trying to execute a command in windows using nodes child_process module. The problem is that the application in question (ftp command line in windows) prompts for a username and password. I tried to provide the command with the asked information in the following way:
var ftp = spawn('ftp',['<<ip of server>>']);
var authenticated = false;
var commandsSended = false;
ftp.stdin.write("debug\n");
ftp.stdin.write(os.EOL);
ftp.stdout.on("data", function(data) {
console.log("FTPService: " + data.toString());
if(data.toString().indexOf("226 Transfer complete") > -1) {
ftp.stdin.write('bye\n');
} else if(data.toString().indexOf("Gebruiker") > -1) {
ftp.stdin.write("<<username of server>>");
ftp.stdin.write(os.EOL);
} else if(data.toString().indexOf("Wachtwoord") > -1) {
ftp.stdin.write("<<password of server>>");
ftp.stdin.write(os.EOL);
authenticated = true;
}
if(authenticated && !commandsSended) {
ftp.stdin.write("put " + filePath + " " + newName + "\n");
commandsSended = true;
}
});
ftp.on('exit', function(code) {
if(code > 0) {
console.log("FTPService closed with error " + code);
} else {
console.log("FTPService closed without error");
}
});
This doesn't result in an error, but simply doesn't work. In linux i don't have the problem because i can send the login information as argument with the command. I know that nodejs has it's own module but i need to get it working with the command line (Also other commands need to be performed which will also cause prompts that need to be filled in).
A good practice developing Node applications is to try to make your application as hybrid as possible. When I say hybrid I mean that it should operate identically and seamlessly on the various operating systems it supports. In your case, this means dropping support for the third-party FTP built-in to Windows or Linux and using a FTP client package specifically built for Node.
There are lots of FTP client packages for Node, here's one that's actively developed: node-ftp.
Another one that got more years on its back is jsftp and allows you to hook into the raw FTP socket connection and write arbitrary FTP comnmands to the server.

Network request in threads is crashing my application

Currently I have a code that is crashing (SEGFAULT) on me.
I am trying to compare a big amount of images that are in my drive to their counter parts in a server.
To speed up the process I get the image from the server and compare the images on a different thread.
From what I already tried and debugged, the issue is in getting the image from the server (that is why the other calls are commented out).
Also if I run without the QtConcurrent::run it does not crash, but if I put semaphore concurrentComparisons with only one resorce, it will crash.
Finally I also get the following errors
QObject::connect: Cannot connect (null)::configurationAdded(QNetworkConfiguration) to QNetworkConfigurationManager::configurationAdded(QNetworkConfiguration)
QObject::connect: Cannot connect (null)::configurationRemoved(QNetworkConfiguration) to QNetworkConfigurationManager::configurationRemoved(QNetworkConfiguration)
QObject::connect: Cannot connect (null)::configurationChanged(QNetworkConfiguration) to QNetworkConfigurationManager::configurationChanged(QNetworkConfiguration)
QObject::connect: Cannot connect (null)::onlineStateChanged(bool) to QNetworkConfigurationManager::onlineStateChanged(bool)
QObject::connect: Cannot connect (null)::configurationUpdateComplete() to QNetworkConfigurationManager::updateCompleted()
Any help would be very appreciated.....
Relevant code:
QSemaphore FileComparisonInfo::concurrentComparisons(1);
QtConcurrent::run( [this, localPath, imageURL]()
{
ImageComparer cmp;
FileComparisonInfo::concurrentComparisons.acquire();
//cmp.setImageLeftPath(localPath);
cmp.setImageRightPath(imageURL);
//cmp.createDifferenceImage();
FileComparisonInfo::concurrentComparisons.release();
});
void ImageComparer::setImageRightPath(QString path)
{
this->rightImagePath = path;
this->imageRight = getImage(path);
}
QImage* ImageComparer::getImage(QString path)
{
QUrl url(path);
QFile file(path);
if(file.exists())
{
return new QImage(path);
}
else if(url.isValid())
{
return getImageFromURL(path);
}
}
QImage* ImageComparer::getImageFromURL(QString url)
{
QNetworkAccessManager * tempNAM = new QNetworkAccessManager();
QNetworkReply *imageConnection = tempNAM->get( QNetworkRequest( QUrl( url ) ));
QEventLoop loop;
connect(imageConnection, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QImage * downloadedImage;
if(imageConnection->error() != QNetworkReply::NoError)
{
qDebug() << imageConnection->errorString();
downloadedImage = new QImage();
}
else
{
QByteArray data = imageConnection->readAll();
downloadedImage = new QImage(QImage::fromData(data));
}
tempNAM->deleteLater();
imageConnection->deleteLater();
return downloadedImage;
}
Unfortunately this had nothing to do with the code.
One of the images was corrupted and was segfaulting in the comparison.

BlackBerry - App freezes when background thread executing

I have a BlackBerry App that sends data over a web service when a button has it state set to ON. When the button is ON a timer is started which is running continuously in the background at fixed intervals. The method for HttpConnection is called as follows:
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
return;
}
else
{
confirmation=PostMsgToServer(encryptedMsg);
}
The method PostMsgToServer is as follows:
public static String PostMsgToServer(String encryptedGpsMsg) {
//httpURL= "https://prerel.track24c4i.com/track24prerel/service/spi/post?access_id="+DeviceBoardPassword+"&IMEI="+IMEI+"&hex_data="+encryptedGpsMsg+"&device_type=3";
httpURL= "https://t24.track24c4i.com/track24c4i/service/spi/post?access_id="+DeviceBoardPassword+"&IMEI="+IMEI+"&hex_data="+encryptedGpsMsg+"&device_type=3";
//httpURL= "http://track24.unit1.overwatch/track24/service/spi/post?access_id="+DeviceBoardPassword+"&IMEI="+IMEI+"&hex_data="+encryptedGpsMsg+"&device_type=3";
try {
String C0NNECTION_EXTENSION = checkInternetConnection();
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
return null;
}
else
{
httpURL=httpURL+C0NNECTION_EXTENSION+";ConnectionTimeout=120000";
//Dialog.alert(httpURL);
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
responce = res.trim();
httpConn.close();
}
}catch (Exception e) {
//Dialog.alert("Connection Time out");
}
return responce;
}
My Question: The App freezes whenever the method is called, i.e. whenever the timer has to execute and send data to the web service the App freezes - at times for a few seconds and at times for a considerable amount of time applying to the user as if the handset has hanged. Can this be solved? Kindly help!!
You are running your networking operation on the Event Thread - i.e. the same Thread that processes your application's Ui interactions. Networking is a blocking operation so effectively this is stopping your UI operation. Doing this on the Event Thread is not recommended and to be honest, I'm surprised it is not causing your application to be terminated, as this is often what the OS will do, if it thinks the application has blocked the Event Thread.
The way to solve this is start your network processing using a separate Thread. This is generally the easy part, the difficult part is
blocking the User from doing anything else while waiting for the
response (assuming you need to do this)
updating the User Interface with the results of your networking
processing
I think the second of these issues are discussed in this Thread:
adding-field-from-a-nonui-thread-throws-exception-in-blackberry
Since it appears you are trying to do this update at regular intervals in the background, I don't think the first is an issue, - for completeness, you can search SO for answers including this one:
blackberry-please-wait-screen-with-time-out
There is more information regarding the Event Thread here:
Event Thread

Live555 OpenRTSP Client : How to delete current rtsp client properly and start new One

Well,
When my OpenRtsp Client lost connection with server, I dispose the
old client and other parameters then re-create new client.
The Client send Options,Describe request successfully but failed after that... I can not able create Session and Subsesions so I got Access Violations errors..
How to reset old OpenRtspClient properly so that get new "brand" RTSPClient?
My Current Way to Reset Old Client:
I just modify the "shutdown" method in playCommon class. I did not send Teardown...
...
void ResetOurClient(){
if (env != NULL) {
env->taskScheduler().unscheduleDelayedTask(sessionTimerTask);
env->taskScheduler().unscheduleDelayedTask(arrivalCheckTimerTask);
env->taskScheduler().unscheduleDelayedTask(interPacketGapCheckTimerTask);
env->taskScheduler().unscheduleDelayedTask(qosMeasurementTimerTask);
}
closeMediaSinks();
Medium::close(session);
delete ourAuthenticator;
Medium::close(ourClient);
}
And My ReStartCode:
void StartOurClient()
{
TaskScheduler* scheduler = BasicTaskScheduler::createNew();
env = BasicUsageEnvironment::createNew(*scheduler);
char* streamURL = "XXXXXXXXX";
// Create our client object:
ourClient = createClient(*env, streamURL, verbosityLevel, progName);
if (ourClient == NULL) {
*env << "Failed to create " << clientProtocolName
<< " client: " << env->getResultMsg() << "\n";
shutdown();
}
if (sendOptionsRequest) {
// Begin by sending an "OPTIONS" command:
getOptions(continueAfterOPTIONS);
} else {
continueAfterOPTIONS(NULL, 0, NULL);
}
// All subsequent activity takes place within the event loop:
env->taskScheduler().doEventLoop(&continuesStream); // does not return
}
(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Well there was a static variable setUpIter...[MediaSubsessionIterator* setupIter = NULL;] in setupstreams method...so make it global non-static variable and make it NULL at ReStart

Resources