Example #1
0
   void 
   AWStats::Log_(const String &senderIP, const String &recipientIP, const String &senderAddress, const String &recipientAddress, int iErrorCode, int iBytesReceived)
   {
      if (!enabled_)
         return;

      // Following format is used:
      // %time2 %email %email_r %host %host_r %method %url %code %bytesd"
      
      String sTime = Time::GetCurrentDateTime();

      String sModifiedSender = senderAddress;
      sModifiedSender.Replace(_T("<"), _T(""));
      sModifiedSender.Replace(_T(">"), _T(""));
      sModifiedSender.Replace(_T(" "), _T(""));
      sModifiedSender.Replace(_T("\t"), _T(""));

      String sModifiedRecipient = recipientAddress;
      sModifiedRecipient.Replace(_T("<"), _T(""));
      sModifiedRecipient.Replace(_T(">"), _T(""));
      sModifiedRecipient.Replace(_T(" "), _T(""));
      sModifiedRecipient.Replace(_T("\t"), _T(""));

      String sLogLine;
      sLogLine.Format(_T("%s\t%s\t%s\t%s\t%s\tSMTP\t?\t%d\t%d\r\n"), 
                        sTime, sModifiedSender, sModifiedRecipient, senderIP, recipientIP, iErrorCode, iBytesReceived );

      Logger::Instance()->LogAWStats(sLogLine);
   }
Example #2
0
 String
 FileUtilities::GetTempFileName()
 {
    String sTmpFile;
    sTmpFile.Format(_T("%s\\%s.tmp"), IniFileSettings::Instance()->GetTempDirectory(), GUIDCreator::GetGUID() );      
    return sTmpFile;
 }
   VirusScanningResult 
   CustomVirusScanner::Scan(const String &executablePath, int virusReturnCode, const String &sFilename)
   {
      LOG_DEBUG("Running custom virus scanner...");


      String sPath = FileUtilities::GetFilePath(sFilename);

      String sCommandLine;

      if (executablePath.Find(_T("%FILE%")) >= 0)
      {
         sCommandLine = executablePath;
         sCommandLine.Replace(_T("%FILE%"), sFilename);
      }
      else
         sCommandLine.Format(_T("%s %s"), executablePath, sFilename);

      unsigned int exitCode = 0;
      ProcessLauncher launcher(sCommandLine, sPath);
      launcher.SetErrorLogTimeout(20000);
      if (!launcher.Launch(exitCode))
      {
         return VirusScanningResult("CustomVirusScanner::Scan", "Unable to launch executable.");
      }

      String sDebugMessage = Formatter::Format("Scanner: {0}. Return code: {1}", sCommandLine, exitCode);
      LOG_DEBUG(sDebugMessage);

      if (exitCode == virusReturnCode)
         return VirusScanningResult(VirusScanningResult::VirusFound, "Unknown");
      else
         return VirusScanningResult(VirusScanningResult::NoVirusFound, Formatter::Format("Return code: {0}", exitCode));

   }
   void
   SMTPClientConnection::_StartSendFile(const String &sFilename)
   {
      if (!_currentFile.Open(sFilename, File::OTReadOnly))
      {
         String sErrorMsg;
         sErrorMsg.Format(_T("Could not send file %s via socket since it does not exist."), sFilename);

         ErrorManager::Instance()->ReportError(ErrorManager::High, 5019, "SMTPClientConnection::_SendFileContents", sErrorMsg);

         return;
      }

      _transmissionBuffer.Initialize(this);

      shared_ptr<ByteBuffer> pBuf = _currentFile.ReadChunk(GetBufferSize());

      if (!pBuf)
         return;

      BYTE *pSendBuffer = (BYTE*) pBuf->GetBuffer();
      int iSendBufferSize = pBuf->GetSize();

      // Append the transmission buffer
      _transmissionBuffer.Append(pSendBuffer, iSendBufferSize);
      
	  _ReadAndSend();
   }
   bool 
   PersistentBlockedAttachment::SaveObject(shared_ptr<BlockedAttachment> pObject)
   {
      SQLStatement oStatement;
      oStatement.SetTable("hm_blocked_attachments");
      
      if (pObject->GetID() == 0)
      {
         oStatement.SetStatementType(SQLStatement::STInsert);
         oStatement.SetIdentityColumn("baid");
      }
      else
      {
         oStatement.SetStatementType(SQLStatement::STUpdate);
         String sWhere;
         sWhere.Format(_T("baid = %I64d"), pObject->GetID());
         oStatement.SetWhereClause(sWhere);
         
      }

      oStatement.AddColumn(_T("bawildcard"), pObject->GetWildcard());
      oStatement.AddColumn(_T("badescription"), pObject->GetDescription());

      bool bNewObject = pObject->GetID() == 0;

      // Save and fetch ID
      __int64 iDBID = 0;
      bool bRetVal = Application::Instance()->GetDBManager()->Execute(oStatement, bNewObject ? &iDBID : 0);
      if (bRetVal && bNewObject)
         pObject->SetID((int) iDBID);


      return true;
   }
   void
   SpamAssassinClient::ParseData(std::shared_ptr<ByteBuffer> pBuf)
   {
      if (!result_)
      {
         String logMessage;
         logMessage.Format(_T("Parsing response from SpamAssassin. Session %d"), GetSessionID());
         LOG_DEBUG(logMessage);

         result_ = std::shared_ptr<File>(new File);
         result_->Open(FileUtilities::GetTempFileName(), File::OTAppend);

         spam_dsize_ = ParseFirstBuffer_(pBuf);
      }

      // Append output to the file
      result_->Write(pBuf);

      total_result_bytes_written_ += pBuf->GetSize();

      if (total_result_bytes_written_ < spam_dsize_)
         EnqueueRead();
      else
         FinishTesting_();
   }
