void DownloadProgressView::UpdateProgress( off_t nBytesReceived )
{
    double vBytesPerSec = double(nBytesReceived) / (double(get_system_time() - m_nStartTime) / 1000000.0);

    os::String cSpeedStr;
    if ( vBytesPerSec < 1024.0 ) {
	cSpeedStr.Format( "%.2f bytes/s", vBytesPerSec );
    } else {
	cSpeedStr.Format( "%.2f KB/s", vBytesPerSec / 1024.0 );
    }
    m_pcStatusView->SetText( 2, cSpeedStr );
    if ( m_nTotalSize != -1 ) {
	int nETA = int(double(m_nTotalSize - nBytesReceived) / vBytesPerSec);
	String cETA;
	if ( nETA < 60 ) {
	    cETA.Format( "%02d seconds", nETA );
	} else if ( nETA < 60*60 ) {
	    cETA.Format( "%d:%02d minutes", nETA/60, nETA % 60 );
	} else {
	    int nHours = nETA / (60*60);
	    nETA -= nHours * 60*60;
	    cETA.Format( "%d:%02d:%02d hours", nHours, nETA/60, nETA % 60 );
	}
	m_pcStatusView->SetText( 1, String().Format( "%s / %s (ETA: %s)",
						     get_size_str( nBytesReceived ).c_str(),
						     get_size_str( m_nTotalSize ).c_str(),
						     cETA.c_str() ) );
	m_pcProgressBar->SetProgress( double(nBytesReceived) / double(m_nTotalSize) );
    } else {
	m_pcStatusView->SetText( 1, get_size_str( nBytesReceived ).c_str() );
    }
    GetRoot()->Layout();
}
Example #2
0
String
FormatArgument::GetValue()
{
    String result;

    switch (_type)
    {
    case TypeUnicodeString:
        result = _unicodeStringValue;
        break;
    case TypeAnsiString:
        result = String(_ansiStringValue);
        break;
    case TypeNumber:
        result.Format(_T("%I64d"), _numericValue);
        break;
    case TypeUnsignedNumber:
        result.Format(_T("%I64u"), _unsignedNumericValue);
        break;
    case TypeBoolean:
        if (_boolValue)
            result = "True";
        else
            result = "False";
        break;
    default:
        assert(0);
    }

    return result;
}
   bool
   IniFileSettings::CheckSettings(String &sErrorMessage)
   {
      String sIniFile = GetInitializationFile();

      String sLog;
      sLog.Format(_T("Configuration::CheckSettings - %s"), sIniFile.c_str());
      LOG_DEBUG(sLog);

      switch (GetDatabaseType())
      {
      case HM::DatabaseSettings::TypeMSSQLCompactEdition:
         {
            if (database_name_.IsEmpty())
            {
               sErrorMessage.Format(_T("The setting Database in the section Database could not be read from %s"), sIniFile.c_str());
               return false;
            }
            break;
         }
      default:
         {
            if (database_server_.IsEmpty())
            {
               sErrorMessage.Format(_T("The setting Server in the section Database could not be read from %s"), sIniFile.c_str());
               return false;
            }
            break;
         }
      }


      return true;
   }
Example #4
0
void
Accelerometer::GetLastAcceleration() {
	String res;
	res.Format(256, L"PhoneGap.callbacks['%S'].success({x:%f,y:%f,z:%f,timestamp:%d});", callbackId.GetPointer(), x, y, z, timestamp);
	pWeb->EvaluateJavascriptN(res);

	res.Clear();
	res.Format(256, L"navigator.accelerometer.lastAcceleration = new Acceleration(%f,%f,%f,%d});", x, y, z, timestamp);
	pWeb->EvaluateJavascriptN(res);
}
Example #5
0
 String 
 StringParser::IntToString(__int64 lTheInt)
 {
    String sRetVal;
    sRetVal.Format(_T("%I64d"), lTheInt);
    return sRetVal;
 }
Example #6
0
 String
 FileUtilities::GetTempFileName()
 {
    String sTmpFile;
    sTmpFile.Format(_T("%s\\%s.tmp"), IniFileSettings::Instance()->GetTempDirectory(), GUIDCreator::GetGUID() );      
    return sTmpFile;
 }