Example #7
0
   void 
   ExternalFetchTask::DoWork()
   {
      try
      {
         // Do the actual delivery of the message.
         ExternalFetch oFetcher;
         oFetcher.Start(m_pFA);
      }
      catch (boost::system::system_error error)
      {
         String sErrorMessage;
         sErrorMessage.Format(_T("An error occurred while download messages from external account. Error number: %d, Description: %s"), error.code().value(), String(error.what()));
         ErrorManager::Instance()->ReportError(ErrorManager::High, 5316, "DeliveryTask::DoWork", sErrorMessage);
      }
      catch (...)
      {
         String sErrorMessage = _T("An error occurred while download messages from external account.");
         ErrorManager::Instance()->ReportError(ErrorManager::High, 5317, "DeliveryTask::DoWork", sErrorMessage);
      }

      // Set next fetch time 
      PersistentFetchAccount::SetNextTryTime(m_pFA);

      // Unlock the account
      PersistentFetchAccount::Unlock(m_pFA->GetID());
   }
Example #8
0
File: job.cpp Project: PyroOS/Pyro
int RecursiveUploadJob::AttachToHandle( CurlHandle_s* psHandle )
{
	/* First open the local directory for listing; if it can't be opened then fail with error message */
	try {
		m_pcDirIterator = new Directory( m_zLocalPath );
	} catch( errno_exception& e ) {
		DEBUG( "RecursiveUploadJob: Error accessing directory '%s': %s (%i)!\n", m_zLocalPath.c_str(), e.what(), e.error() );
		String zMsg;
		zMsg.Format( "Could not read directory %s: %s", m_zLocalPath.c_str(), e.what() );
		m_pcServer->SendFailureNotification( this, zMsg );
		m_nStatus = STATUS_FAILED;
		FinaliseJob();
		return( -1 );
	}
	
	/* Then create & attach a child CommandJob to create the remote dir */
	String zCommand = "MKD ";
	zCommand += m_zRemotePath;
	std::vector<String> cTmp;
	cTmp.push_back( zCommand );
	
	int nNewID = m_pcServer->GetNewJobID();
	Job* pcChild = new CommandJob( m_pcServer, cTmp, false, nNewID, this );
	/* TODO: overwrite/failure policy here? */
	m_pcChildJob = pcChild;
	m_pcServer->AddJob( pcChild );
	m_nStatus = STATUS_PENDING_CHILD_JOB;
	m_pcServer->JobUpdated( this );
	/* Child will be activated by _Schedule() */
	
	/* The uploading will be done in ChildTransferFinished() */

	return( CURLE_OK );
}
Example #9
0
   bool 
   SMTPDeliverer::_RunGlobalRules(boost::shared_ptr<Message> pMessage, RuleResult &ruleResult)
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Performs global rules. We will do this on every retry of the message.
   //---------------------------------------------------------------------------()
   {
      boost::shared_ptr<RuleApplier> pRuleApplier = boost::shared_ptr<RuleApplier>(new RuleApplier);
      boost::shared_ptr<Account> emptyAccount;
      pRuleApplier->ApplyRules(ObjectCache::Instance()->GetGlobalRules(), emptyAccount, pMessage, ruleResult);

      if (ruleResult.GetDeleteEmail())
      {
         String sDeleteRuleName = ruleResult.GetDeleteRuleName();

         String sMessage;
         sMessage.Format(_T("SMTPDeliverer - Message %I64d: ")
            _T("Message deleted. Action was taken by a global rule (%s). "),
            pMessage->GetID(), 
            sDeleteRuleName);

         LOG_APPLICATION(sMessage);

         PersistentMessage::DeleteObject(pMessage);
         return false;
      }

      return true;
   }
   void
   SMTPClientConnection::StartSendFile_(const String &sFilename)
   {
      try
      {
         current_file_.Open(sFilename, File::OTReadOnly);
      }
      catch (...)
      {
         String sErrorMsg;
         sErrorMsg.Format(_T("Could not send file %s via socket since it does not exist."), sFilename.c_str());

         ErrorManager::Instance()->ReportError(ErrorManager::High, 5019, "SMTPClientConnection::_SendFileContents", sErrorMsg);

         return;
      }

      transmission_buffer_.Initialize(shared_from_this());

      std::shared_ptr<ByteBuffer> pBuf = current_file_.ReadChunk(GetBufferSize());

      if (pBuf->GetSize() == 0)
         return;

      BYTE *pSendBuffer = (BYTE*) pBuf->GetBuffer();
      size_t iSendBufferSize = pBuf->GetSize();

      // Append the transmission buffer
      transmission_buffer_.Append(pSendBuffer, iSendBufferSize);
      
	  ReadAndSend_();
   }
Example #11
0
bool OTASCIIArmor::WriteArmoredString(
    String& strOutput,
    const // for "-----BEGIN OT LEDGER-----", str_type would contain "LEDGER"
    std::string str_type, // There's no default, to force you to enter the right
                          // string.
    bool bEscaped) const
{
    const char* szEscape = "- ";

    String strTemp;
    strTemp.Format(
        "%s%s %s-----\n" // "%s-----BEGIN OT ARMORED %s-----\n"
        "Version: Open Transactions %s\n"
        "Comment: "
        "http://opentransactions.org\n\n" // todo
        // hardcoding.
        "%s"                // Should already have a newline at the bottom.
        "%s%s %s-----\n\n", // "%s-----END OT ARMORED %s-----\n"
        bEscaped ? szEscape : "",
        OT_BEGIN_ARMORED, str_type.c_str(), // "%s%s %s-----\n"
        Log::Version(),                     // "Version: Open Transactions %s\n"
        /* No variable */                   // "Comment:
        // http://github.com/FellowTraveler/Open-Transactions/wiki\n\n",
        Get(), //  "%s"     <==== CONTENTS OF THIS OBJECT BEING
               // WRITTEN...
        bEscaped ? szEscape : "", OT_END_ARMORED,
        str_type.c_str()); // "%s%s %s-----\n"

    strOutput.Concatenate("%s", strTemp.Get());

    return true;
}
   VirusScanningResult 
   ClamWinVirusScanner::Scan(const String &scannerExecutable, const String &databasePath, const String &sFilename)
   {
      LOG_DEBUG("Running ClamWin");

      String sPath = FileUtilities::GetFilePath(sFilename);
      String sFileToScan = FileUtilities::GetFileNameFromFullPath(sFilename);
      String sTempDir = Utilities::GetWin32TempDirectory();

      String sCommandLine;
      sCommandLine.Format(_T("%s --database=\"%s\" \"%s\" --tempdir=\"%s\""), scannerExecutable, databasePath, sFileToScan, sTempDir);

      unsigned int exitCode = 0;
      ProcessLauncher launcher(sCommandLine, sPath);
      launcher.SetErrorLogTimeout(20000);
      if (!launcher.Launch(exitCode))
      {
         return VirusScanningResult("ClamWinVirusScanner::Scan", "Unable to launch executable.");
      }

      String sDebugMessage = Formatter::Format("ClamWin: {0}. Return code: {1}", sCommandLine, exitCode);
      LOG_DEBUG(sDebugMessage);

      if (exitCode == 1)
         return VirusScanningResult(VirusScanningResult::VirusFound, "Unknown");
      else
         return VirusScanningResult(VirusScanningResult::NoVirusFound, Formatter::Format("Return code: {0}", exitCode));

   }