Example #7
0
LRESULT CLobbyServerdlg::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	DlgResize_Init();
	m_serverlist.SubclassWindow(GetDlgItem(IDC_LIST1));
	m_serverlist.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);
	//m_serverlist.Create(m_hWnd, rcDefault, NULL);

	// TODO: Add your message handler code here and/or call default
	CListViewCtrl list = GetDlgItem(IDC_LIST1);
	list.InsertColumn(0, L"PSUID");
	list.InsertColumn(1, L"ServerType");
	list.InsertColumn(2, L"ServerVersion");


	for(_dword a=0; a<m_servers.Number(); a++)
	{
		stIP_LobbyNode & node = m_servers[a];
		list.InsertItem(a, ClientCommon::PSUID2Str(node.ServerID));
		list.SetItemText(a, 1, ClientCommon::GetServerDespByType(node.ServerType));
		String s;
		s.Format(L"%d", node.ServerVer);
		list.SetItemText(a, 2, s);
		
	}


//	list.SetRedraw(FALSE);
	gResizeList(list);
	
//	list.SetRedraw(TRUE);

	CenterWindow(GetParent());

	return TRUE;
}
Example #8
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;
}
Example #9
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");
    }
}
   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 #11
0
void
Accelerometer::OnDataReceived(SensorType sensorType, SensorData& sensorData, result r) {

	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_TIMESTAMP, timestamp);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_X, x);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Y, y);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Z, z);

	AppLogDebug("x: %f, y: %f, z: %f timestamp: %d", x, y, z, timestamp);

	String res;
	res.Format(256, L"PhoneGap.callbacks['%S'].success({x:%f,y:%f,z:%f,timestamp:%d});", callbackId.GetPointer(), x, y, z, timestamp);
	pWeb->EvaluateJavascriptN(res);

	res.Clear();
	res.Format(256, L"navigator.accelerometer.lastAcceleration = new Acceleration(%f,%f,%f,%d});", x, y, z, timestamp);
	pWeb->EvaluateJavascriptN(res);
}
Example #12
0
   void 
   Domains::Refresh(__int64 iDomainID)
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Reads a specific domain from the database.
   //---------------------------------------------------------------------------()
   {
      String sSQL;
      sSQL.Format(_T("select * from hm_domains where domainid = %I64d"), iDomainID);

      DBLoad_(sSQL);
   }
Example #13
0
   void 
   GroupMembers::Refresh()
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Reads all group members from the database
   //---------------------------------------------------------------------------()
   {
      String sSQL;
      sSQL.Format(_T("select * from hm_group_members where membergroupid = %I64d order by memberid asc"), m_iGroupID);

      _DBLoad(sSQL);      
   }
Example #14
0
String
Application::GetVersion() const
//---------------------------------------------------------------------------()
// DESCRIPTION:
// Returns the version of this application.
//---------------------------------------------------------------------------()
{
    String sVersion;
    sVersion.Format(_T("%s %s"), m_sProdName, m_sVersion);

    return sVersion;
}
Example #15
0
/** \brief Create and display icons for each of the RemoteNodes. in pacNodes.
 * This sets the remote view contents and updates the layout when necessary.
 * It also gets the initial path the first time it is called.
 *
 * \todo Perform periodic layouts while downloading large dirlisting.
 * \todo Display file sizes in a human readable format?
 * \todo Move the entry path stuff somewhere else?
 *
 * \param pacNodes List of RemoteNodes that should be updated for the remote view contents.
 * \param bInitial Set this to true if this is the first of several messages and we should clear the iconview first.
 * \param bFinal Set this to true if this is the last of the directory listing. and should Layout() when done.
 */