Example #13
0
bool
Application::OpenDatabase(String &sErrorMessage)
{
    String sIniFileCheckError;
    if (!IniFileSettings::Instance()->CheckSettings(sIniFileCheckError))
    {
        String sError;
        sError.Format(_T("Loading of ini file settings failed. Error: %s"), sIniFileCheckError);

        ErrorManager::Instance()->ReportError(ErrorManager::Medium, 5005, "Application::OpenDatabase", sError);
        return false;
    }

    m_pDBManager = shared_ptr<DatabaseConnectionManager>(new DatabaseConnectionManager);
    bool bConnectedSuccessfully = m_pDBManager->CreateConnections(sErrorMessage);

    m_sLastConnectErrorMessage = sErrorMessage;

    if (!bConnectedSuccessfully)
    {
        ErrorManager::Instance()->ReportError(ErrorManager::Critical, 4354, "Application::OpenDatabase", "hMailServer failed to connect to the database server. Error message: " + sErrorMessage);
        return false;
    }

    return true;
}
   IMAPResult
   IMAPCommandNamespace::ExecuteCommand(std::shared_ptr<HM::IMAPConnection> pConnection, std::shared_ptr<IMAPCommandArgument> pArgument)
   {
      if (!pConnection->IsAuthenticated())
         return IMAPResult(IMAPResult::ResultNo, "Authenticate first");

      std::shared_ptr<IMAPSimpleCommandParser> pParser = std::shared_ptr<IMAPSimpleCommandParser>(new IMAPSimpleCommandParser());
      pParser->Parse(pArgument);

      if (pParser->WordCount() < 1)
         return IMAPResult(IMAPResult::ResultBad, "NAMESPACE command requires exactly 0 parameter.");

      String sPublicFolderName = Configuration::Instance()->GetIMAPConfiguration()->GetIMAPPublicFolderName();
      String hierarchyDelimiter = Configuration::Instance()->GetIMAPConfiguration()->GetHierarchyDelimiter();
      hierarchyDelimiter.Replace(_T("\\"), _T("\\\\"));

      String sPersonalNamespace = "((\"\" \"" + hierarchyDelimiter + "\"))";
      String sOtherUsersNamespace = "NIL";
      String sSharedNamespaces = "((\"" + sPublicFolderName + "\" \"" + hierarchyDelimiter + "\"))";
      String sResponse;
      
      sResponse.Format(_T("* NAMESPACE %s %s %s\r\n"), sPersonalNamespace.c_str(), sOtherUsersNamespace.c_str(), sSharedNamespaces.c_str());
      sResponse += pArgument->Tag() + _T(" OK namespace command complete\r\n");

      pConnection->SendAsciiData(sResponse);   

      return IMAPResult();
   }
Example #15
0
   set<shared_ptr<SpamTestResult> > 
   SpamTestSPF::RunTest(shared_ptr<SpamTestData> pTestData)
   {
      set<shared_ptr<SpamTestResult> > setSpamTestResults;

      String sMessage = "";
      int iScore = 0;

      const IPAddress &originatingAddress = pTestData->GetOriginatingIP();

      if (originatingAddress.IsAny())
         return setSpamTestResults;

      String sExplanation;
      SPF::Result result = SPF::Instance()->Test(originatingAddress.ToString(), pTestData->GetEnvelopeFrom(), sExplanation);
      
      if (result == SPF::Fail)
      {
         // Blocked by SPF.s
         sMessage.Format(_T("Blocked by SPF (%s)"), sExplanation);
         iScore = Configuration::Instance()->GetAntiSpamConfiguration().GetUseSPFScore();

         shared_ptr<SpamTestResult> pResult = shared_ptr<SpamTestResult>(new SpamTestResult(GetName(), SpamTestResult::Fail, iScore, sMessage));
         setSpamTestResults.insert(pResult);
      }      
      else if (result == SPF::Pass)
      {
         shared_ptr<SpamTestResult> pResult = shared_ptr<SpamTestResult>(new SpamTestResult(GetName(), SpamTestResult::Pass, 0, ""));
         setSpamTestResults.insert(pResult);
      }


      return setSpamTestResults;
   }
Example #16
0
 String 
 StringParser::IntToString(__int64 lTheInt)
 {
    String sRetVal;
    sRetVal.Format(_T("%I64d"), lTheInt);
    return sRetVal;
 }
Example #17
0
void
HashCreatorTester::Test()
{
    // Run basic test.
    HashCreator hasher(HashCreator::SHA256);
    AnsiString result = hasher.GenerateHash("The quick brown fox jumps over the lazy dog", "");

    if (!hasher.ValidateHash("The quick brown fox jumps over the lazy dog", result, true))
        throw 0;

    // Check that same password hashed twice yealds separate hashes.
    AnsiString test1 = hasher.GenerateHash("The quick brown fox jumps over the lazy dog", "");
    AnsiString test2 = hasher.GenerateHash("The quick brown fox jumps over the lazy dog", "");
    if (test1 == test2)
        throw 0;

    for (int i = 0; i < 250; i++)
    {
        HashCreator memoryTester(HashCreator::SHA256);

        String temp;
        temp.Format(_T("%d"), i);
        AnsiString hashableString = temp;

        hasher.GenerateHash(hashableString, "test");
    }
}
Example #18
0
   bool
   VirusScanner::Scan(shared_ptr<Message> pMessage, String &virusName)
   {
      AntiVirusConfiguration &antiVirusConfig = Configuration::Instance()->GetAntiVirusConfiguration();

      int iMaxVirusScanSizeKB = antiVirusConfig.GetVirusScanMaxSize();
      int iMessageSizeKB = pMessage->GetSize() / 1024;
      if (iMaxVirusScanSizeKB > 0 &&
          iMessageSizeKB > iMaxVirusScanSizeKB)
      {
         // Message is to big. Don't scan.
         return false;
      }

      // Prevent too many scanners from running at once.
      _WaitForFreeScanner();
      VirusScannerAutoCount autoCounter;

      // First scan the entire file.
      String sLongFilename = PersistentMessage::GetFileName(pMessage);

      VirusScanningResult result = _ScanFile(sLongFilename);
      if (result.GetVirusFound())
      {
         virusName = result.GetDetails();
         return true;
      }


      // Read message, extract attachments, 
      shared_ptr<MimeBody> pMimeBody = shared_ptr<MimeBody>(new MimeBody);
      pMimeBody->LoadFromFile(sLongFilename);

      list<shared_ptr<MimeBody> > oList;
      pMimeBody->GetAttachmentList(pMimeBody, oList);

      list<shared_ptr<MimeBody> >::iterator iter = oList.begin();

      while (iter != oList.end())
      {
         shared_ptr<MimeBody> pBody = (*iter);
         
         // Create a temporary filename.
         sLongFilename.Format(_T("%s\\%s.tmp"), IniFileSettings::Instance()->GetTempDirectory(), GUIDCreator::GetGUID() );
         pBody->WriteToFile(sLongFilename);

         VirusScanningResult result = _ScanFile(sLongFilename);
         if (result.GetVirusFound())
         {
            virusName = result.GetDetails();
            FileUtilities::DeleteFile(sLongFilename);
            return true;
         }

         FileUtilities::DeleteFile(sLongFilename);
         iter++;
      }

      return false;
   }
 void 
 SpamAssassinClient::OnCouldNotConnect(const AnsiString &sErrorDescription)
 {
    String logMessage;
    logMessage.Format(_T("Failed to connect to SpamAssassin. Session %d"), GetSessionID());
    LOG_DEBUG(logMessage);
 }