void RemoteIconView::SetContents( std::vector< RemoteNode >* pacNodes, bool bInitial, bool bFinal )
{
	/* If we haven't yet got the entry path, get it now. */
	if( m_zPath == "" ) {	/* \todo Is it possible that GetEntryPath() could be "" ? */
		if( m_pcServer->GetEntryPath() != "" ) {
			m_zPath = m_pcServer->GetEntryPath();

			if( m_pcDirChangedMsg ) {
				Message cTmp = *m_pcDirChangedMsg;
				cTmp.AddString( "file/path", m_zPath );
				Invoke( &cTmp );
			}
		} else {
			DEBUG( "RemoteView: GetEntryPath() is empty.\n" );
		}
	}
	
	if( bInitial ) Clear();	/* Remove all icons */

	HideMessage();

	int nCount = pacNodes->size();
//	DEBUG( "RemoteIconView: Dirlisting fragment contains %i nodes; %s initial, %sfinal\n", nCount, bInitial?"":"not ", bFinal?"":"not " );

	for( int i = 0; i < nCount; i++ ) {
		RemoteNode cNode = (*pacNodes)[i];
//		DEBUG( "  '%s', %s, size %i, permissions %i\n", cNode.GetName().c_str(), (cNode.IsDir() ? "dir" : "file"), cNode.GetSize(), cNode.GetPermissions() );

		Image* pcImage = GetNodeImage( &cNode, (GetView() == VIEW_LIST || GetView() == VIEW_DETAILS) );
		RemoteIconData* pcData = new RemoteIconData;
		pcData->m_cNode = cNode;

		uint nIndex = AddIcon( pcImage, pcData );
		AddIconString( nIndex, cNode.GetName() );

		String zTmp;
		if( cNode.IsDir() ) {
			zTmp = "<Dir>";
		} else {
			zTmp.Format( "%li", cNode.GetSize() );
		}
		AddIconString( nIndex, zTmp );
		
		AddIconString( nIndex, cNode.GetTimestamp().GetDate() );
	}
	
	// When this is the last of the directory listing, reset the update flag.
	if( bFinal ) {
		m_bUpdatePending = false;
	}
	
	Layout();
}
bool
PersistentLogonFailure::ClearOldFailures(int olderThanMinutes)
{
    String whereClause;
    whereClause.Format(_T("failuretime < %s"), SQLStatement::GetCurrentTimestampPlusMinutes(-olderThanMinutes));

    SQLStatement statement;
    statement.SetStatementType(SQLStatement::STDelete);
    statement.SetWhereClause(whereClause);
    statement.SetTable("hm_logon_failures");

    return Application::Instance()->GetDBManager()->Execute(statement);

}
Example #17
0
bool
POP3Connection::_ProtocolLIST(const String &sParameter)
{
    if (!_account)
    {
        _SendData("-ERR Message list not loaded");
        return true;
    }

    String sResponse;

    if (sParameter.IsEmpty())
    {
        int iMessageCount = 0;
        __int64 iTotalBytes = 0;
        _GetMailboxContents(iMessageCount, iTotalBytes);

        // preallocate memory to speed up a bit.
        sResponse.reserve(iMessageCount * 10);

        sResponse.Format(_T("+OK %d messages (%I64d octets)"), iMessageCount, iTotalBytes);
        _SendData(sResponse);


        sResponse = "";
        String sRow;

        int index = 0;
        boost_foreach(shared_ptr<Message> pMessage, _messages)
        {
            index++;
            if (!pMessage->GetFlagDeleted())
            {
                sRow.Format(_T("%d %d\r\n"), index, pMessage->GetSize());
                sResponse.append(sRow);
            }
        }
   bool 
   PersistentRoute::SaveObject(shared_ptr<Route> pRoute, String &sErrorMessage, PersistenceMode mode)
   {
      if (!PreSaveLimitationsCheck::CheckLimitations(mode, pRoute, sErrorMessage))
         return false;

      SQLStatement oStatement;
      
      oStatement.SetTable("hm_routes");

      oStatement.AddColumn("routedomainname", pRoute->DomainName());
      oStatement.AddColumn("routedescription", pRoute->GetDescription());
      oStatement.AddColumn("routetargetsmthost", pRoute->TargetSMTPHost());
      oStatement.AddColumn("routetargetsmtport", pRoute->TargetSMTPPort());
      oStatement.AddColumn("routenooftries", pRoute->NumberOfTries());
      oStatement.AddColumn("routeminutesbetweentry", pRoute->MinutesBetweenTry());
      oStatement.AddColumn("routealladdresses", pRoute->ToAllAddresses() ? 1 : 0);

      oStatement.AddColumn("routeuseauthentication", pRoute->GetRelayerRequiresAuth() ? 1 : 0);
      oStatement.AddColumn("routeauthenticationusername", pRoute->GetRelayerAuthUsername());
      oStatement.AddColumn("routeauthenticationpassword", Crypt::Instance()->EnCrypt(pRoute->GetRelayerAuthPassword(), Crypt::ETBlowFish));
      oStatement.AddColumn("routetreatsecurityaslocal", pRoute->GetTreatRecipientAsLocalDomain() ? 1 : 0);
      oStatement.AddColumn("routetreatsenderaslocaldomain", pRoute->GetTreatSenderAsLocalDomain() ? 1 : 0);
      oStatement.AddColumn("routeconnectionsecurity", pRoute->GetConnectionSecurity() );

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

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

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

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

      return true;
   }
Example #19
0
   bool
   FileUtilities::Move(const String &sFrom, const String &sTo, bool overwrite)
   {
      int iNumberOfTries = 0;
      const int iMaxNumberOfTries = 5;

      const int maxRecursions = 10000;
      for (int i = 0; i < maxRecursions; i++)
      {
         if (overwrite)
         {
            if (::MoveFileEx(sFrom, sTo, MOVEFILE_REPLACE_EXISTING) != 0)
            {
               return true;
            }
         }
         else
         {
            if (::MoveFile(sFrom, sTo) != 0)
            {
               //Copy OK
               return true;
            }
         }

         iNumberOfTries ++;

         // We failed to delete the file. 

         if (iNumberOfTries >= iMaxNumberOfTries)
         {
            // We still couldn't move the file. Lets give up and report in windows event log and hMailServer application log.
            int iLastError = ::GetLastError();

            String sErrorMessage;
            sErrorMessage.Format(_T("Could not move the file %s to %s. Tried 5 times without success. Windows eror code: %d (%s)"), sFrom, sTo, iLastError, Dictionary::GetWindowsErrorDescription(iLastError));
            ErrorManager::Instance()->ReportError(ErrorManager::High, 5049, "File::Normal", sErrorMessage);

            return false;
         }

         // Some other process must have locked the file.
         Sleep(250);
      }

      assert(0); // if we get here, something is really strange...
      return false;
   }
Example #20
0
   bool
   FileUtilities::CreateDirectory(const String &sName)
   {
      int iNumberOfTries = 0;
      const int iMaxNumberOfTries = 5;

      int maxRecursions = 10000;
      for (int i = 0; i < maxRecursions; i++)
      {
         if (::CreateDirectory(sName, 0) != 0)
         {
            // Create Directory OK
            return true;
         }

         int iWinErr = ::GetLastError();

         if (iWinErr == ERROR_ALREADY_EXISTS)
         {
            // Create directory failed, because the directory exists. 
            // That's good enough for us.

            return true;
         }

         iNumberOfTries ++;

         // We failed to delete the file. 

         if (iNumberOfTries >= iMaxNumberOfTries)
         {
            // We still couldn't copy the file. Lets give up and report in windows event log and hMailServer application log.
            String sErrorMessage;
            sErrorMessage.Format(_T("Could not create the directory %s. Tried 5 times without success. Windows error code: %d (%s)"), sName, iWinErr, Dictionary::GetWindowsErrorDescription(iWinErr));

            ErrorManager::Instance()->ReportError(ErrorManager::Medium, 5050, "File::CreateDirectory", sErrorMessage);
            return false;
         }

         // Some other process must have locked the file.
         Sleep(250);

      }

      assert(0);
      return false;
   }
bool
PersistentLogonFailure::ClearFailuresByIP(const IPAddress &ipaddress)
{
    IPAddressSQLHelper helper;

    String whereClause;
    whereClause.Format(_T("ipaddress1 %s and ipaddress2 %s"),
                       String(helper.GetAddress1Equals(ipaddress)),
                       String(helper.GetAddress2Equals(ipaddress)));

    SQLStatement statement;
    statement.SetStatementType(SQLStatement::STDelete);
    statement.SetWhereClause(whereClause);
    statement.SetTable("hm_logon_failures");

    return Application::Instance()->GetDBManager()->Execute(statement);
}
Example #22
0
   bool
   FileUtilities::Copy(const String &sFrom, const String &sTo, bool bCreateMissingDirectories)
   {
      int iNumberOfTries = 0;
      const int iMaxNumberOfTries = 5;

      if (bCreateMissingDirectories)
      {
         String sToPath = sTo.Mid(0, sTo.ReverseFind(_T("\\")));
         CreateDirectoryRecursive(sToPath);
      }


      const int maxRecursions = 10000;
      for (int i = 0; i < maxRecursions; i++)
      {
         // Use classic api to copy the file
         if (::CopyFile(sFrom, sTo, FALSE) != 0)
         {
            //Copy OK
            return true;
         }

         iNumberOfTries ++;

         // We failed to delete the file. 

         if (iNumberOfTries >= iMaxNumberOfTries)
         {
            // We still couldn't copy the file. Lets give up and report in windows event log and hMailServer application log
            int iLastError = ::GetLastError();

            String sErrorMessage;
            sErrorMessage.Format(_T("Could not copy the file %s to %s. Tried 5 times without success. Windows eror code: %d (%s)"), sFrom, sTo, iLastError, Dictionary::GetWindowsErrorDescription(iLastError));
            ErrorManager::Instance()->ReportError(ErrorManager::High, 5048, "File::Copy", sErrorMessage);
            return false;
         }

         // Some other process must have locked the file.
         Sleep(1000);
      }

      assert(0); // if we get here, something is really strange...
      return false;
   }
Example #23
0
   String 
   Domains::GetNames()
   {
      bool first = true;
      String result;
      boost_foreach(shared_ptr<Domain> domain, vecObjects)
      {
         if (first)
            first = false;

         String append;
         append.Format(_T("%I64d\t%s\t%d\r\n"), domain->GetID(), domain->GetName(), domain->GetIsActive() ? 1 :0);

         result += append;
      }

      return result;
   }
Example #24
0
   bool
   FileUtilities::DeleteFile(const String &FileName)
   {
      int iNumberOfTries = 0;
      const int iMaxNumberOfTries = 5;

      const int FILE_NOT_FOUND = 2;
      const int PATH_NOT_FOUND = 3;

      const int maxRecursions = 10000;
      for (int i = 0; i < maxRecursions; i++)
      {
         AnsiString sFilename = FileName;
         if (remove(sFilename) != -1)
            return true;

         int iLastError = ::GetLastError();
         if (iLastError == FILE_NOT_FOUND || iLastError == PATH_NOT_FOUND )
         {
            // We could not delete the file. But it doesn't exist, so it doens't matter.
            return true;
         }

         iNumberOfTries ++;

         // We failed to delete the file. 

         if (iNumberOfTries >= iMaxNumberOfTries)
         {
            // We still couldn't delete the file. Lets give up and report in windows event log.
            String sErrorMessage;
            sErrorMessage.Format(_T("Could not delete the file %s. Tried 5 times without success. Windows error code: %d (%s)"), FileName, iLastError, Dictionary::GetWindowsErrorDescription(iLastError));

            ErrorManager::Instance()->ReportError(ErrorManager::High, 5047, "File::DeleteFile", sErrorMessage);
            return false;
         }

         // Some other process must have locked the file.
         Sleep(1000);
      }

      return false;
   }
   bool
   PersistentDistributionList::SaveObject(std::shared_ptr<DistributionList> pDistList, String &sErrorMessage, PersistenceMode mode)
   {
      if (!PreSaveLimitationsCheck::CheckLimitations(mode, pDistList, sErrorMessage))
         return false;

      SQLStatement oStatement;
      oStatement.SetTable("hm_distributionlists");

      oStatement.AddColumnInt64("distributionlistdomainid", pDistList->GetDomainID());
      oStatement.AddColumn("distributionlistenabled", pDistList->GetActive() ? 1 : 0);
      oStatement.AddColumn("distributionlistaddress", pDistList->GetAddress());
      oStatement.AddColumn("distributionlistrequireauth", pDistList->GetRequireAuth() ? 1 : 0);
      oStatement.AddColumn("distributionlistrequireaddress", pDistList->GetRequireAddress());
      oStatement.AddColumn("distributionlistmode", pDistList->GetListMode());

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

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

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

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

      Cache<DistributionList>::Instance()->RemoveObject(pDistList);

      return bRetVal;
   }
int
PersistentLogonFailure::GetCurrrentFailureCount(const IPAddress &ipaddress)
{
    IPAddressSQLHelper helper;

    String sql;
    sql.Format(_T("select count(*) as c from hm_logon_failures where ipaddress1 %s and ipaddress2 %s"),
               String(helper.GetAddress1Equals(ipaddress)),
               String(helper.GetAddress2Equals(ipaddress)));

    SQLCommand command(sql);

    shared_ptr<DALRecordset> pRS = Application::Instance()->GetDBManager()->OpenRecordset(command);
    if (!pRS)
        return 0;

    long count = pRS->GetLongValue("c");

    return count;
}
Example #27
0
bool
Accelerometer::StartSensor(void) {
	result r = E_SUCCESS;

	if(__sensorMgr.IsAvailable(SENSOR_TYPE_ACCELERATION)) {
		r = __sensorMgr.AddSensorListener(*this, SENSOR_TYPE_ACCELERATION, 50, true);
		if(IsFailed(r)) {
			return false;
		}
	} else {
		AppLogException("Acceleration sensor is not available");
		String res;
		res.Format(256, L"PhoneGap.callbacks['%S'].fail({message:'Acceleration sensor is not available',code:'001'});");
		pWeb->EvaluateJavascriptN(res);
		return false;
	}
	started = true;
	AppLogDebug("Start Watching Sensor");
	return true;
}
   bool
   PersistentRuleCriteria::SaveObject(shared_ptr<RuleCriteria> pRuleCriteria)
   {
      SQLStatement oStatement;
      oStatement.SetTable("hm_rule_criterias");

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

      if (bNewObject)
      {
         oStatement.SetStatementType(SQLStatement::STInsert);
         oStatement.SetIdentityColumn("criteriaid");
      }
      else
      {
         oStatement.SetStatementType(SQLStatement::STUpdate);
         
         String sWhere;
         sWhere.Format(_T("criteriaid = %I64d"), pRuleCriteria->GetID());
         oStatement.SetWhereClause(sWhere);

      }

      oStatement.AddColumnInt64("criteriaruleid", pRuleCriteria->GetRuleID());
      oStatement.AddColumn("criteriausepredefined", pRuleCriteria->GetUsePredefined());
      oStatement.AddColumn("criteriapredefinedfield", pRuleCriteria->GetPredefinedField());
      oStatement.AddColumn("criteriaheadername", pRuleCriteria->GetHeaderField());
      oStatement.AddColumn("criteriamatchtype", pRuleCriteria->GetMatchType());
      oStatement.AddColumn("criteriamatchvalue", pRuleCriteria->GetMatchValue());

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

      return bRetVal;

   }
Example #29
0
bool
Application::OnDatabaseConnected(String &sErrorMessage)
{
    LOG_DEBUG("Application::OnDatabaseConnected()");

    int iDBVersion = GetDBManager()->GetCurrentDatabaseVersion();

    if (iDBVersion == 0)
    {
        sErrorMessage = "Database version could not be detected.";
        m_sLastConnectErrorMessage = sErrorMessage;
        return false;
    }

    if (iDBVersion < Configuration::Instance()->GetRequiredDBVersion()
            || iDBVersion > Configuration::Instance()->GetRequiredDBVersion())
    {
        String sErrorMessage;

        if (iDBVersion > Configuration::Instance()->GetRequiredDBVersion())
            sErrorMessage = "The database is too new for this version of hMailServer. Please upgrade hMailServer.";
        else
            sErrorMessage = "The database is too old for this version of hMailServer. Please run hMailServer Database updater (DBUpdater.exe) to upgrade it.";

        String sVersionInfo;
        sVersionInfo.Format(_T(" Database version: %d, Required database version: %d"), iDBVersion, Configuration::Instance()->GetRequiredDBVersion());

        sErrorMessage += sVersionInfo;

        m_sLastConnectErrorMessage = sErrorMessage;

        ErrorManager::Instance()->ReportError(ErrorManager::Critical, 5011, "Application::OnDatabaseConnected", sErrorMessage);

        return false;
    }

    LOG_DEBUG("Application::~OnDatabaseConnected() - E2");
    return true;
}
Example #30
0
void CSquirrel::RegisterFunction(String strFunctionName, SQFUNCTION pfnFunction, int iParameterCount, String strFunctionTemplate)
{
	// Push the function name onto the stack
	sq_pushstring(m_pVM, strFunctionName.Get(), -1);

	// Create a new function
	sq_newclosure(m_pVM, pfnFunction, 0);

	// Set the function parameter template and count
	if(iParameterCount != -1)
	{
		String strTypeMask;

		if(strFunctionTemplate.IsNotEmpty())
			strTypeMask.Format(".%s", strFunctionTemplate.Get());

		sq_setparamscheck(m_pVM, (iParameterCount + 1), strTypeMask.Get());
	}

	// Create a new slot
	sq_createslot(m_pVM, -3);
}