Example #20
0
void LogFile::LogMessage(const String& message, const ELogMessageLevel& logMessageLevel, const String& source)
{
	String buffer;

	buffer.Format("%s", (logMessageLevel==HIGH) ? "HIGH: " : (logMessageLevel==NORMAL) ? "" : "");
	buffer += message + '\n';

#if PLATFORM == PLATFORM_WINDOWS
	OutputDebugString(buffer.GetReadPtr());
#endif

	if (IsOpen())
	{
		Write((void*)buffer.GetReadPtr(), buffer.GetLength());
		Flush();
	}
/*
	// Write time into log
	//struct tm *pTime;
	//time_t ctTime; time(&ctTime);
	//pTime = gmtime( &ctTime );
	if(logMessageLevel == Log::HIGH)
		*this<<"HIGH: ";

	*this<<source;
	*this<<": ";
	*this<<message;*/
}
Example #21
0
static ActionStatus TryCallOutprocClientUsingVMMON(KDClientCommand cmd, unsigned PID, LPWSTR lpStringResult, size_t StringSize, ULONGLONG *pResult)
{
	unsigned pidCurrent = GetCurrentProcessId();
	String virtualCmdLine;
	virtualCmdLine.Format(_T("rundll32 KdClient32To64Entry %d %d %d"), pidCurrent, cmd, PID);

	PipeMessage msg = {0,};
	DWORD dwDone = 0;

	if (lpStringResult)
		lpStringResult[0] = 0;

	if (!CallNamedPipe(WOW64APIProvider::sIsWow64Process() ? tszVVMONCommandPipe64 : tszVVMONCommandPipe32,
				  (LPVOID)virtualCmdLine.c_str(),
				  virtualCmdLine.SizeInBytes(true),
				  &msg,
				  sizeof(msg),
				  &dwDone,
				  1000))
		 return MAKE_STATUS(ActionStatus::FailFromLastError());

	if (dwDone != sizeof(msg))
		return MAKE_STATUS(UnknownError);

	if (lpStringResult)
		wcsncpy(lpStringResult, msg.wszStringResult, min(StringSize, __countof(msg.wszStringResult)));

	if (pResult)
		*pResult = msg.LongResult;

	return MAKE_STATUS(Success);
}
Example #22
0
   bool 
   Events::FireOnDeliveryStart(std::shared_ptr<Message> pMessage)
   {
      if (!Configuration::Instance()->GetUseScriptServer())
         return true;

      std::shared_ptr<ScriptObjectContainer> pContainer = std::shared_ptr<ScriptObjectContainer>(new ScriptObjectContainer);
      std::shared_ptr<Result> pResult = std::shared_ptr<Result>(new Result);
      pContainer->AddObject("HMAILSERVER_MESSAGE", pMessage, ScriptObject::OTMessage);
      pContainer->AddObject("Result", pResult, ScriptObject::OTResult);
      String sEventCaller = "OnDeliveryStart(HMAILSERVER_MESSAGE)";
      ScriptServer::Instance()->FireEvent(ScriptServer::EventOnDeliveryStart, sEventCaller, pContainer);

      switch (pResult->GetValue())
      {
      case 1:
         {
            String sMessage;
            sMessage.Format(_T("SMTPDeliverer - Message %I64d: ")
               _T("Message deleted. Action was taken by script subscribing to OnDeliveryStart."),
               pMessage->GetID());

            LOG_APPLICATION(sMessage);

            PersistentMessage::DeleteObject(pMessage);             

            return false;
         }
      }

      return true;
   }
   void
   IMAPFolderContainer::SetFolderNeedRefresh(__int64 AccountID, __int64 lMailBox)
   {
      CriticalSectionScope scope(m_hFetchListCriticalSection);

      shared_ptr<IMAPFolder> pFolder;
      if (AccountID == 0)
      {
         // Get the public folder.
         pFolder = GetPublicFolders()->GetItemByDBIDRecursive(lMailBox);
      }
      else
      {
         std::map<__int64, shared_ptr<HM::IMAPFolders> >::iterator iterFolder = m_mapFolders.find(AccountID); 

         if (iterFolder == m_mapFolders.end())
            return;

         pFolder = (*iterFolder).second->GetItemByDBIDRecursive(lMailBox);
      }

      if (!pFolder)
      {
         String sErrorMessage;
         sErrorMessage.Format(_T("Folder could not be fetched. Account: %d, Folder: %d"), AccountID, lMailBox);
         ErrorManager::Instance()->ReportError(ErrorManager::Medium, 4214, "IMAPFolderContainer::SetFolderNeedRefresh", sErrorMessage);

         return;
      }

      pFolder->SetFolderNeedsRefresh();
   }
   bool
   PersistentRouteAddress::SaveObject(shared_ptr<RouteAddress> pRA)
   {

      SQLStatement oStatement;
      oStatement.AddColumnInt64("routeaddressrouteid", pRA->GetRouteID());
      oStatement.AddColumn("routeaddressaddress", pRA->GetAddress());

      oStatement.SetTable("hm_routeaddresses");

      if (pRA->GetID() == 0)
      {
         oStatement.SetStatementType(SQLStatement::STInsert);
         oStatement.SetIdentityColumn("routeaddressid");
      }
      else
      {
         oStatement.SetStatementType(SQLStatement::STUpdate);

         String sWhere;
         sWhere.Format(_T("routeaddressid = %I64d"), pRA->GetID());
         oStatement.SetWhereClause(sWhere);
      }

      bool bNewObject = pRA->GetID() == 0;

      // Save and fetch ID
      __int64 iDBID = 0;
      bool bRetVal = Application::Instance()->GetDBManager()->Execute(oStatement, bNewObject ? &iDBID : 0);
      if (bRetVal && bNewObject)
         pRA->SetID((int) iDBID);

      return bRetVal;
   }
   void 
   IOCPQueueWorkerTask::DoWork()
   {
      bool continueProcess = true;
      while (continueProcess)
      {
         try
         {
            io_service_.run();

            continueProcess = false;
         }
         catch (thread_interrupted const&)
         {
            
            return;
         }
         catch (boost::system::system_error error)
         {
            String sErrorMessage;
            sErrorMessage.Format(_T("An error occured while handling asynchronous requests. Error number: %d, Description: %s"), error.code().value(), String(error.what()));
            
            ErrorManager::Instance()->ReportError(ErrorManager::High, 4208, "IOCPQueueWorkerTask::DoWork", sErrorMessage);
         }
         catch (std::exception const& e)
         {
            String sErrorMessage = Formatter::Format("An unknown error occured while handling asynchronous requests. Error number: {0}", e.what());
            ErrorManager::Instance()->ReportError(ErrorManager::High, 4208, "IOCPQueueWorkerTask::DoWork", sErrorMessage);
         }
         catch (...)
         {
            ErrorManager::Instance()->ReportError(ErrorManager::High, 4208, "IOCPQueueWorkerTask::DoWork", "An unknown error occured while handling asynchronous requests.");
         }
      }
   }
Example #26
0
void
Network::OnTransactionAborted (HttpSession &httpSession, HttpTransaction &httpTransaction, result r) {
	AppLogDebug("Transaction Aborted");
	String res;
	res.Format(128, L"Cordova.callbacks['%S'].fail({code:%d,message:'%s'});", callbackId.GetPointer(), r, GetErrorMessage(r));
	AppLogDebug("%S", res.GetPointer());
	pWeb->EvaluateJavascriptN(res);
}
Example #27
0
String & String::Prepend(float f)
{
	String string;
	string.Allocate(64);
	string.Format("%g",f);
	return Prepend(string);

}
Example #28
0
String & String::Replace(float f)
{
	String string;
	string.Allocate(64);
	string.Format("%g",f);
	return Replace(string);

}
Example #29
0
String & String::Prepend(double d)
{
	String string;
	string.Allocate(512);
	string.Format("%f",d);
	return Prepend(string);

}
Example #30
0
String & String::Replace(double d)
{
	String string;
	string.Allocate(512);
	string.Format("%f",d);
	return Replace(string);

}