void CIRCSock::ReadLine(const CString& sData) { CString sLine = sData; sLine.TrimRight("\n\r"); DEBUG("(" << m_pUser->GetUserName() << ") IRC -> ZNC [" << sLine << "]"); MODULECALL(OnRaw(sLine), m_pUser, NULL, return); if (sLine.Equals("PING ", false, 5)) { // Generate a reply and don't forward this to any user, // we don't want any PING forwarded PutIRC("PONG " + sLine.substr(5)); return; } else if (sLine.Token(1).Equals("PONG")) { // Block PONGs, we already responded to the pings return; } else if (sLine.Equals("ERROR ", false, 6)) { //ERROR :Closing Link: nick[24.24.24.24] (Excess Flood) CString sError(sLine.substr(6)); if (sError.Left(1) == ":") { sError.LeftChomp(); } m_pUser->PutStatus("Error from Server [" + sError + "]"); return; } CString sCmd = sLine.Token(1); if ((sCmd.length() == 3) && (isdigit(sCmd[0])) && (isdigit(sCmd[1])) && (isdigit(sCmd[2]))) { CString sServer = sLine.Token(0); sServer.LeftChomp(); unsigned int uRaw = sCmd.ToUInt(); CString sNick = sLine.Token(2); CString sRest = sLine.Token(3, true); switch (uRaw) { case 1: { // :irc.server.com 001 nick :Welcome to the Internet Relay Network nick if (m_bAuthed && sServer == "irc.znc.in") { // m_bAuthed == true => we already received another 001 => we might be in a traffic loop m_pUser->PutStatus("ZNC seems to be connected to itself, disconnecting..."); Quit(); return; } m_pUser->SetIRCServer(sServer); SetTimeout(240, TMO_READ); // Now that we are connected, let nature take its course PutIRC("WHO " + sNick); m_bAuthed = true; m_pUser->PutStatus("Connected!"); vector<CClient*>& vClients = m_pUser->GetClients(); for (unsigned int a = 0; a < vClients.size(); a++) { CClient* pClient = vClients[a]; CString sClientNick = pClient->GetNick(false); if (!sClientNick.Equals(sNick)) { // If they connected with a nick that doesn't match the one we got on irc, then we need to update them pClient->PutClient(":" + sClientNick + "!" + m_Nick.GetIdent() + "@" + m_Nick.GetHost() + " NICK :" + sNick); } } SetNick(sNick); MODULECALL(OnIRCConnected(), m_pUser, NULL, ); m_pUser->ClearRawBuffer(); m_pUser->AddRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); CZNC::Get().ReleaseISpoof(); m_bISpoofReleased = true; break; } case 5: ParseISupport(sRest); m_pUser->UpdateExactRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 2: case 3: case 4: case 250: // highest connection count case 251: // user count case 252: // oper count case 254: // channel count case 255: // client count case 265: // local users case 266: // global users m_pUser->UpdateRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 305: m_pUser->SetIRCAway(false); break; case 306: m_pUser->SetIRCAway(true); break; case 324: { // MODE sRest.Trim(); CChan* pChan = m_pUser->FindChan(sRest.Token(0)); if (pChan) { pChan->SetModes(sRest.Token(1, true)); } } break; case 329: { sRest.Trim(); CChan* pChan = m_pUser->FindChan(sRest.Token(0)); if (pChan) { unsigned long ulDate = sLine.Token(4).ToULong(); pChan->SetCreationDate(ulDate); } } break; case 331: { // :irc.server.com 331 yournick #chan :No topic is set. CChan* pChan = m_pUser->FindChan(sLine.Token(3)); if (pChan) { pChan->SetTopic(""); } break; } case 332: { // :irc.server.com 332 yournick #chan :This is a topic CChan* pChan = m_pUser->FindChan(sLine.Token(3)); if (pChan) { CString sTopic = sLine.Token(4, true); sTopic.LeftChomp(); pChan->SetTopic(sTopic); } break; } case 333: { // :irc.server.com 333 yournick #chan setternick 1112320796 CChan* pChan = m_pUser->FindChan(sLine.Token(3)); if (pChan) { sNick = sLine.Token(4); unsigned long ulDate = sLine.Token(5).ToULong(); pChan->SetTopicOwner(sNick); pChan->SetTopicDate(ulDate); } break; } case 352: { // :irc.yourserver.com 352 yournick #chan ident theirhost.com irc.theirserver.com theirnick H :0 Real Name sServer = sLine.Token(0); sNick = sLine.Token(7); CString sIdent = sLine.Token(4); CString sHost = sLine.Token(5); sServer.LeftChomp(); if (sNick.Equals(GetNick())) { m_Nick.SetIdent(sIdent); m_Nick.SetHost(sHost); } m_pUser->SetIRCNick(m_Nick); m_pUser->SetIRCServer(sServer); const vector<CChan*>& vChans = m_pUser->GetChans(); for (unsigned int a = 0; a < vChans.size(); a++) { vChans[a]->OnWho(sNick, sIdent, sHost); } break; } case 353: { // NAMES sRest.Trim(); // Todo: allow for non @+= server msgs CChan* pChan = m_pUser->FindChan(sRest.Token(1)); // If we don't know that channel, some client might have // requested a /names for it and we really should forward this. if (pChan) { CString sNicks = sRest.Token(2, true); if (sNicks.Left(1) == ":") { sNicks.LeftChomp(); } pChan->AddNicks(sNicks); } ForwardRaw353(sLine); // We forwarded it already, so return return; } case 366: { // end of names list m_pUser->PutUser(sLine); // First send them the raw // :irc.server.com 366 nick #chan :End of /NAMES list. CChan* pChan = m_pUser->FindChan(sRest.Token(0)); if (pChan) { if (pChan->IsOn()) { // If we are the only one in the chan, set our default modes if (pChan->GetNickCount() == 1) { CString sModes = pChan->GetDefaultModes(); if (sModes.empty()) { sModes = m_pUser->GetDefaultChanModes(); } if (!sModes.empty()) { PutIRC("MODE " + pChan->GetName() + " " + sModes); } } } } return; // return so we don't send them the raw twice } case 375: // begin motd case 422: // MOTD File is missing m_pUser->ClearMotdBuffer(); case 372: // motd case 376: // end motd m_pUser->AddMotdBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 437: // :irc.server.net 437 * badnick :Nick/channel is temporarily unavailable // :irc.server.net 437 mynick badnick :Nick/channel is temporarily unavailable // :irc.server.net 437 mynick badnick :Cannot change nickname while banned on channel if (m_pUser->IsChan(sRest.Token(0)) || sNick != "*") break; case 432: // :irc.server.com 432 * nick :Erroneous Nickname: Illegal characters case 433: { CString sBadNick = sRest.Token(0); if (!m_bAuthed) { SendAltNick(sBadNick); return; } break; } case 451: // :irc.server.com 451 CAP :You have not registered // Servers that dont support CAP will give us this error, dont send it to the client if (sNick.Equals("CAP")) return; case 470: { // :irc.unreal.net 470 mynick [Link] #chan1 has become full, so you are automatically being transferred to the linked channel #chan2 // :mccaffrey.freenode.net 470 mynick #electronics ##electronics :Forwarding to another channel // freenode style numeric CChan* pChan = m_pUser->FindChan(sRest.Token(0)); if (!pChan) { // unreal style numeric pChan = m_pUser->FindChan(sRest.Token(1)); } if (pChan) { pChan->Disable(); m_pUser->PutStatus("Channel [" + pChan->GetName() + "] is linked to " "another channel and was thus disabled."); } break; } } } else {
/******************************************************************************* Function Name : bOpenReplayFile Input(s) : BOOL - TRUE if parsing is successful, FALSE otherwise Output : - Functionality : Load the replay file. Updates entries and CAN message list with the parsed content Member of : CReplayProcess Author(s) : Raja N Date Created : 16.7.2005 Modifications : Raja N on 26.07.2005, Implementwed code review comments *******************************************************************************/ BOOL CReplayProcess::bOpenReplayFile() { BOOL bReturn = TRUE; BOOL bModeMismatch = FALSE; CString omStrLine = ""; CString omStrTemp = ""; CHAR Line[500] = { 0 }; CString omStrMsgType = " "; std::ifstream omInReplayFile; int nBlockCounter = 0; // Clear string array m_omEntries.RemoveAll(); m_omMsgList.RemoveAll(); // Clear error message m_omStrError = ""; TRY { omInReplayFile.open( m_ouReplayFile.m_omStrFileName, std::ios::in ); if (!omInReplayFile.good()) { // Info file open error notification m_omStrError = defSTR_FILE_OPEN_ERROR; bReturn = FALSE ; } if(bReturn != FALSE) { // Read the file line by line. BOOL bModeFound = FALSE; BOOL bFileEndFlag = FALSE; BOOL bMsgModeFound = FALSE; BOOL bOldVersionFile = FALSE; BOOL bVersionFound = FALSE; BOOL bProtocolFound = FALSE; while ( bOldVersionFile == FALSE && (!omInReplayFile.eof()) && ( bMsgModeFound == FALSE || bModeFound == FALSE || bVersionFound == FALSE )) { omInReplayFile.getline( Line, sizeof(Line)); omStrLine = Line; omStrLine.TrimLeft(); omStrLine.TrimRight(); // Check if Protocol exists in the log file if( omStrLine.Find(defSTR_PROTOCOL_USED) != -1) { // If can related log file if( omStrLine.Find(defSTR_PROTOCOL_CAN) == -1) { m_omStrError = defSTR_LOG_PRTOCOL_MISMATCH; bReturn = FALSE ; bFileEndFlag = TRUE; } } // Version check if( omStrLine.Find(defSTR_BUSMASTER_VERSION_STRING) != -1 ) { bVersionFound = TRUE; int nPos = omStrLine.Find( defSTR_BUSMASTER_VERSION_STRING ); nPos += (int)strlen( defSTR_BUSMASTER_VERSION_STRING ); int nMajorVer = omStrLine[ nPos ] - '0'; if( nMajorVer < defLOG_FILE_MAJOR_VERSION_SUPPORTED ) { bOldVersionFile = TRUE; } } // set the mode of reply if( omStrLine.Find(HEX_MODE) == 0) { m_bReplayHexON = TRUE; bMsgModeFound = TRUE; } else if (omStrLine.Find(DEC_MODE) == 0) { m_bReplayHexON = FALSE; bMsgModeFound = TRUE; } if( omStrLine.Find(SYSTEM_MODE) == 0) { m_wLogReplayTimeMode= eSYSTEM_MODE; bModeFound = TRUE; } else if( omStrLine.Find(ABSOLUTE_MODE) == 0) { m_wLogReplayTimeMode= eABSOLUTE_MODE; bModeFound = TRUE; } else if( omStrLine.Find(RELATIVE_MODE) == 0) { m_wLogReplayTimeMode= eRELATIVE_MODE; bModeFound = TRUE; } } if( bOldVersionFile == TRUE ) { m_omStrError = defSTR_LOG_FILE_UNSUPPORTED; bReturn = FALSE ; bFileEndFlag = TRUE; } if( bReturn == TRUE && ( bModeFound == FALSE || bMsgModeFound == FALSE || bVersionFound == FALSE ) ) { m_omStrError = defINVALID_HEADER; bReturn = FALSE ; bFileEndFlag = TRUE; } while (! omInReplayFile.eof() && bFileEndFlag == FALSE ) { omInReplayFile.getline( Line, sizeof(Line)); omStrLine = Line; omStrLine.TrimLeft(); omStrLine.TrimRight(); // Exclude empty line, line with starting string // hash defined as DefSPL_LINE if( omStrLine.IsEmpty()==0 && omStrLine.Find(DefSPL_LINE) == -1 && omStrLine.Find(omStrMsgType) != -1) { // Apply Filtering STCANDATA sCanMsg; if( bGetMsgInfoFromMsgStr( omStrLine, &sCanMsg, m_bReplayHexON ) == TRUE ) { SFRAMEINFO_BASIC_CAN sBasicCanInfo; vFormatCANDataMsg(&sCanMsg, &sBasicCanInfo); EnterCriticalSection(&m_omCritSecFilter); BOOL bTobeBlocked = m_ouReplayFile.m_sFilterApplied.bToBeBlocked(sBasicCanInfo); LeaveCriticalSection(&m_omCritSecFilter); // Add it to the list based on filtering result //if( bTobeBlocked == FALSE ) //{ // bTobeBlocked = bMessageTobeBlocked( sBasicCanInfo ); //if(bTobeBlocked == FALSE) { m_omEntries.Add( omStrLine ); m_omMsgList.Add(sCanMsg ); } // } } } else if(! omStrLine.Compare(START_SESSION)) { bModeMismatch = bIsModeMismatch( omInReplayFile, m_bReplayHexON, m_wLogReplayTimeMode ); if(bModeMismatch == TRUE) { nBlockCounter++; BOOL bEndBlock = FALSE; CString omStrEndBlock = END_SESSION; while (! omInReplayFile.eof() && bEndBlock == FALSE) { omInReplayFile.getline( Line, sizeof(Line)); if( omStrEndBlock.Compare(Line) == 0) { bEndBlock = TRUE; } } } } }// while } } CATCH_ALL(pomException) { if(pomException != nullptr ) { CHAR scErrorMsg[255]; // Get the exception error message pomException->GetErrorMessage(scErrorMsg,sizeof(scErrorMsg)); m_omStrError = scErrorMsg; pomException->Delete(); } bReturn = FALSE; if( omInReplayFile.is_open() !=0) { omInReplayFile.close(); } } END_CATCH_ALL if(nBlockCounter >=1 ) { m_omStrError.Format( defSTR_MIXED_MODE_WARNING, nBlockCounter ); } // close the file if it open if( omInReplayFile.is_open() !=0 ) { omInReplayFile.close(); } return bReturn; }
void CVersionChecker::ProcessResponse() { int nDays = VERSIONCHECKER_FREQUENCY; CString strValue; if ( m_pResponse.Lookup( _T("Message"), strValue ) || m_pResponse.Lookup( _T("MessageBox"), strValue ) ) { m_sMessage = strValue; } if ( m_pResponse.Lookup( _T("Quote"), strValue ) ) { m_sQuote = strValue; theApp.WriteProfileString( _T("VersionCheck"), _T("Quote"), m_sQuote ); } if ( m_pResponse.Lookup( _T("SystemMsg"), strValue ) ) { for ( strValue += '\n' ; strValue.GetLength() ; ) { CString strLine = strValue.SpanExcluding( _T("\r\n") ); strValue = strValue.Mid( strLine.GetLength() + 1 ); if ( strLine.GetLength() ) theApp.Message( MSG_SYSTEM, strLine ); } } if ( m_pResponse.Lookup( _T("UpgradePrompt"), strValue ) ) { m_sUpgradePrompt = strValue; m_pResponse.Lookup( _T("UpgradeFile"), m_sUpgradeFile ); m_pResponse.Lookup( _T("UpgradeSHA1"), m_sUpgradeSHA1 ); m_pResponse.Lookup( _T("UpgradeTiger"), m_sUpgradeTiger ); m_pResponse.Lookup( _T("UpgradeSize"), m_sUpgradeSize ); m_pResponse.Lookup( _T("UpgradeSources"), m_sUpgradeSources ); m_pResponse.Lookup( _T("UpgradeVersion"), m_sUpgradeVersion ); // Old name if ( ! m_sUpgradeSHA1.GetLength() ) m_pResponse.Lookup( _T("UpgradeHash"), m_sUpgradeSHA1 ); theApp.WriteProfileString( _T("VersionCheck"), _T("UpgradePrompt"), m_sUpgradePrompt ); theApp.WriteProfileString( _T("VersionCheck"), _T("UpgradeFile"), m_sUpgradeFile ); theApp.WriteProfileString( _T("VersionCheck"), _T("UpgradeSHA1"), m_sUpgradeSHA1 ); theApp.WriteProfileString( _T("VersionCheck"), _T("UpgradeTiger"), m_sUpgradeTiger); theApp.WriteProfileString( _T("VersionCheck"), _T("UpgradeSize"), m_sUpgradeSize ); theApp.WriteProfileString( _T("VersionCheck"), _T("UpgradeSources"), m_sUpgradeSources ); theApp.WriteProfileString( _T("VersionCheck"), _T("UpgradeVersion"), m_sUpgradeVersion ); m_bUpgrade = TRUE; } else { theApp.WriteProfileString( _T("VersionCheck"), _T("UpgradePrompt"), _T("") ); m_bUpgrade = FALSE; } if ( m_pResponse.Lookup( _T("AddDiscovery"), strValue ) ) { strValue.TrimLeft(); strValue.TrimRight(); DiscoveryServices.Add( strValue, CDiscoveryService::dsWebCache ); } if ( m_pResponse.Lookup( _T("NextCheck"), strValue ) ) { _stscanf( strValue, _T("%lu"), &nDays ); } SetNextCheck( nDays ); PostMessage( m_hWndNotify, WM_VERSIONCHECK, 0, 0 ); }
BOOL CIfExpressEditorDlg::InitDlgCtrl() { if (!m_Express.m_LeftParam.strID.IsEmpty() && m_Express.m_LeftParam.strConst.IsEmpty()) { CString strText = m_Express.m_LeftParam.strParamFullPath; if (!m_Express.m_LeftParam.strArry.IsEmpty()) // 存在数组下标 { strText.TrimRight(m_Express.m_LeftParam.strArry); //将数组下标显示到专门的编辑框 m_EditLeftArry.ShowWindow(SW_SHOW); m_EditLeftArry.SetWindowText(m_Express.m_LeftParam.strArry); } else { m_EditLeftArry.ShowWindow(SW_HIDE); AdjustLeftEditSize(); } m_EditLeft.SetWindowText(strText); // 变参 GetDataFullPathByID(m_Express.m_LeftParam.strID,&m_pNodeLeft); //用于后面取数组维度,判断是否下标越界和常量类型的检测 GetCheckDataType(m_pNodeLeft); } else { m_EditLeft.SetWindowText(m_Express.m_LeftParam.strConst); // 常参 } if (!m_Express.m_RightParam.strID.IsEmpty() && m_Express.m_RightParam.strConst.IsEmpty()) { CString strText = m_Express.m_RightParam.strParamFullPath; if (!m_Express.m_RightParam.strArry.IsEmpty()) // 存在数组下标 { strText.TrimRight(m_Express.m_RightParam.strArry); //将数组下标显示到专门的编辑框 m_EditRightArry.ShowWindow(SW_SHOW); m_EditRightArry.SetWindowText(m_Express.m_RightParam.strArry); } else { m_EditRightArry.ShowWindow(SW_HIDE); AdjustRightEditSize(); } m_EditRight.SetWindowText(strText); // 变参 m_strLastRightEditParam = strText; m_ComboRightType.SetCurSel(TP_PARAM); m_iLastComboTypeSel = TP_PARAM; GetDataFullPathByID(m_Express.m_RightParam.strID,&m_pNodeRight); //用于后面取数组维度,判断是否下标越界 } else { if (m_iCheckType==DT_STRING) { ASSERT(m_Express.m_RightParam.strConst.GetLength()>=2); ASSERT(m_Express.m_RightParam.strConst.Left(1)=="\""); ASSERT(m_Express.m_RightParam.strConst.Right(1)=="\""); // 显示字符串类型的表达式时,左右引号不显示 m_Express.m_RightParam.strConst = m_Express.m_RightParam.strConst.Mid(1,m_Express.m_RightParam.strConst.GetLength()-2); /*m_Express.m_RightParam.strConst.Replace("\\\"","\"");*/ } m_EditRight.SetWindowText(m_Express.m_RightParam.strConst); // 常参 m_strLastRightEditConst = m_Express.m_RightParam.strConst; m_ComboRightType.SetCurSel(TP_CONST); m_iLastComboTypeSel = TP_CONST; m_EditRightArry.ShowWindow(SW_HIDE); AdjustRightEditSize(); m_EditRight.SetReadOnly(FALSE); GetCheckDataType(m_pNodeLeft); } if (m_Express.m_strIdExpress.IsEmpty()) { DeleteExpress(); } UpdateComboBoxSymbol(); int iCurSel = -1; int iCount = m_ComboSymbol.GetCount(); for (int i=0;i<iCount;i++) { CString strTextCombo; m_ComboSymbol.GetLBText(i,strTextCombo); if (strTextCombo.Compare(m_Express.m_strExpressSymbol)==0) { iCurSel = i; break; } } m_ComboSymbol.SetCurSel(iCurSel); m_EditLeftArry.SetMsgProWnd(GetSafeHwnd()); // 设计错误检测处理窗口为本对话框 m_EditRightArry.SetMsgProWnd(GetSafeHwnd()); m_EditRight.SetMsgProWnd(GetSafeHwnd()); return TRUE; }
void CFtpSettingsDialog::OnChangeDirectory() { INT nAccount = m_nCurrentAccount; CString szText; m_edtDirectory.GetWindowText( szText ); szText.TrimLeft(); szText.TrimRight(); m_pFtpAccounts[nAccount].m_szSubDirectory = szText; }
void runCmdAndResult(LPSTR argCmd, CString& argResult, bool IsReadResult) { /// 查看进程数 argResult.Empty(); CString strShowInfo; strShowInfo.Format(_T("runCmdAndResult begin argCmd=%s\r\n"), argCmd); XWriteEventLog(strShowInfo); CString strPath, strPath2; int nTimeOut = 6; // 一般情况是6秒 DWORD WaitTime = nTimeOut * 1000; CString argCmdStr = argCmd; if(argCmdStr.Find(_T("install")) != -1) { nTimeOut = 60; // 移动应用程序时,2兆以下是60秒。2兆以上按 y = x*1000 + 40*1000的公司计算TimeOut的毫秒数,其中x = z/1024*1024 + WaitTime = nTimeOut * 1000; CString TempPath = argCmdStr.Mid(argCmdStr.Find(_T("install"))+8); int Pos = 0; if( TempPath.Find( _T("-r")) != -1 ) { TempPath = TempPath.Mid( TempPath.Find("-r") + 2 ); } TempPath.TrimLeft(); TempPath.TrimRight(); if( TempPath.Find("\"") != -1 ) { TempPath=TempPath.Mid(TempPath.Find("\"")+1); TempPath=TempPath.Left(TempPath.Find("\"")); } XWriteEventLog(_T("[runCmdAndResult] intall Apk path=[%s]"),TempPath); HANDLE FileHandle = CreateFile(TempPath,GENERIC_WRITE|GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if(FileHandle == INVALID_HANDLE_VALUE) { WaitTime = nTimeOut*1000; } DWORD Size = GetFileSize(FileHandle,NULL); DWORD Time = Size / (1024*1024) + 1; if( Time > 2 ) { WaitTime = Time * 2000 + 40 * 1000; } CloseHandle(FileHandle); } else if(argCmdStr.Find(_T("pull")) != -1) { WaitTime = 20 * 1000; } else if(argCmdStr.Find(_T("forward")) != -1 || argCmdStr.Find(_T("shell am broadcast")) != -1) { WaitTime = 2 * 1000; } strPath2 = _T("\""); ::GetModuleFileName(NULL,strPath.GetBuffer(MAX_PATH),MAX_PATH); strPath.ReleaseBuffer(); strPath=strPath.Left(strPath.ReverseFind('\\')); if(strPath.Right(1)!='\\') { strPath+="\\"; strPath += "adb\\adb.exe"; strPath2 += strPath; strPath2 += _T("\""); strPath = strPath2; }else{ strShowInfo.Format(_T("runCmdAndResult Failed strPath=%s\r\n"), strPath); XWriteEventLog(strShowInfo); return; } // TODO: Add extra validation here SECURITY_ATTRIBUTES sa; HANDLE hRead,hWrite; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; //使用系统默认的安全描述符 sa.bInheritHandle = TRUE; //创建的进程继承句柄 if (!CreatePipe(&hRead,&hWrite,&sa,0)) //创建匿名管道 { XWriteEventLog(_T("runCmdAndResult CreatePipe Failed \r\n")); return ; } STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_ATTRIBUTES ai; ZeroMemory(&ai,sizeof(SECURITY_ATTRIBUTES)); ai.nLength = sizeof(ai); ai.bInheritHandle = TRUE; DWORD nFlag = PROCESS_TERMINATE ; ai.lpSecurityDescriptor = NULL; ZeroMemory(&si,sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.hStdError = hWrite; si.hStdOutput = hWrite; //新创建进程的标准输出连在写管道一端 si.wShowWindow = SW_HIDE; //隐藏窗口 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; CString strCmd = argCmd; strCmd.Mid(3,strCmd.GetLength()-3); int Pos=strCmd.Find(_T("adb")); if(Pos!= -1) strCmd=strCmd.Mid(Pos+3); strPath += strCmd; //tmp.Format("cmd /C %s",argCmd); //"adb devices" char cmdline[512] = {0}; sprintf(cmdline,"%s",strPath); HANDLE hOpenProcess ; if (!CreateProcess(NULL,cmdline,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) //创建子进程 { XWriteEventLog(_T("runCmdAndResult CreateProcess Failed \r\n")); return ; } CloseHandle(hWrite); //关闭管道句柄 DWORD dwExitCode; DWORD dwRet = WaitForSingleObject(pi.hProcess, WaitTime); AsyncReadPipe(hRead, argResult) ; if(argResult.Find(_T("daemon not running")) != -1) { dwRet = WaitForSingleObject(pi.hProcess, WaitTime); AsyncReadPipe(hRead, argResult) ; } //if(dwRet != WAIT_OBJECT_0 && !GetExitCodeProcess(pi.hProcess, &dwExitCode)) { if(dwRet == WAIT_TIMEOUT) { XWriteEventLog(_T("runCmdAndResult WaitForSingleObject TimeOut \r\n")); ::TerminateProcess(pi.hProcess,1); // KillAdb(); }else { XWriteEventLog(_T("runCmdAndResult WaitForSingleObject Others Error To KillAdb\r\n")); } } if(!IsReadResult) { CloseHandle(hRead); XWriteEventLog(_T("runCmdAndResult CloseHandle(hRead) and return \r\n")); return; } // SyncReadPipe(hRead, argResult) ; // XWriteEventLog(_T("runCmdAndResult return OK\n")); CloseHandle(hRead); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); }
// Check if an update is required // CAutoUpdater::ErrorType CAutoUpdater::CheckForUpdate() { if (!InternetOkay()) { return InternetConnectFailure; } bTransferSuccess = false; // First we must check the remote configuration file to see if an update is necessary CString URL = CString(UPDATE_CHECK_URL) + CString(LOCATION_UPDATE_FILE_CHECK); HINTERNET hSession = GetSession(URL); if (!hSession) { return InternetSessionFailure; } BYTE pBuf[TRANSFER_SIZE]; memset(pBuf, NULL, sizeof(pBuf)); bTransferSuccess = DownloadConfig(hSession, pBuf, TRANSFER_SIZE); InternetCloseHandle(hSession); if (!bTransferSuccess) { return ConfigDownloadFailure; } // Get the version number of our executable and compare to see if an update is needed CString executable = GetExecutable(); CString fileVersion = GetFileVersion(executable);\ if (fileVersion.IsEmpty()) { return NoExecutableVersion; } CString updateVersion = (char *) pBuf; if (CompareVersions(updateVersion, fileVersion) != 1) { return UpdateNotRequired; } // At this stage an update is required TCHAR path[MAX_PATH]; GetTempPath(MAX_PATH, path); CString directory = path; // Download the updated file /* TCHAR *pToken = strtok(updateVersion.GetBuffer(256),_T(".")); while(pToken!=NULL) { if(IsDigits(pToken[0])) URL.Insert(URL.GetLength(),pToken[0]); pToken = strtok(NULL, _T(".")); } */ updateVersion.TrimLeft(); updateVersion.TrimRight(); updateVersion.TrimRight(_T(".")); URL = CString(UPDATE_DOWNLOAD_URL) + updateVersion + CString("/") + CString(InstallerName) + CString(".exe"); updateVersion.ReleaseBuffer(); DBG_PRINT(URL); hSession = GetSession(URL); if (!hSession) { return InternetSessionFailure; } CAutoUpdateDlg autoupdate_dlg; int nResult = autoupdate_dlg.DoModal(); if (nResult==0) { AppConfig.autoupdate_disable=1; return UpdateNotComplete; } else if (nResult==2) { return UpdateNotComplete; } // Proceed with the update CString updateFileLocation = directory+InstallerName+CString(".exe"); download_update_dlg = new CDownloadUpdateDlg(); CAutoUpdater_DownloadInfo * Info = new CAutoUpdater_DownloadInfo(hSession, updateFileLocation,download_update_dlg); CWinThread * controlThread = AfxBeginThread(DownloadUpdateFile,Info,THREAD_PRIORITY_NORMAL); download_update_dlg->DoModal(); //download_update_dlg->OnCancel(); LPDWORD lpExitCode = new unsigned long; *lpExitCode = STILL_ACTIVE; //while(*lpExitCode==STILL_ACTIVE) //{ // GetExitCodeThread(controlThread->m_hThread,lpExitCode); // ::Sleep(1000); //} //bTransferSuccess = (int)(*lpExitCode); //InternetCloseHandle(hSession); // if (!bTransferSuccess) // { // return FileDownloadFailure; // } MessageBox(AfxGetMainWnd()->m_hWnd, LoadString(IDS_INSTALL_UPDATE), LoadString(IDS_PCMAN_CLOSE), MB_ICONINFORMATION|MB_OK); if (!::ShellExecute(AfxGetMainWnd()->m_hWnd, "open", updateFileLocation, NULL, NULL, SW_SHOWNORMAL)) { return UpdateNotComplete; } ASSERT(AfxGetMainWnd() != NULL); SetActiveWindow(AfxGetMainWnd()->m_hWnd); AfxGetMainWnd()->SendMessage(WM_COMMIT_UPDATE); return Success; }
void CSetTimeDlg::InitWGas(int gasfds) { if ( m_CommonSet._IsOpen() ) m_CommonSet.Close(); m_nSecond = 6; m_CommonSet.Create(); m_CommonSet.CursorType(adOpenDynamic); m_CommonSet.CacheSize(50); m_CommonSet._SetRecordsetEvents(new CAccountSetEvents); m_CommonSet.Open(_T("Select * From commonset"), &theApp.m_Cn); m_CommonSet.MarshalOptions(adMarshalModifiedOnly); unsigned char nfds; if(gasfds == 0) nfds= m_VERIFYT.GetCurSel()+1; else nfds= gasfds; m_CommonSet.MoveFirst(); while ( !m_CommonSet.IsEOF() ) { int sfds = m_CommonSet.m_szCommonID; if(sfds >(nfds*6) && sfds <( (nfds+1)*6+1 ) ) { CString dddd = m_CommonSet.m_szstrc30; dddd.TrimRight(); str_list[sfds-nfds*6-1].strl = dddd; } m_CommonSet.MoveNext(); } m_listC.DeleteAllItems(); for (int iItem1 = 2; iItem1 >= 0; iItem1--) m_listC.DeleteColumn(iItem1); m_listC.InsertHiddenLabelColumn(); // Requires one never uses column 0 for(int col = 0; col < 2 ; ++col) { CString title; int kkk; CGridColumnTrait* pTrait = NULL; if (col==0) // Country { kkk = 200; title ="传感器位置"; } if (col==1) // Year won { int k=0; kkk = 250; title ="通道号"; CGridColumnTraitCombo* pComboTrait = new CGridColumnTraitCombo; for(int i = 01; i < MAX_CHAN; i++) { CString strfds,strtemp,strchan; strtemp = m_SlaveStation[nfds][i].WatchName; if(strtemp != "") { int n=i; if(i>16) n = i-16; strfds.Format(_T("%02d"), nfds); strchan.Format(_T("%02d"), n); int n_ptype = m_SlaveStation[nfds][i].ptype; if(n_ptype < 3) { pComboTrait->AddItem(k, strfds+"A"+strchan+"|"+strtemp); k++; } else if(n_ptype==10 || n_ptype==13 ||n_ptype==14) { pComboTrait->AddItem(k, strfds+"D"+strchan+"|"+strtemp); k++; } else if(n_ptype == 12) { pComboTrait->AddItem(k, strfds+"C"+strchan+"|"+strtemp); k++; } } } pTrait = pComboTrait; } m_listC.InsertColumnTrait(col+1, title, LVCFMT_LEFT, kkk, col, pTrait); } for( int iItem = 0; iItem < 6 ; iItem++) { m_listC.InsertItem(iItem, "通断"); m_listC.SetItemText(iItem, 2, str_list[iItem].strl); } m_listC.SetItemText(0, 1, "进风瓦斯"); m_listC.SetItemText(1, 1, "回风瓦斯"); m_listC.SetItemText(2, 1, "串联通风"); m_listC.SetItemText(3, 1, "局扇"); m_listC.SetItemText(4, 1, "风筒风量"); m_listC.SetItemText(5, 1, "控制量通道"); }
///////////////////////////////////////////////////////////////////////////// // CSetTimeDlg message handlers BOOL CSetTimeDlg::OnInitDialog() { CXTResizeDialog::OnInitDialog(); CMainFrame* pFWnd=(CMainFrame*)AfxGetMainWnd(); pFWnd->m_pSetTimeDlg=this; SetResize(IDOK_SEND, SZ_BOTTOM_LEFT, SZ_BOTTOM_LEFT); SetResize(IDCANCEL, SZ_BOTTOM_LEFT, SZ_BOTTOM_LEFT); if(chcommand == 0x43) //配置测点 { SetResize(IDC_LIST_C, SZ_TOP_LEFT, SZ_BOTTOM_CENTER); SetResize(IDC_LIST_C2, SZ_TOP_CENTER, SZ_BOTTOM_RIGHT); } else SetResize(IDC_LIST_C, SZ_TOP_LEFT, SZ_BOTTOM_RIGHT); // Enable Office XP themes. XTThemeManager()->SetTheme(xtThemeOffice2003); HWND hWndHeader = m_listC.GetDlgItem(0)->GetSafeHwnd(); m_header.SubclassWindow(hWndHeader); // add bitmap images. m_header.SetBitmap(0, IDB_COLUMN_0, FALSE, RGB(0,255,0)); m_header.SetBitmap(1, IDB_COLUMN_1, FALSE, RGB(0,255,0)); //m_header.SetBitmap(2, IDB_COLUMN_2, FALSE, RGB(0,255,0)); // enable auto sizing. m_header.EnableAutoSize(TRUE); m_header.ResizeColumnsToFit(); //SortColumn(m_nSortedCol, m_bAscending); // m_listCtrl.ModifyExtendedStyle(0, LVS_EX_FULLROWSELECT|LVS_EX_FULLROWSELECT); m_listC.ModifyExtendedStyle(0, LVS_EX_GRIDLINES); m_listC2.ModifyExtendedStyle(0, LVS_EX_GRIDLINES); // insert strings into the size combo box. if(chcommand == 0x5A) //故障闭锁 { m_FUNCTION.AddString("关闭"); m_FUNCTION.AddString("使能"); } else { m_FUNCTION.AddString("吸合"); m_FUNCTION.AddString("断开"); } for(int i = 01; i < MAX_FDS; i++) { CString strItem; strItem.Format(_T("%d"), i); m_VERIFYT.AddString(strItem); if(i<9) m_PORT.AddString(strItem); } m_VERIFYT.SetCurSel(0); m_PORT.SetCurSel(0); m_FUNCTION.SetCurSel(0); CString szConnect ; if(chcommand == 0x54) //校时 { GetDlgItem(IDC_STATICV1)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_STATICV2)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_COMBO_PORT)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_COMBO_FUNCTION)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_BUT_RES)->ShowWindow(SW_HIDE);; m_listC.InsertColumn(0,"命令返回信息",LVCFMT_LEFT,450); GetDlgItem(IDC_STATICV)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_COMBO_VERIFYT)->ShowWindow(SW_HIDE);; } else if(chcommand == 0x4B) //手动控制 { m_listC.DeleteAllItems(); GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE);; SetWindowText("手动控制操作"); m_listC.InsertColumn(0,"命令返回信息",LVCFMT_LEFT,450); // m_listC.InsertColumn(1,"控制量",LVCFMT_LEFT,80); // m_listC.InsertColumn(2,"关联量",LVCFMT_LEFT,80); /* int xxx = 0; int yyy = 0; unsigned char nfds = m_VERIFYT.GetCurSel()+1; for( int iItem = 0; iItem < 8 ; iItem++) { yyy = xxx; for( int i = 0; i < 64 ; i++) { if(m_ADCbreakE[nfds][iItem+17][i].bFSd != 0) { m_listC.InsertItem(i+yyy, m_SlaveStation[nfds][iItem+17].WatchName); m_listC.SetItemText(i+yyy, 1, m_ADCbreakE[nfds][iItem+17][i].cpoint); m_listC.SetItemText(i+yyy, 2, m_ADCbreakE[nfds][iItem+17][i].adpoint); xxx++; } } } m_nSecond = xxx;*/ } else if(chcommand == 0x43) //配置测点 { GetDlgItem(IDC_STATICV1)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_STATICV2)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_COMBO_PORT)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_COMBO_FUNCTION)->ShowWindow(SW_HIDE);; SetWindowText("分站测点配置操作"); GetDlgItem(IDC_BUT_RES)->SetWindowText("初始化"); m_listC.InsertColumn(0,"命令返回信息",LVCFMT_LEFT,450); GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE); } else if(chcommand == 0x41) //配置分站 { m_SControl.Create(); m_SControl.CursorType(adOpenDynamic); m_SControl.CacheSize(50); m_SControl._SetRecordsetEvents(new CAccountSetEvents); m_SControl.Open(_T("Select * From specialcontrol"), &theApp.m_Cn); m_SControl.MarshalOptions(adMarshalModifiedOnly); GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE); SetWindowText("配置分站操作"); GetDlgItem(IDC_STATICV2)->ShowWindow(SW_HIDE); GetDlgItem(IDC_COMBO_FUNCTION)->ShowWindow(SW_HIDE); GetDlgItem(IDC_STATICV1)->ShowWindow(SW_HIDE); GetDlgItem(IDC_COMBO_PORT)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_COMBO_VERIFYT)->ShowWindow(SW_HIDE); GetDlgItem(IDC_STATICV)->ShowWindow(SW_HIDE);; // GetDlgItem(IDC_STATICV1)->SetWindowText("串口号"); GetDlgItem(IDC_BUT_RES)->ShowWindow(SW_HIDE);; m_listC.InsertHiddenLabelColumn(); // Requires one never uses column 0 for(int col = 0; col < 2 ; ++col) { CString title; int kkk; CGridColumnTrait* pTrait = NULL; if (col==0) // Country { kkk = 270; title ="分站号"; } if (col==1) // Year won { kkk = 90; title ="串口号"; CGridColumnTraitCombo* pComboTrait = new CGridColumnTraitCombo; pComboTrait->AddItem(0, "无配置"); for(int i = 01; i < 100; i++) { CString strItem,strtemp; strItem.Format(_T("%d"), i); pComboTrait->AddItem(i, strItem); } pTrait = pComboTrait; } m_listC.InsertColumnTrait(col+1, title, LVCFMT_LEFT, kkk, col, pTrait); } int iItem = 0; m_SControl.MoveFirst(); while ( !m_SControl.IsEOF() ) { m_listC.InsertItem(iItem, "通断"); CString dddd; dddd.Format("%d",m_SControl.m_szSID); m_listC.SetItemText(iItem, 1, dddd); dddd.Format("%d",m_SControl.m_szSerialnum); m_listC.SetItemText(iItem, 2, dddd); iItem++; m_SControl.MoveNext(); } } else if(chcommand == 0x47) //通讯测试 { GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE);; SetWindowText("通讯测试"); GetDlgItem(IDC_STATICV2)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_COMBO_FUNCTION)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_STATICV1)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_COMBO_PORT)->ShowWindow(SW_HIDE);; GetDlgItem(IDC_BUT_RES)->ShowWindow(SW_HIDE);; m_listC.InsertColumn(0,"命令返回信息",LVCFMT_LEFT,450); } else if(chcommand == 0x5A) //故障闭锁 { GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE); SetWindowText("故障闭锁配置"); GetDlgItem(IDC_STATICV1)->ShowWindow(SW_HIDE); GetDlgItem(IDC_COMBO_PORT)->ShowWindow(SW_HIDE); GetDlgItem(IDC_STATICV2)->SetWindowText("故障闭锁状态"); GetDlgItem(IDC_BUT_RES)->SetWindowText("初始化"); m_SControl.Create(); m_SControl.CursorType(adOpenDynamic); m_SControl.CacheSize(50); m_SControl._SetRecordsetEvents(new CAccountSetEvents); m_SControl.Open(_T("Select * From specialcontrol"), &theApp.m_Cn); m_SControl.MarshalOptions(adMarshalModifiedOnly); m_listC.InsertColumn(0,"分站号",LVCFMT_LEFT,300); m_listC.InsertColumn(1,"故障闭锁状态",LVCFMT_LEFT,120); int iItem = 0; m_SControl.MoveFirst(); while ( !m_SControl.IsEOF() ) { CString dddd; dddd.Format("%d",m_SControl.m_szSID); m_listC.InsertItem(iItem, dddd); if(m_SControl.m_szSpeCtrol) m_listC.SetItemText(iItem, 1, "使能"); else m_listC.SetItemText(iItem, 1, "关闭"); iItem++; m_SControl.MoveNext(); } m_nSecond = 64; } else if(chcommand == 0x46) //风电瓦斯闭锁 { GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE); SetWindowText("风电瓦斯闭锁配置"); GetDlgItem(IDC_STATICV1)->ShowWindow(SW_HIDE); GetDlgItem(IDC_COMBO_PORT)->ShowWindow(SW_HIDE); GetDlgItem(IDC_STATICV2)->ShowWindow(SW_HIDE); GetDlgItem(IDC_COMBO_FUNCTION)->ShowWindow(SW_HIDE); GetDlgItem(IDC_BUT_RES)->SetWindowText("初始化"); InitWGas(0); } else if(chcommand == 0xf0) //双风门、主扇备扇报警 { m_Records1.clear(); m_Records2.clear(); GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE); SetWindowText("双设备报警逻辑管理"); GetDlgItem(IDOK_SEND)->SetWindowText("添加"); GetDlgItem(IDC_BUT_RES)->SetWindowText("删除"); GetDlgItem(IDC_STATICV1)->SetWindowText("开关量1"); GetDlgItem(IDC_STATICV2)->SetWindowText("开关量2"); GetDlgItem(IDC_STATICV)->SetWindowText(_T("报警态")); // GetDlgItem(IDC_COMBO_VERIFYT)->ShowWindow(SW_HIDE); m_PORT.ResetContent(); m_FUNCTION.ResetContent(); m_VERIFYT.ResetContent(); m_VERIFYT.AddString(_T("0态")); m_VERIFYT.AddString(_T("1态")); m_VERIFYT.SetCurSel(0); m_Fans.Create(); m_Fans.CursorType(adOpenDynamic); m_Fans.CacheSize(50); m_Fans._SetRecordsetEvents(new CAccountSetEvents); m_Fans.Open(_T("Select * From fanscon"), &theApp.m_Cn); m_Fans.MarshalOptions(adMarshalModifiedOnly); int ptype; CString dddd; for(int i = 1; i < MAX_FDS;i++ ) { for(int j = 0; j < MAX_CHAN;j++ ) { ptype = m_SlaveStation[i][j].ptype; if((ptype == 10 || ptype == 13 ||ptype == 14) && m_SlaveStation[i][j].WatchName !="") { dddd = m_SlaveStation[i][j].strPN + "|"+m_SlaveStation[i][j].WatchName; m_PORT.AddString(dddd); m_FUNCTION.AddString(dddd); } } } m_PORT.SetCurSel(0); m_FUNCTION.SetCurSel(0); m_listC.InsertColumn(0,"开关量1",LVCFMT_LEFT,60); m_listC.InsertColumn(1,"安装地点/名称1",LVCFMT_LEFT,200); m_listC.InsertColumn(2,"开关量2",LVCFMT_LEFT,60); m_listC.InsertColumn(3,"安装地点/名称2",LVCFMT_LEFT,200); m_listC.InsertColumn(4,"报警状态",LVCFMT_LEFT,60); // m_listC.InsertColumn(5,"ID",LVCFMT_LEFT,30); int iItem = 0; m_Fans.MoveFirst(); while ( !m_Fans.IsEOF() ) { CString dddd = m_Fans.m_szpointnum1; dddd.TrimRight(); m_listC.InsertItem(iItem, dddd); m_Records1.push_back(dddd); dddd = m_Fans.m_szName1; dddd.TrimRight(); m_listC.SetItemText(iItem, 1, dddd); dddd = m_Fans.m_szpointnum2; dddd.TrimRight(); m_listC.SetItemText(iItem, 2, dddd); m_Records2.push_back(dddd); dddd = m_Fans.m_szName2; dddd.TrimRight(); m_listC.SetItemText(iItem, 3, dddd); dddd.Format(_T("%d态"), m_Fans.m_szAStatus); m_listC.SetItemText(iItem, 4, dddd); m_nSecond = m_Fans.m_szFansID+1; // dddd.Format(_T("%d"), m_nSecond-1); // m_listC.SetItemText(iItem, 5, dddd); iItem++; m_Fans.MoveNext(); } } else if(chcommand == 0xf1) //数据显示页属性 { m_Records1.clear(); GetDlgItem(IDC_LIST_C2)->ShowWindow(SW_HIDE); SetWindowText("数据显示页属性"); GetDlgItem(IDOK_SEND)->SetWindowText("保存"); GetDlgItem(IDC_BUT_RES)->ShowWindow(SW_HIDE); GetDlgItem(IDC_STATICV1)->SetWindowText("文件名"); GetDlgItem(IDC_STATICV2)->SetWindowText("列表"); GetDlgItem(IDC_STATICV)->SetWindowText(_T("存表")); GetDlgItem(IDC_COMBO_VERIFYT)->EnableWindow(FALSE); CString strPointNo,cccc,strrsy,strrsy1; strrsy = gstrTimeOut + "\\" + strMetrics+ "rsy\\"; m_PORT.ResetContent(); m_FUNCTION.ResetContent(); m_VERIFYT.ResetContent(); for(int i =0; i < theApp.m_addfilesy.size() ;i++) { strPointNo = theApp.m_addfilesy[i]; int m_ishave = strPointNo.GetLength(); cccc = strPointNo.Mid(m_ishave-3,3); strPointNo.Replace(strrsy,""); if(cccc =="rsf") { m_Records1.push_back(strPointNo); m_PORT.AddString(strPointNo); } } // m_VERIFYT.SetCurSel(0); for(int k =1; k < 4 ;k++) { cccc.Format("%d",k); m_FUNCTION.AddString(cccc); m_FUNCTION.SetCurSel(0); } // Give better margin to editors m_listC.SetCellMargin(1.2); CGridRowTraitXP* pRowTrait = new CGridRowTraitXP; m_listC.SetDefaultRowTrait(pRowTrait); // Create Columns m_listC.InsertHiddenLabelColumn(); // Requires one never uses column 0 for(int col = 0; col < 2 ; ++col) { CString title; int kkk; CGridColumnTrait* pTrait = NULL; if (col==0) // Country { kkk = 350; title ="数据显示页属性"; } if (col==1) // City { kkk = 100; title ="参数(整数)"; pTrait = new CGridColumnTraitEdit; } m_listC.InsertColumnTrait(col+1, title, LVCFMT_LEFT, kkk, col, pTrait); } CString strl[35]; // strl[0] = "是否可见(1可见|0隐藏)"; strl[1] = "子类头控制(1或0)"; // strl[2] = "列表左上顶点x坐标"; // strl[3] = "列表宽度"; strl[4] = "列表高度"; strl[5] = "第一列名字"; // strl[6] = "第一列宽度"; strl[7] = "第二列名字"; strl[8] = "第二列宽度"; // strl[9] = "第三列名字"; strl[10] = "第三列宽度"; strl[11] = "行数"; strl[0] = "是否可见(1可见|0隐藏)"; strl[1] = "子类头控制(1或0)"; strl[2] = "列表左上顶点x坐标"; strl[3] = "列表宽度"; strl[4] = "列表高度"; strl[5] = "第一列宽度"; strl[6] = "第二列宽度"; strl[7] = "第三列宽度"; //strl[8] = "行数"; strl[8] = "最大值列宽度"; strl[9] = "最小值列宽度"; strl[10] = "平均值列宽度"; strl[11] = "断电值列宽度"; strl[12] = "复电值列宽度"; strl[13] = "报警上限列宽度"; strl[14] = "报警下限列宽度"; strl[15] = "量程高值列宽度"; strl[16] = "量程低值列宽度"; strl[17] = "断电时刻列宽度"; strl[18] = "复电时刻列宽度"; strl[19] = "报警时刻列宽度"; strl[20] = "馈电状态及时刻列宽度"; strl[21] = "断电范围列宽度"; strl[22] = "开停次数列宽度"; strl[23] = "工作时间列宽度"; for( k =0; k < 22 ;k++) { m_listC.InsertItem(k, "通断"); m_listC.SetItemText(k, 1, strl[k]); m_listC.SetItemText(k, 2, ""); } } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
/******************************************************************************* Function Name : bOpenReplayFile Input(s) : BOOL - TRUE if parsing is successful, FALSE otherwise Output : - Functionality : Load the replay file. Updates entries and CAN message list with the parsed content Member of : CReplayProcess Author(s) : Raja N Date Created : 16.7.2005 Modifications : Raja N on 26.07.2005, Implementwed code review comments *******************************************************************************/ BOOL CReplayProcess::bOpenReplayFile(BOOL bIsInteractive) { BOOL bReturn = TRUE; BOOL bModeMismatch = FALSE; CString omStrLine = ""; CString omStrTemp = ""; CHAR Line[500] = { 0 }; CString omStrMsgType = " "; int nBlockCounter = 0; m_bIsInteractive = FALSE; // Clear string array m_omEntries.RemoveAll(); m_omMsgList.RemoveAll(); // Clear error message m_omStrError = ""; m_bIsEmptySession = false; TRY { omInReplayFile.open( m_ouReplayFile.m_omStrFileName, std::ios::in ); if (!omInReplayFile.good()) { // Info file open error notification m_omStrError = defSTR_FILE_OPEN_ERROR; bReturn = FALSE ; } if((dwGetNoOfMsgsInLog()*BYTES_PER_LINE > MAX_FILE_SIZE_INTERACTIVE_REPLAY) && bIsInteractive && bReturn != FALSE) { m_omStrError = defSTR_REPLAY_FILE_SIZE_EXCEEDED; bReturn = FALSE ; } omInReplayFile.seekg(0, std::ios::beg); if(bReturn != FALSE) { // Read the file line by line. BOOL bModeFound = FALSE; BOOL bFileEndFlag = FALSE; BOOL bMsgModeFound = FALSE; BOOL bOldVersionFile = FALSE; BOOL bVersionFound = FALSE; BOOL bProtocolFound = FALSE; while ( bOldVersionFile == FALSE && (!omInReplayFile.eof()) && ( bMsgModeFound == FALSE || bModeFound == FALSE || bVersionFound == FALSE )) { omInReplayFile.getline( Line, sizeof(Line)); omStrLine = Line; omStrLine.TrimLeft(); omStrLine.TrimRight(); // Check if Protocol exists in the log file if( omStrLine.Find(defSTR_PROTOCOL_USED) != -1) { // If can related log file if( omStrLine.Find(defSTR_PROTOCOL_CAN) == -1) { m_omStrError = defSTR_LOG_PRTOCOL_MISMATCH; bReturn = FALSE ; bFileEndFlag = TRUE; } } // Version check if( omStrLine.Find(defSTR_BUSMASTER_VERSION_STRING) != -1 ) { bVersionFound = TRUE; int nPos = omStrLine.Find( defSTR_BUSMASTER_VERSION_STRING ); nPos += (int)strlen( defSTR_BUSMASTER_VERSION_STRING ); int nMajorVer = omStrLine[ nPos ] - '0'; if( nMajorVer < defLOG_FILE_MAJOR_VERSION_SUPPORTED ) { bOldVersionFile = TRUE; } } // set the mode of reply if( omStrLine.Find(HEX_MODE) == 0) { bMsgModeFound = TRUE; } else if (omStrLine.Find(DEC_MODE) == 0) { bMsgModeFound = TRUE; } if( omStrLine.Find(SYSTEM_MODE) == 0) { m_wLogReplayTimeMode= eSYSTEM_MODE; bModeFound = TRUE; } else if( omStrLine.Find(ABSOLUTE_MODE) == 0) { m_wLogReplayTimeMode= eABSOLUTE_MODE; bModeFound = TRUE; } else if( omStrLine.Find(RELATIVE_MODE) == 0) { m_wLogReplayTimeMode= eRELATIVE_MODE; bModeFound = TRUE; } } if( bOldVersionFile == TRUE ) { m_omStrError = defSTR_LOG_FILE_UNSUPPORTED; bReturn = FALSE ; bFileEndFlag = TRUE; } if( bReturn == TRUE && ( bModeFound == FALSE || bMsgModeFound == FALSE || bVersionFound == FALSE ) ) { m_omStrError = defINVALID_HEADER; bReturn = FALSE ; bFileEndFlag = TRUE; } } } CATCH_ALL(pomException) { if(pomException != nullptr ) { CHAR scErrorMsg[255]; // Get the exception error message pomException->GetErrorMessage(scErrorMsg,sizeof(scErrorMsg)); m_omStrError = scErrorMsg; pomException->Delete(); } bReturn = FALSE; } END_CATCH_ALL if(nBlockCounter >=1 ) { m_omStrError.Format( defSTR_MIXED_MODE_WARNING, nBlockCounter ); } return bReturn; }
void CSetTimeDlg::OnButRES() { m_ndkSend = new unsigned char[166]; if(chcommand == 0x4B) //手动控制 { m_ndkSend[0] = 0x7E; unsigned char nfds = m_VERIFYT.GetCurSel()+1; m_ndkSend[1] = nfds; m_ndkSend[2] = chcommand; m_ndkSend[3] = 0xff; m_ndkSend[4] = 0x02; m_ndkSend[5] = 0x21; CNDKMessage message1(MANUALCONTROL); message1.Add(m_ndkSend , 100); theApp.Sync(message1,1); // m_nchangev = 0; } else if(chcommand == 0xf0) //双风门、主扇备扇报警 { CString dddd =""; int nItemCount=m_listC.GetItemCount(); for(int nItem=0;nItem<nItemCount;nItem++) { if(m_listC.GetItemState(nItem,LVIS_SELECTED) & LVIS_SELECTED) { dddd = m_listC.GetItemText(nItem,0) +" "+m_listC.GetItemText(nItem,1) +" " +m_listC.GetItemText(nItem,2) +" "+m_listC.GetItemText(nItem,3) +" "+m_listC.GetItemText(nItem,4)+" "+theApp.curuser; CString strf,strc; strf = dddd.Mid(0,2); strc = dddd.Mid(3,2); int nfds = m_Str2Data.String2Int(strf); int nchan = m_Str2Data.String2Int(strc); int n_fans = m_AFans[nfds][nchan].fchan; if(n_fans == 1) { nItemCount =666; break; } m_listC.DeleteItem(nItem); // nItem = m_Str2Data.String2Int(strPointNo); g_Log.StatusOut("双设备报警关系删除:" + dddd); break; } } CString strSQL; if(dddd =="") { AfxMessageBox("请选择要删除的设备!", MB_OK); delete m_ndkSend; return; } if(nItemCount == 666) { strSQL.Format("%s:设备报警,不能删除!",dddd); AfxMessageBox(strSQL, MB_OK); delete m_ndkSend; return; } else m_Fans.Delete(); if ( m_Fans._IsOpen() ) m_Fans.Close(); m_Records1.clear(); m_Records2.clear(); m_listC.DeleteAllItems(); m_Fans.Create(); m_Fans.CursorType(adOpenDynamic); m_Fans.CacheSize(50); m_Fans._SetRecordsetEvents(new CAccountSetEvents); m_Fans.Open(_T("Select * From fanscon"), &theApp.m_Cn); m_Fans.MarshalOptions(adMarshalModifiedOnly); int iItem = 0; m_Fans.MoveFirst(); while ( !m_Fans.IsEOF() ) { CString dddd = m_Fans.m_szpointnum1; dddd.TrimRight(); m_listC.InsertItem(iItem, dddd); m_Records1.push_back(dddd); dddd = m_Fans.m_szName1; dddd.TrimRight(); m_listC.SetItemText(iItem, 1, dddd); dddd = m_Fans.m_szpointnum2; dddd.TrimRight(); m_listC.SetItemText(iItem, 2, dddd); m_Records2.push_back(dddd); dddd = m_Fans.m_szName2; dddd.TrimRight(); m_listC.SetItemText(iItem, 3, dddd); dddd.Format(_T("%d态"), m_Fans.m_szAStatus); m_listC.SetItemText(iItem, 4, dddd); m_nSecond = m_Fans.m_szFansID+1; // dddd.Format(_T("%d"), m_nSecond-1); // m_listC.SetItemText(iItem, 5, dddd); iItem++; m_Fans.MoveNext(); } theApp.InitData(); } else if(chcommand == 0x46) //风电瓦斯闭锁初始化 { unsigned char nfds = m_VERIFYT.GetCurSel()+1; CString strSQL; if(m_SerialF[nfds].SFSd ==0) { strSQL.Format("%d号分站没有巡检!",nfds); AfxMessageBox(strSQL, MB_OK); delete m_ndkSend; return; } for(int i =0; i < 6 ;i++)//风电瓦斯闭锁关系定义的测点正常时可以初始化、修改 { CString strf,strc; if(str_list[i].strl =="") break; strf = str_list[i].strl.Mid(0,2); strc = str_list[i].strl.Mid(3,2); int nfds = m_Str2Data.String2Int(strf); int nchan = m_Str2Data.String2Int(strc); unsigned char nstatus = m_SlaveStation[nfds][nchan].Channel_state; if(nstatus == 0x10 || nstatus == 0x20 || nstatus == 0xa0) { strSQL.Format("%d号分站%s状态为%s,不能初始化!",nfds,str_list[i].strl,theApp.m_RTDM.strstatus(nstatus)); AfxMessageBox(strSQL, MB_OK); delete m_ndkSend; return; } } strSQL.Format("%d号分站风电瓦斯闭锁初始化,此操作将删除%d号分站风电瓦斯闭锁配置,是否继续操作?",nfds,nfds); int Reply = AfxMessageBox(strSQL, MB_YESNO); if ( Reply != IDYES ) { delete m_ndkSend; return; } m_ndkSend[0] = 0x7E; m_ndkSend[1] = nfds; m_ndkSend[2] = chcommand; m_ndkSend[3] = 0xff; m_ndkSend[4] = 0xff; m_ndkSend[5] = 0xff; m_ndkSend[6] = 0xff; m_ndkSend[7] = 0xff; m_ndkSend[8] = 0xff; m_ndkSend[9] = 0x21; CNDKMessage message1(WINDGASATRESIA); message1.Add(m_ndkSend , 100); theApp.Sync(message1,1); for( i =0;i<6;i++) str_list[i].strl=""; strSQL.Format("设置%d号分站风电瓦斯闭锁初始化!",nfds); AfxMessageBox(strSQL, MB_OK); g_Log.StatusOut(strSQL); } else if(chcommand == 0x5A) //故障闭锁初始化 { CString strSQL; strSQL.Format("故障闭锁初始化,此操作将删除60个分站故障闭锁配置,是否继续操作。"); int Reply = AfxMessageBox(strSQL, MB_YESNO); if ( Reply != IDYES ) { delete m_ndkSend; return; } CMainFrame* pFWnd=(CMainFrame*)AfxGetMainWnd(); pFWnd->n_derr60 =1; } else if(chcommand == 0x43) //配置测点初始化 { unsigned char nfds = m_VERIFYT.GetCurSel()+1; CString strim2; if(m_SerialF[nfds].SFSd ==0) { strim2.Format("%d号分站没有巡检!",nfds); AfxMessageBox(strim2, MB_OK); delete m_ndkSend; return; } strim2.Format("%d号分站测点配置初始化,此操作将删除%d号分站测点配置,是否继续操作?",nfds,nfds); int Reply = AfxMessageBox(strim2, MB_YESNO); if ( Reply != IDYES ) { delete m_ndkSend; return; } m_ndkSend[0] = 0x7E; m_ndkSend[1] = nfds; m_ndkSend[2] = 0x43; strim2.Format("%x|%x|%x",m_ndkSend[0],m_ndkSend[1],m_ndkSend[2]); ComDisMes(strim2); for(int i=1;i<17 ;i++) { m_ndkSend[i*10-7] = 0xff; m_ndkSend[i*10-6] = 0xff; // m_ndkSend[i*10-5] = 0xff; m_ndkSend[i*10-4] = 0xff; // m_ndkSend[i*10-3] = 0xff; m_ndkSend[i*10-2] = 0xff; // m_ndkSend[i*10-1] = 0xff; m_ndkSend[i*10] = 0xff; // m_ndkSend[i*10+1] = 0xff; m_ndkSend[i*10+2] = 0xff; // strim2.Format("%x|%x|%x|%x|%x|%x|%x|%x|%x|%x %d|%d|%d|%d|%d|%d|%d|%d|%d|%d",m_ndkSend[i*10-7],m_ndkSend[i*10-6],m_ndkSend[i*10-5],m_ndkSend[i*10-4],m_ndkSend[i*10-3],m_ndkSend[i*10-2],m_ndkSend[i*10-1], m_ndkSend[i*10],m_ndkSend[i*10+1],m_ndkSend[i*10+2], m_ndkSend[i*10-7],m_ndkSend[i*10-6],m_ndkSend[i*10-5],m_ndkSend[i*10-4],m_ndkSend[i*10-3],m_ndkSend[i*10-2],m_ndkSend[i*10-1], m_ndkSend[i*10],m_ndkSend[i*10+1],m_ndkSend[i*10+2]); ComDisMes(strim2); } m_ndkSend[163] = 0xff; //控制量类型 m_ndkSend[164] = 0xff; // m_ndkSend[165] = 0x21; // strim2.Format("%x|%x|%x",m_ndkSend[163],m_ndkSend[164],m_ndkSend[165]); CNDKMessage message1(SENDCONFIG); message1.Add(m_ndkSend , 200); theApp.Sync(message1,1); ComDisMes(strim2); strim2.Format("%d号分站测点初始化。",nfds); AfxMessageBox(strim2, MB_OK); g_Log.StatusOut( strim2 ); } delete m_ndkSend; }
///////////////////////////////////////////////////////////////////////////// // 显示About对话框 ///////////////////////////////////////////////////////////////////////////// void CPlugIn::ShowAboutBox() { #ifdef APPLICATION_SCRIPTDEV CString strLicensePlugin = theApp.m_xmlPlat.GetNodeText("application\\LicensePlugin"); if(strLicensePlugin == "") { return; } ILicense* pILicense = (ILicense*)(theApp.CreateVciObject(strLicensePlugin)); if(pILicense) { pILicense->ComponentAbout(m_strId); } #endif TTaskDialogInfo taskDialogInfo; taskDialogInfo.strWindowTitle = m_strName; taskDialogInfo.strMainInstruction = m_strName; CString strContent; strContent = "Version : " + m_strVersion + "\n"; strContent += "Author : "; strContent += m_strProvider; strContent += "\n"; CString strXmlFile = m_strPath; if(LANGUAGE_PAGE_CHINESE == theApp.m_curLanguage) { strXmlFile += "\\plugin_cn.xml"; // 如果不存在中文的配置文件,就用缺省的 if(GetFileAttributes(strXmlFile) == 0xFFFFFFFF) { strXmlFile = m_strPath + "\\plugin.xml"; } }else { strXmlFile += "\\plugin.xml"; } CXmlParser parser; if(parser.Open(strXmlFile) == 0) { strContent += "License : "; CString strLicense = parser.GetNodeText("license"); strLicense.TrimLeft(); strLicense.TrimRight(); strContent += strLicense; strContent += "\n"; CString strDesc = parser.GetNodeText("description"); strDesc.TrimLeft(); strDesc.TrimRight(); strContent += strDesc; strContent += "\n"; CString strCopyright = parser.GetNodeText("copyright"); strCopyright.TrimLeft(); strCopyright.TrimRight(); strContent += strCopyright; } taskDialogInfo.strContent = strContent; taskDialogInfo.strMainIcon = "Information"; theApp.DoTaskDialog(&taskDialogInfo); }
void CClient::ReadLine(const CString& sData) { CString sLine = sData; sLine.TrimRight("\n\r"); DEBUG("(" << GetFullName() << ") CLI -> ZNC [" << sLine << "]"); if (sLine.Left(1) == "@") { // TODO support message-tags properly sLine = sLine.Token(1, true); } bool bReturn = false; if (IsAttached()) { NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this, &bReturn); } else { GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn); } if (bReturn) return; CString sCommand = sLine.Token(0); if (sCommand.Left(1) == ":") { // Evil client! Sending a nickmask prefix on client's command // is bad, bad, bad, bad, bad, bad, bad, bad, BAD, B A D! sLine = sLine.Token(1, true); sCommand = sLine.Token(0); } if (!IsAttached()) { // The following commands happen before authentication with ZNC if (sCommand.Equals("PASS")) { m_bGotPass = true; CString sAuthLine = sLine.Token(1, true).TrimPrefix_n(); // [user[/network]:]password if (sAuthLine.find(":") == CString::npos) { m_sPass = sAuthLine; sAuthLine = ""; } else { m_sPass = sAuthLine.Token(1, true, ":"); sAuthLine = sAuthLine.Token(0, false, ":"); } if (!sAuthLine.empty()) { m_sUser = sAuthLine.Token(0, false, "/"); m_sNetwork = sAuthLine.Token(1, true, "/"); } AuthUser(); return; // Don't forward this msg. ZNC has already registered us. } else if (sCommand.Equals("NICK")) { CString sNick = sLine.Token(1).TrimPrefix_n(); m_sNick = sNick; m_bGotNick = true; AuthUser(); return; // Don't forward this msg. ZNC will handle nick changes until auth is complete } else if (sCommand.Equals("USER")) { // user[/network] CString sAuthLine = sLine.Token(1); if (m_sUser.empty() && !sAuthLine.empty()) { m_sUser = sAuthLine.Token(0, false, "/"); m_sNetwork = sAuthLine.Token(1, true, "/"); } m_bGotUser = true; if (m_bGotPass) { AuthUser(); } else if (!m_bInCap) { SendRequiredPasswordNotice(); } return; // Don't forward this msg. ZNC has already registered us. } } if (sCommand.Equals("CAP")) { HandleCap(sLine); // Don't let the client talk to the server directly about CAP, // we don't want anything enabled that ZNC does not support. return; } if (!m_pUser) { // Only CAP, NICK, USER and PASS are allowed before login return; } if (sCommand.Equals("ZNC")) { CString sTarget = sLine.Token(1); CString sModCommand; if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) { sModCommand = sLine.Token(2, true); } else { sTarget = "status"; sModCommand = sLine.Token(1, true); } if (sTarget.Equals("status")) { if (sModCommand.empty()) PutStatus("Hello. How may I help you?"); else UserCommand(sModCommand); } else { if (sModCommand.empty()) CALLMOD(sTarget, this, m_pUser, m_pNetwork, PutModule("Hello. How may I help you?")) else CALLMOD(sTarget, this, m_pUser, m_pNetwork, OnModCommand(sModCommand)) } return; } else if (sCommand.Equals("PING")) {
BOOL CDlgBatteryParam::GetParamFromInterface( STRUCT_BATTERY_PARAM* pBatteryParam ) { UpdateData(TRUE); if (m_batteryCell==-1) { return FALSE; } else pBatteryParam->dwCell = m_batteryCell; CString strValue; int nValue; GetDlgItem(IDC_EDIT_PULL_UP)->GetWindowText(strValue); if (strValue.IsEmpty()) { return FALSE; } else { strValue.TrimLeft(); strValue.TrimRight(); if (strValue==_T("0")) { pBatteryParam->dwPullUp = 0; } else { nValue = _ttoi((LPTSTR)(LPCTSTR)strValue); if (nValue<=0) { return FALSE; } pBatteryParam->dwPullUp = nValue; } } GetDlgItem(IDC_EDIT_PULL_DOWN)->GetWindowText(strValue); if (strValue.IsEmpty()) { return FALSE; } else { strValue.TrimLeft(); strValue.TrimRight(); if (strValue==_T("0")) { pBatteryParam->dwPullDown = 0; } else { nValue = _ttoi((LPTSTR)(LPCTSTR)strValue); if (nValue<=0) { return FALSE; } pBatteryParam->dwPullDown = nValue; } } int i; for (i=0;i<11;i++) { GetDlgItem(IDC_EDIT_DISCHARGE_1+i)->GetWindowText(strValue); if (strValue.IsEmpty()) { return FALSE; } else { strValue.TrimLeft(); strValue.TrimRight(); if (strValue==_T("0")) { pBatteryParam->dwDischarge[i] = 0; } else { nValue = _ttoi((LPTSTR)(LPCTSTR)strValue); if (nValue<=0) { return FALSE; } pBatteryParam->dwDischarge[i] = nValue; } } } for (i=0;i<11;i++) { GetDlgItem(IDC_EDIT_CHARGE_1+i)->GetWindowText(strValue); if (strValue.IsEmpty()) { return FALSE; } else { strValue.TrimLeft(); strValue.TrimRight(); if (strValue==_T("0")) { pBatteryParam->dwCharge[i] = 0; } else { nValue = _ttoi((LPTSTR)(LPCTSTR)strValue); if (nValue<=0) { return FALSE; } pBatteryParam->dwCharge[i] = nValue; } } } return TRUE; }
void CClient::ReadLine(const CString& sData) { CLanguageScope user_lang(GetUser() ? GetUser()->GetLanguage() : ""); CString sLine = sData; sLine.TrimRight("\n\r"); DEBUG("(" << GetFullName() << ") CLI -> ZNC [" << sLine << "]"); MCString mssTags; if (sLine.StartsWith("@")) { mssTags = CUtils::GetMessageTags(sLine); sLine = sLine.Token(1, true); } bool bReturn = false; if (IsAttached()) { NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this, &bReturn); } else { GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn); } if (bReturn) return; CMessage Message(sLine); Message.SetClient(this); Message.SetTags(mssTags); if (IsAttached()) { NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this, &bReturn); } else { GLOBALMODULECALL(OnUnknownUserRawMessage(Message), &bReturn); } if (bReturn) return; CString sCommand = Message.GetCommand(); if (!IsAttached()) { // The following commands happen before authentication with ZNC if (sCommand.Equals("PASS")) { m_bGotPass = true; CString sAuthLine = Message.GetParam(0); ParsePass(sAuthLine); AuthUser(); // Don't forward this msg. ZNC has already registered us. return; } else if (sCommand.Equals("NICK")) { CString sNick = Message.GetParam(0); m_sNick = sNick; m_bGotNick = true; AuthUser(); // Don't forward this msg. ZNC will handle nick changes until auth // is complete return; } else if (sCommand.Equals("USER")) { CString sAuthLine = Message.GetParam(0); if (m_sUser.empty() && !sAuthLine.empty()) { ParseUser(sAuthLine); } m_bGotUser = true; if (m_bGotPass) { AuthUser(); } else if (!m_bInCap) { SendRequiredPasswordNotice(); } // Don't forward this msg. ZNC has already registered us. return; } } if (Message.GetType() == CMessage::Type::Capability) { HandleCap(Message); // Don't let the client talk to the server directly about CAP, // we don't want anything enabled that ZNC does not support. return; } if (!m_pUser) { // Only CAP, NICK, USER and PASS are allowed before login return; } switch (Message.GetType()) { case CMessage::Type::Action: bReturn = OnActionMessage(Message); break; case CMessage::Type::CTCP: bReturn = OnCTCPMessage(Message); break; case CMessage::Type::Join: bReturn = OnJoinMessage(Message); break; case CMessage::Type::Mode: bReturn = OnModeMessage(Message); break; case CMessage::Type::Notice: bReturn = OnNoticeMessage(Message); break; case CMessage::Type::Part: bReturn = OnPartMessage(Message); break; case CMessage::Type::Ping: bReturn = OnPingMessage(Message); break; case CMessage::Type::Pong: bReturn = OnPongMessage(Message); break; case CMessage::Type::Quit: bReturn = OnQuitMessage(Message); break; case CMessage::Type::Text: bReturn = OnTextMessage(Message); break; case CMessage::Type::Topic: bReturn = OnTopicMessage(Message); break; default: bReturn = OnOtherMessage(Message); break; } if (bReturn) return; PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); }
// //--------------------------------------------------------- // BOOL CEasyBDoc::ReadFilePBN(CArchive& ar) { int nLineCode, nValue, nCode; CString strMessage, string, strTag, strValue, partString, strModifier; double fValue; BOOL bValue; CString strLine; // init some flags m_bReviewingGame = FALSE; m_bGameReviewAvailable = FALSE; // preload the file numLines = PreloadPBNFile(ar, strLines); /* int sizeOf = strLines.GetSize(); // NCR DEBUG ONLY for(int xxx = 0; xxx < sizeOf; xxx++) { CString nxtStr = strLines.GetAt(xxx); ASSERT(!nxtStr.IsEmpty()); } */ // read in the ines pGameRecord = NULL; m_nLineNumber = 0; nGameIndex = 0; nPreviousTag = 0; int numGamesLoaded = 0; int numInvalidGames = 0; int numTagsRead = 0; int numDeclarers = 0; // NCR use to test reviewable deals ie no Declarer means no review // for(;;) { // check for EOF if (m_nLineNumber >= numLines) break; strBuf = strLines.GetAt(m_nLineNumber++); // strBuf.TrimLeft(); strBuf.TrimRight(); nLineLen = strBuf.GetLength(); // see if this is a blank line (but watch out for multiple empty lines) if (strBuf.IsEmpty()) { // flush out the current game if (pGameRecord) { pGameRecord->AnalyzePlayRecord(); if (pGameRecord->IsValid(isExportFile)) // NCR_PBNI added isExportFile { m_gameRecords.Add(pGameRecord); numGamesLoaded++; nGameIndex++; } else { delete pGameRecord; numInvalidGames++; } pGameRecord = NULL; nPreviousTag = 0; continue; } } // else parse the line for tokens nLineCode = ParseLinePBN(strBuf, strTag, strValue, nLineLen); // check for error if (nLineCode < 0) { // junk tag? if (m_nLineNumber == 0) { AfxMessageBox("This is not a proper PBN format file."); AfxThrowFileException(CFileException::generic); } continue; } // // else the tag is OK // // see if the value is "#" -- then substitute if ((strValue == "#") && (nGameIndex > 0)) { // look up the value from the previous game CGameRecord* pPrevGame = m_gameRecords[nGameIndex-1]; std::map<CString,CString>::const_iterator iter = pPrevGame->m_mapTagValues.find(strTag); if (iter != pPrevGame->m_mapTagValues.end()) strValue = (*iter).second; } // // get data value // nValue = atoi(strValue); fValue = atof(strValue); if ((strValue == "Yes") || (strValue == "1")) bValue = TRUE; else bValue = FALSE; // // if this is a valid tag, alloc a new game object // if ((!strTag.IsEmpty()) && (pGameRecord == NULL)) { pGameRecord = new CGameRecord; numTagsRead = 0; } // //------------------------------------------------------------------- // // process item // switch(nLineCode) { case TAG_EVENT: break; case TAG_SITE: // ignore for now break; case TAG_DATE: // ignore for now break; case TAG_ROUND: // ignore for now break; case TAG_BOARD: // ignore for now break; case TAG_WEST: // ignore for now break; case TAG_NORTH: // ignore for now break; case TAG_EAST: // ignore for now break; case TAG_SOUTH: // ignore for now break; // dealer case TAG_DEALER: if (!strValue.IsEmpty() && (strValue[0] != '?')) pGameRecord->m_nDealer = CharToPosition(strValue[0]); break; // vulnerability case TAG_VULNERABLE: if (strValue.CompareNoCase("NS") == 0) pGameRecord->m_nVulnerability = NORTH_SOUTH; else if (strValue.CompareNoCase("EW") == 0) pGameRecord->m_nVulnerability = EAST_WEST; else if ((strValue.CompareNoCase("All") == 0) || (strValue.CompareNoCase("Both") == 0)) pGameRecord->m_nVulnerability = BOTH; else if((strValue.CompareNoCase("None") == 0) || (strValue.CompareNoCase("-") == 0)) // NCR-PBNI pGameRecord->m_nVulnerability = NEITHER; else // error if not above AfxMessageBox("Invalid Vulnerabliity: " + strValue); break; case TAG_DEAL: // AssignCardsPBN(strValue); break; case TAG_SCORING: // ignore for now break; case TAG_DECLARER: if (!strValue.IsEmpty() && (strValue[0] != '?')) { pGameRecord->m_nDeclarer = CharToPosition(strValue[0]); numDeclarers++; // NCR count for need to do review } break; case TAG_CONTRACT: { // decipher the contract if ((strValue.GetLength() < 2) || (strValue[0] == '?')) { // contract has not yet been set theApp.SetValue(tbGameInProgress, FALSE); break; } int nContractLevel = atoi(strValue); int nContractSuit = CharToSuit(strValue[1]); int nContract = MAKEBID(nContractSuit, nContractLevel); int nContractModifier = 0; // pGameRecord->m_nContract = nContract; // get modifier if (nContractSuit == NOTRUMP) strModifier = strValue.Mid(3); else strModifier = strValue.Mid(2); if (strModifier.CompareNoCase("X") == 0) nContractModifier = 1; else if (strModifier.CompareNoCase("XX") == 0) nContractModifier = 2; // pGameRecord->m_nContractModifier = nContractModifier; break; } case TAG_RESULT: // ignore for now break; // ge the auction case TAG_AUCTION: if (strValue.IsEmpty()) break; // parse the bids nCode = ParseBidsPBN(ar, strValue); break; case TAG_PLAY: // read in the plays if (strValue.IsEmpty() || (strValue[0] == '?')) break; // parse the plays nCode = ParsePlaysPBN(ar, strValue); // mark this file as being reviewable if (ISBID(pGameRecord->m_nContract)) { // contract must also be valid m_bReviewingGame = TRUE; m_bGameReviewAvailable = TRUE; } break; case TAG_NOTE: // add to the appropriate list if (nPreviousTag == TAG_AUCTION) pGameRecord->m_strBiddingNotes.Add(strValue); else if (nPreviousTag == TAG_PLAY) pGameRecord->m_strPlayNotes.Add(strValue); break; case TAG_OPTIMUMSCORE: // NCR-776 for BridgeWebs files // ignore break; case TAG_TERMINATOR: // ignore for now break; } // end switch(nLineCode) // save this tag nPreviousTag = nLineCode; numTagsRead++; // save the tag-value pair in the map if (pGameRecord) { // but don't save notes here if (strTag.CompareNoCase("Note") != 0) pGameRecord->SetTagValue(strTag, strValue); } } // end for(;;) // see if the file ended with no ending empty line // if (nGameIndex == 0 && pGameRecord) if (pGameRecord && (numTagsRead >= 1)) { pGameRecord->AnalyzePlayRecord(); if (pGameRecord->IsValid(isExportFile)) // NCR-PBNI added isExportFile { m_gameRecords.Add(pGameRecord); numGamesLoaded++; nGameIndex++; } // pGameRecord = NULL; } // if the file has > 1 game record, set game review mode if (nGameIndex > 1) { m_bReviewingGame = TRUE; m_bGameReviewAvailable = TRUE; } // see if we have a dangling (invalid) game object if (pGameRecord) delete pGameRecord; // all done return TRUE; }
// Config Parser. Might drop this. bool CConfig::Parse(CFile& file, CString& sErrorMsg) { CString sLine; unsigned int uLineNum = 0; CConfig *pActiveConfig = this; std::stack<ConfigStackEntry> ConfigStack; bool bCommented = false; // support for /**/ style comments if (!file.Seek(0)) { sErrorMsg = "Could not seek to the beginning of the config."; return false; } while (file.ReadLine(sLine)) { uLineNum++; #define ERROR(arg) do { \ std::stringstream stream; \ stream << "Error on line " << uLineNum << ": " << arg; \ sErrorMsg = stream.str(); \ m_SubConfigs.clear(); \ m_ConfigEntries.clear(); \ return false; \ } while (0) // Remove all leading spaces and trailing line endings sLine.TrimLeft(); sLine.TrimRight("\r\n"); if (bCommented || sLine.Left(2) == "/*") { /* Does this comment end on the same line again? */ bCommented = (sLine.Right(2) != "*/"); continue; } if ((sLine.empty()) || (sLine[0] == '#') || (sLine.Left(2) == "//")) { continue; } if ((sLine.Left(1) == "<") && (sLine.Right(1) == ">")) { sLine.LeftChomp(); sLine.RightChomp(); sLine.Trim(); CString sTag = sLine.Token(0); CString sValue = sLine.Token(1, true); sTag.Trim(); sValue.Trim(); if (sTag.Left(1) == "/") { sTag = sTag.substr(1); if (!sValue.empty()) ERROR("Malformated closing tag. Expected \"</" << sTag << ">\"."); if (ConfigStack.empty()) ERROR("Closing tag \"" << sTag << "\" which is not open."); const struct ConfigStackEntry& entry = ConfigStack.top(); CConfig myConfig(entry.Config); CString sName(entry.sName); if (!sTag.Equals(entry.sTag)) ERROR("Closing tag \"" << sTag << "\" which is not open."); // This breaks entry ConfigStack.pop(); if (ConfigStack.empty()) pActiveConfig = this; else pActiveConfig = &ConfigStack.top().Config; SubConfig &conf = pActiveConfig->m_SubConfigs[sTag.AsLower()]; SubConfig::const_iterator it = conf.find(sName); if (it != conf.end()) ERROR("Duplicate entry for tag \"" << sTag << "\" name \"" << sName << "\"."); conf[sName] = CConfigEntry(myConfig); } else { if (sValue.empty()) ERROR("Empty block name at begin of block."); ConfigStack.push(ConfigStackEntry(sTag.AsLower(), sValue)); pActiveConfig = &ConfigStack.top().Config; } continue; } // If we have a regular line, figure out where it goes CString sName = sLine.Token(0, false, "="); CString sValue = sLine.Token(1, true, "="); // Only remove the first space, people might want // leading spaces (e.g. in the MOTD). if (sValue.Left(1) == " ") sValue.LeftChomp(); // We don't have any names with spaces, trim all // leading/trailing spaces. sName.Trim(); if (sName.empty() || sValue.empty()) ERROR("Malformed line"); CString sNameLower = sName.AsLower(); pActiveConfig->m_ConfigEntries[sNameLower].push_back(sValue); } if (bCommented) ERROR("Comment not closed at end of file."); if (!ConfigStack.empty()) { const CString& sTag = ConfigStack.top().sTag; ERROR("Not all tags are closed at the end of the file. Inner-most open tag is \"" << sTag << "\"."); } return true; }
/******************************************** GetText Purpose The GetText function will return a text representation of cell's data, if current data type is other than string than data will be converted using current format settings. For numbers we introduced a way to retrieve localized or plain number representation, this mode can be controlled using the UGCELL_DONOT_LOCALIZE flag. If it is set than numbers will be returned as plain, by default all numeric data will be localized. Params none Return pointer to the text object *********************************************/ LPCTSTR CUGCell::GetText() { if (!( m_propSetFlags&UGCELL_STRING_SET )) { // if a value is not set to a cell than return NULL return NULL; } else if ( m_dataType == UGCELLDATA_NUMBER ) { CString strDouble; // parse the string without localized formatting m_string = ""; if( m_propSetFlags&UGCELL_NUMBERDEC_SET ) { CString formatStr = _T("%lf"); formatStr.Format(_T("%%1.%dlf"), m_numDecimals ); // strDouble.Format( formatStr, m_nNumber ); } else { strDouble.Format(_T("%.20f"), m_nNumber ); strDouble.TrimRight(_T('0')); } if(!( m_propSetFlags&UGCELL_NUMBERDEC_SET )) { strDouble.TrimLeft(_T('0')); strDouble.TrimRight(_T('0')); } // if the number ends with a period, than remove it if ( strDouble.Right( 1 ) == _T('.')) strDouble.TrimRight( _T('.')); if ( strDouble == _T("") && m_propSetFlags&UGCELL_STRING_SET ) strDouble = _T("0"); // create a 'proper' localized string representation of the numeric value if (!( m_propSetFlags&UGCELL_DONOT_LOCALIZE )) { TCHAR szBuffer[256]; NUMBERFMT nformat; // Determine the number of decimal places if (m_propSetFlags & UGCELL_NUMBERDEC_SET) nformat.NumDigits = m_numDecimals; else { int iDotIndex = strDouble.ReverseFind('.'); if (iDotIndex == -1) nformat.NumDigits = 0; else nformat.NumDigits = strDouble.GetLength() - iDotIndex - 1; } // Set up the rest of the members of NUMBERFMT GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ILZERO|LOCALE_RETURN_NUMBER, (TCHAR*)&nformat.LeadingZero, sizeof(nformat.LeadingZero)); nformat.Grouping = 3; TCHAR szDecimalSep[4]; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, szDecimalSep, 4); nformat.lpDecimalSep = szDecimalSep; TCHAR szThousandSep[4]; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, szThousandSep, 4); nformat.lpThousandSep = szThousandSep; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_INEGNUMBER|LOCALE_RETURN_NUMBER, (TCHAR*)&nformat.NegativeOrder, sizeof(nformat.NegativeOrder)); // Format the buffer int iRes = ::GetNumberFormat(LOCALE_USER_DEFAULT, 0, strDouble, &nformat, szBuffer, 256); if (iRes == 0) { // Too many decimal digits, so GetNumberFormat failed - let's format manually strDouble.Replace(_T("."), szDecimalSep); } else strDouble = szBuffer; } m_string = strDouble; } return m_string; }
void CHTTPSock::ReadLine(const CString& sData) { if (m_bGotHeader) { return; } CString sLine = sData; sLine.TrimRight("\r\n"); CString sName = sLine.Token(0); if (sName.Equals("GET")) { m_bPost = false; m_sURI = sLine.Token(1); m_bHTTP10Client = sLine.Token(2).Equals("HTTP/1.0"); ParseURI(); } else if (sName.Equals("POST")) { m_bPost = true; m_sURI = sLine.Token(1); ParseURI(); } else if (sName.Equals("Cookie:")) { VCString vsNV; sLine.Token(1, true).Split(";", vsNV, false, "", "", true, true); for (const CString& s : vsNV) { m_msRequestCookies[s.Token(0, false, "=").Escape_n(CString::EURL, CString::EASCII)] = s.Token(1, true, "=").Escape_n(CString::EURL, CString::EASCII); } } else if (sName.Equals("Authorization:")) { CString sUnhashed; sLine.Token(2).Base64Decode(sUnhashed); m_sUser = sUnhashed.Token(0, false, ":"); m_sPass = sUnhashed.Token(1, true, ":"); m_bBasicAuth = true; // Postpone authorization attempt until end of headers, because cookies should be read before that, otherwise session id will be overwritten in GetSession() } else if (sName.Equals("Content-Length:")) { m_uPostLen = sLine.Token(1).ToULong(); if (m_uPostLen > MAX_POST_SIZE) PrintErrorPage(413, "Request Entity Too Large", "The request you sent was too large."); } else if (sName.Equals("X-Forwarded-For:")) { // X-Forwarded-For: client, proxy1, proxy2 if (m_sForwardedIP.empty()) { const VCString& vsTrustedProxies = CZNC::Get().GetTrustedProxies(); CString sIP = GetRemoteIP(); VCString vsIPs; sLine.Token(1, true).Split(",", vsIPs, false, "", "", false, true); while (!vsIPs.empty()) { // sIP told us that it got connection from vsIPs.back() // check if sIP is trusted proxy bool bTrusted = false; for (const CString& sTrustedProxy : vsTrustedProxies) { if (sIP.WildCmp(sTrustedProxy)) { bTrusted = true; break; } } if (bTrusted) { // sIP is trusted proxy, so use vsIPs.back() as new sIP sIP = vsIPs.back(); vsIPs.pop_back(); } else { break; } } // either sIP is not trusted proxy, or it's in the beginning of the X-Forwarded-For list // in both cases use it as the endpoind m_sForwardedIP = sIP; } } else if (sName.Equals("If-None-Match:")) { // this is for proper client cache support (HTTP 304) on static files: m_sIfNoneMatch = sLine.Token(1, true); } else if (sName.Equals("Accept-Encoding:") && !m_bHTTP10Client) { SCString ssEncodings; // trimming whitespace from the tokens is important: sLine.Token(1, true).Split(",", ssEncodings, false, "", "", false, true); m_bAcceptGzip = (ssEncodings.find("gzip") != ssEncodings.end()); } else if (sLine.empty()) { if (m_bBasicAuth && !m_bLoggedIn) { m_bLoggedIn = OnLogin(m_sUser, m_sPass, true); // After successful login ReadLine("") will be called again to trigger "else" block // Failed login sends error and closes socket, so no infinite loop here } else { m_bGotHeader = true; if (m_bPost) { m_sPostData = GetInternalReadBuffer(); CheckPost(); } else { GetPage(); } DisableReadLine(); } } }
void CGitProgressList::OnContextMenu(CWnd* pWnd, CPoint point) { if (m_options & ProgOptDryRun) return; // don't do anything in a dry-run. if (pWnd != this) return; int selIndex = GetSelectionMark(); if ((point.x == -1) && (point.y == -1)) { // Menu was invoked from the keyboard rather than by right-clicking CRect rect; GetItemRect(selIndex, &rect, LVIR_LABEL); ClientToScreen(&rect); point = rect.CenterPoint(); } if ((selIndex < 0) || m_bThreadRunning || GetSelectedCount() == 0) return; // entry is selected, thread has finished with updating so show the popup menu CIconMenu popup; if (!popup.CreatePopupMenu()) return; ContextMenuActionList actions; NotificationData* data = m_arData[selIndex]; if (data && GetSelectedCount() == 1) data->GetContextMenu(popup, actions); if (!actions.empty()) popup.AppendMenu(MF_SEPARATOR, NULL); actions.push_back([&]() { CString sLines; POSITION pos = GetFirstSelectedItemPosition(); while (pos) { int nItem = GetNextSelectedItem(pos); NotificationData* data = m_arData[nItem]; if (data) { sLines += data->sPathColumnText; sLines += _T("\r\n"); } } sLines.TrimRight(); if (!sLines.IsEmpty()) CStringUtils::WriteAsciiStringToClipboard(sLines, GetSafeHwnd()); }); popup.AppendMenuIcon(actions.size(), IDS_LOG_POPUP_COPYTOCLIPBOARD, IDI_COPYCLIP); if (actions.empty()) return; int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this, 0); if (cmd <= 0 || cmd > actions.size()) return; theApp.DoWaitCursor(1); actions.at(cmd - 1)(); theApp.DoWaitCursor(-1); }
void CShaderEdit::OnUpdate() { if(m_nIDEvent == -1) { m_nIDEvent = SetTimer(1, 100, NULL); } CString text; int nStartChar = 0, nEndChar = -1; GetSel(nStartChar, nEndChar); if(nStartChar == nEndChar) { GetWindowText(text); while(nStartChar > 0 && _istalnum(text.GetAt(nStartChar-1))) nStartChar--; } if(nStartChar < nEndChar) { text = text.Mid(nStartChar, nEndChar - nStartChar); text.TrimRight('('); text.MakeLower(); m_acdlg.m_list.ResetContent(); CString key, value; POSITION pos = m_acdlg.m_inst.GetStartPosition(); while(pos) { POSITION cur = pos; m_acdlg.m_inst.GetNextAssoc(pos, key, value); if(key.Find(text) == 0) { CAtlList<CString> sl; Explode(value, sl, '|', 2); if(sl.GetCount() != 2) continue; CString name = sl.RemoveHead(); CString description = sl.RemoveHead(); int i = m_acdlg.m_list.AddString(name); m_acdlg.m_list.SetItemDataPtr(i, cur); } } if(m_acdlg.m_list.GetCount() > 0) { int lineheight = GetLineHeight(); CPoint p = PosFromChar(nStartChar); p.y += lineheight; ClientToScreen(&p); CRect r(p, CSize(100, 100)); m_acdlg.MoveWindow(r); m_acdlg.SetWindowPos(&wndTopMost, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE); m_acdlg.ShowWindow(SW_SHOWNOACTIVATE); m_nEndChar = nEndChar; return; } } m_acdlg.ShowWindow(SW_HIDE); }
void CEnListCtrl::OnPaint() { // if no items or in report mode draw to back buffer then blt if (GetItemCount() && GetView() != LVS_REPORT) Default(); else { CPaintDC cleanup(this); CHeaderCtrl* pHeader = GetHeader(); CDC& paintdc = *GetDC(); CDC dc; dc.CreateCompatibleDC(&paintdc); CRect rClient; GetClientRect( &rClient ); CBitmap bitmap; bitmap.CreateCompatibleBitmap(&paintdc, rClient.right, rClient.bottom); CBitmap *pOldBitmap = dc.SelectObject(& bitmap); if (pHeader && m_nCurView == LVS_REPORT && !(GetStyle() & LVS_NOCOLUMNHEADER)) { CRect rHeader; pHeader->GetWindowRect(&rHeader); ScreenToClient(rHeader); dc.ExcludeClipRect(rHeader); rClient.top = rHeader.bottom; } // fill with back color COLORREF crBack = GetItemBackColor(0, FALSE, FALSE, FALSE); dc.FillSolidRect(rClient, crBack); // default drawing CListCtrl::DefWindowProc(WM_PAINT, (WPARAM)dc.m_hDC, 0); // do empty text if nec if (GetItemCount() == 0) { CString sText = GetNoItemsText(); // virtual call if (!sText.IsEmpty()) { sText.TrimRight(); sText.TrimLeft(); if (sText[0] != '(') sText = "(" + sText; if (sText[sText.GetLength() - 1] != ')') sText += ")"; dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT)); dc.SetBkColor(crBack); dc.SelectStockObject( ANSI_VAR_FONT ); rClient.top += 10; dc.DrawText( sText, rClient, DT_CENTER | DT_WORDBREAK | DT_NOPREFIX/* | DT_NOCLIP */); rClient.top -= 10; // reset } } paintdc.BitBlt(0, rClient.top, rClient.right, rClient.bottom, &dc, 0, rClient.top, SRCCOPY); dc.SelectObject(pOldBitmap); ReleaseDC(&paintdc); } // Do not call CListView::OnPaint() for painting messages }
BOOL CXmlFileEx::Decrypt(LPCTSTR szPassword) { if (!IsEncrypted()) return TRUE; // nothing to do // we don't try to decrypt if no encryption capabilities if (!CanEncrypt()) { m_nFileError = XFL_NOENCRYPTIONDLL; return FALSE; } // use existing password if required if (!szPassword) szPassword = m_sPassword; CXmlItem* pXI = GetEncryptedBlock(); if (pXI && !pXI->GetSibling()) { // else keep getting password till success or user cancels while (TRUE) { CString sPassword(szPassword); if (sPassword.IsEmpty()) { CString sExplanation(s_sPasswordExplanation); if (sExplanation.Find(_T("%s")) != -1) sExplanation.Format(s_sPasswordExplanation, GetFileName()); if (!CPasswordDialog::RetrievePassword(FALSE, sPassword, sExplanation)) { // RB - Set m_nFileError to avoid "The selected task list could not be opened..." message when cancelling m_nFileError = XFL_CANCELLED; return FALSE; } } CString sFile; if (Decrypt(pXI->GetValue(), sFile, sPassword)) { m_sPassword = sPassword; sFile.TrimLeft(); sFile.TrimRight(); sFile = _T("<ROOT>") + sFile + _T("</ROOT>"); // delete the cdata item m_xiRoot.DeleteItem(pXI); try { CXmlDocumentWrapper doc; // reparse decrypted xml if (doc.LoadXML(sFile)) { CXmlNodeWrapper node(doc.AsNode()); return ParseItem(m_xiRoot, &node); } } catch (...) { m_nFileError = XFL_BADMSXML; } return FALSE; } // RB - Added code to format the error message before calling AfxMessage else { CEnString sMessage(s_sDecryptFailed, GetFileName()); if (IDNO == AfxMessageBox(sMessage, MB_YESNO)) { m_nFileError = XFL_CANCELLED; return FALSE; } // else user will try again } } } // else m_nFileError = XFL_UNKNOWNENCRYPTION; return FALSE; }
UINT CompNotifyThreadProc(LPVOID pParam) { CString str; CString strItem; int iPos; char chBuf[BUFSIZE+1]; DWORD dwRead; CCompNotifyThreadInfo* pThreadInfo = (CCompNotifyThreadInfo*)pParam; // Wait until the main application thread asks this thread to start the CompNitification if(WaitForSingleObject(pThreadInfo->m_hEventStartCompNotify, INFINITE) != WAIT_OBJECT_0) { return(0); } // Reset event to indicate "not done", that is, CompNotify is in progress. ResetEvent(pThreadInfo->m_hEventCompNotifyDone); FC_DEBUGPRINT1(_T("CEMSG> Start Msg thread id = 0x%X\n"),GetCurrentThreadId()); while (TRUE) { // Exit the thread if the main application sets the "kill CompNotify" // event. The main application will set the "start CompNotify" event // before setting the "kill CompNotify" event. if(ReadFile(pThreadInfo->m_hChildStdoutRd, chBuf, BUFSIZE, &dwRead, NULL) && dwRead != 0) { if(WaitForSingleObject(pThreadInfo->m_hEventKillCompNotify, 0) == WAIT_OBJECT_0) { break; // Terminate this thread by exitting the proc. } chBuf[dwRead] = 0; str += chBuf; while((iPos = str.Find(_T("\n"))) != -1) { strItem = str.Left(iPos); strItem.TrimRight(); EnterCriticalSection(&pThreadInfo->m_Lock); if(WaitForSingleObject(pThreadInfo->m_hEventKillCompNotify, 0) == WAIT_OBJECT_0) { LeaveCriticalSection(&pThreadInfo->m_Lock); break; // Terminate this thread by exitting the proc. } ::SendMessage(pThreadInfo->m_hwndNotifyClient, MSGTHRD_NOTIFY, (WPARAM)pThreadInfo->m_uiIndex, (LPARAM)(LPCTSTR)strItem); LeaveCriticalSection(&pThreadInfo->m_Lock); if(WaitForSingleObject(pThreadInfo->m_hEventKillCompNotify, 0) == WAIT_OBJECT_0) { break; // Terminate this thread by exitting the proc. } strItem = str.Mid(iPos + 1); str = strItem; } } else { break; } } CloseHandle(pThreadInfo->m_hChildStdoutRd); pThreadInfo->m_hChildStdoutRd = NULL; CloseHandle(pThreadInfo->m_hChildStdinWr); pThreadInfo->m_hChildStdinWr = NULL; /*since the normal AfxEndThread mechanism deletes the associated CWinThread object we must notify the CMsgThrd object that the embedded CWinThread object pointer points to an invalid e.g. deleted object so we set this pointer to NULL on exiting the the procedure*/ ::PostMessage(pThreadInfo->m_hwndNotifyClient, MSGTHRD_READY, (WPARAM)0, (LPARAM)0); * pThreadInfo->m_ppThread = NULL; SetEvent(pThreadInfo->m_hEventCompNotifyKilled); return(0); }
CXMLParser::CXMLParser(const std::string& fileStr) { #pragma region Create temp folder CString szFolder; LPITEMIDLIST pidl; LPMALLOC pShellMalloc; TCHAR szTemp[MAX_PATH]; if(SUCCEEDED(SHGetMalloc(&pShellMalloc))) { if(SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,&pidl))) { SHGetPathFromIDList(pidl,szTemp); szFolder =szTemp; pShellMalloc->Free(pidl); } pShellMalloc->Release(); } szFolder.TrimRight(_T("\\")); szFolder += _T("\\TF3DXML"); MyDeleteFile(szFolder); CFileStatus fstatus; if (!CFile::GetStatus(szFolder,fstatus)) { ::CreateDirectory(szFolder,NULL); } #pragma endregion Create temp folder const size_t strsize=(szFolder.GetLength()+1)*2; // 宽字符的长度; char * qstr= new char[strsize]; //分配空间; size_t sz=0; wcstombs_s(&sz,qstr,strsize,szFolder,_TRUNCATE); cUnpackFile unpackTool; unpackTool.CreateDirFromZip(qstr,fileStr.c_str()); delete []qstr; //delete []filestr; CFileFind finder; LPCTSTR pstr = szFolder; CString strWildcard(pstr); strWildcard += _T("\\*.*"); CString m_ext_now; m_ext_now.Format(_T("%s"),_T("3DRep")); CString m_str_3dxml; //查找装配树的.3dxml文件 m_str_3dxml.Format(_T("%s"),_T("3dxml")); BOOL bWorking = finder.FindFile(strWildcard); while (bWorking) { bWorking = finder.FindNextFile(); CString name = finder.GetFileName(); CString extend = name.Right(name.GetLength() - name.ReverseFind('.') - 1); if(!finder.IsDots()) { if (extend == m_ext_now)//m_ext_now为你要查找的文件扩展名 { CString str=finder.GetFilePath(); // 先得到要转换为字符的长度 const size_t strsize=(str.GetLength()+1)*2; // 宽字符的长度; char * pstr= new char[strsize]; //分配空间; size_t sz=0; wcstombs_s(&sz,pstr,strsize,str,_TRUNCATE); TiXmlDocument *myDocument = new TiXmlDocument(pstr); myDocument->LoadFile(); TiXmlElement *rootElement=myDocument->RootElement(); if(rootElement->FirstChildElement()->FirstChildElement()!=NULL && strcmp(rootElement->FirstChildElement()->FirstChildElement()->Value(),"Rep")==0) { m_pTempFile=new TF3DRepFile(); string filename; CT2A xx(name); filename = xx; m_pTempFile->SetFileName(filename); TraverseRep(rootElement->FirstChildElement()->FirstChildElement()); m_fileList.push_back(m_pTempFile); } delete myDocument; delete []pstr; } if(extend == m_str_3dxml) { CString str=finder.GetFilePath(); // 先得到要转换为字符的长度 const size_t strsize=(str.GetLength()+1)*2; // 宽字符的长度; char * pstr= new char[strsize]; //分配空间; size_t sz=0; wcstombs_s(&sz,pstr,strsize,str,_TRUNCATE); TiXmlDocument *myDocument = new TiXmlDocument(pstr); myDocument->LoadFile(); TiXmlElement *rootElement=myDocument->RootElement(); if(strcmp(rootElement->FirstChildElement()->NextSiblingElement()->Value(),"ProductStructure")==0) { rootElement=rootElement->FirstChildElement()->NextSiblingElement()->FirstChildElement(); m_root=new ReferenceTreeElement(); m_root->value=(char *)rootElement->FirstAttribute()->Next()->Next()->Value(); m_root->id=atoi(rootElement->FirstAttribute()->Next()->Value()); m_root->instancename=""; m_root->FirstChildElement=NULL; m_root->NextSimblingElement=NULL; while(rootElement!=NULL) { if(strcmp(rootElement->Value(),"Reference3D")==0) { AddReference3D(rootElement); } if(strcmp(rootElement->Value(),"Instance3D")==0) { AddInstance3D(rootElement); } rootElement=rootElement->NextSiblingElement(); } FindAllTreeNode(); ReferenceTreeElement *p=m_root; LinkTreeNode(p,NULL); } } } } finder.Close(); MyDeleteFile(szFolder); }
CString ProjectProperties::GetBugIDFromLog(CString& msg) { CString sBugID; if (!sMessage.IsEmpty()) { CString sBugLine; CString sFirstPart; CString sLastPart; BOOL bTop = FALSE; if (nBugIdPos < 0) return sBugID; sFirstPart = sMessage.Left(nBugIdPos); sLastPart = sMessage.Mid(nBugIdPos + 7); msg.TrimRight('\n'); if (msg.ReverseFind('\n')>=0) { if (bAppend) sBugLine = msg.Mid(msg.ReverseFind('\n')+1); else { sBugLine = msg.Left(msg.Find('\n')); bTop = TRUE; } } else { if (bNumber) { // find out if the message consists only of numbers bool bOnlyNumbers = true; for (int i=0; i<msg.GetLength(); ++i) { if (!_istdigit(msg[i])) { bOnlyNumbers = false; break; } } if (bOnlyNumbers) sBugLine = msg; } else sBugLine = msg; } if (sBugLine.IsEmpty() && (msg.ReverseFind('\n') < 0)) sBugLine = msg.Mid(msg.ReverseFind('\n')+1); if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0) sBugLine.Empty(); if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0) sBugLine.Empty(); if (sBugLine.IsEmpty()) { if (msg.Find('\n')>=0) sBugLine = msg.Left(msg.Find('\n')); if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0) sBugLine.Empty(); if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0) sBugLine.Empty(); bTop = TRUE; } if (sBugLine.IsEmpty()) return sBugID; sBugID = sBugLine.Mid(sFirstPart.GetLength(), sBugLine.GetLength() - sFirstPart.GetLength() - sLastPart.GetLength()); if (bTop) { msg = msg.Mid(sBugLine.GetLength()); msg.TrimLeft('\n'); } else { msg = msg.Left(msg.GetLength()-sBugLine.GetLength()); msg.TrimRight('\n'); } } return sBugID; }
BOOL CBuildProgram::bAddStrToArrayFromFile(CString& omStrTextFileName, CStringArray& omStrArray) { // Local Var. ifstream InTextFile; CString omStrMainMessage = ""; CString omStrLine = "" ; CHAR cLine[500]; BOOL bReturn = FALSE; TRY { InTextFile.open(/*T2A*/(omStrTextFileName.GetBuffer(MAX_PATH)), ios::in); if (!InTextFile.good()) { // Info file open error notification omStrMainMessage ="Input file open error : "; omStrMainMessage +=omStrTextFileName; //AfxMessageBox(omStrMainMessage ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,0); m_omStrArray.Add(omStrMainMessage); bAddString(m_omStrArray); bReturn = FALSE; } else { // Read line by line and add string to List box while (!InTextFile.eof()) { InTextFile.getline( cLine, sizeof(cLine)); omStrLine = cLine; omStrLine.TrimLeft(); omStrLine.TrimRight(); if(omStrLine.IsEmpty()==FALSE) { omStrArray.Add(omStrLine); } } InTextFile.close(); } } CATCH_ALL(pomException) { if(pomException != NULL ) { char scErrorMsg[255]; CString cStrErrorMessage; // Get the exception error message pomException->GetErrorMessage(scErrorMsg,sizeof(scErrorMsg)); cStrErrorMessage = "Failed to get address of Timer Handlers: "; cStrErrorMessage += scErrorMsg; //Display the error //AfxMessageBox(cStrErrorMessage ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,0); m_omStrArray.Add(cStrErrorMessage); bAddString(m_omStrArray); pomException->Delete(); } bReturn = FALSE; } END_CATCH_ALL return TRUE; }
std::vector<CHARRANGE> ProjectProperties::FindBugIDPositions(const CString& msg) { size_t offset1 = 0; size_t offset2 = 0; std::vector<CHARRANGE> result; // first use the checkre string to find bug ID's in the message if (!sCheckRe.IsEmpty()) { if (!sBugIDRe.IsEmpty()) { // match with two regex strings (without grouping!) try { AutoUpdateRegex(); const std::tr1::wsregex_iterator end; std::wstring s = msg; for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regCheck); it != end; ++it) { // (*it)[0] is the matched string std::wstring matchedString = (*it)[0]; ptrdiff_t matchpos = it->position(0); for (std::tr1::wsregex_iterator it2(matchedString.cbegin(), matchedString.cend(), regBugID); it2 != end; ++it2) { ATLTRACE(_T("matched id : %s\n"), (*it2)[0].str().c_str()); ptrdiff_t matchposID = it2->position(0); CHARRANGE range = {(LONG)(matchpos+matchposID), (LONG)(matchpos+matchposID+(*it2)[0].str().size())}; result.push_back(range); } } } catch (std::exception) {} } else { try { AutoUpdateRegex(); const std::tr1::wsregex_iterator end; std::wstring s = msg; for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regCheck); it != end; ++it) { const std::tr1::wsmatch match = *it; // we define group 1 as the whole issue text and // group 2 as the bug ID if (match.size() >= 2) { ATLTRACE(_T("matched id : %s\n"), std::wstring(match[1]).c_str()); CHARRANGE range = {(LONG)(match[1].first - s.cbegin()), (LONG)(match[1].second - s.cbegin())}; result.push_back(range); } } } catch (std::exception) {} } } else if (result.empty() && (!sMessage.IsEmpty())) { CString sBugLine; CString sFirstPart; CString sLastPart; BOOL bTop = FALSE; if (nBugIdPos < 0) return result; sFirstPart = sMessage.Left(nBugIdPos); sLastPart = sMessage.Mid(nBugIdPos + 7); CString sMsg = msg; sMsg.TrimRight('\n'); if (sMsg.ReverseFind('\n')>=0) { if (bAppend) sBugLine = sMsg.Mid(sMsg.ReverseFind('\n')+1); else { sBugLine = sMsg.Left(sMsg.Find('\n')); bTop = TRUE; } } else sBugLine = sMsg; if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0) sBugLine.Empty(); if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0) sBugLine.Empty(); if (sBugLine.IsEmpty()) { if (sMsg.Find('\n')>=0) sBugLine = sMsg.Left(sMsg.Find('\n')); if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0) sBugLine.Empty(); if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0) sBugLine.Empty(); bTop = TRUE; } if (sBugLine.IsEmpty()) return result; CString sBugIDPart = sBugLine.Mid(sFirstPart.GetLength(), sBugLine.GetLength() - sFirstPart.GetLength() - sLastPart.GetLength()); if (sBugIDPart.IsEmpty()) return result; //the bug id part can contain several bug id's, separated by commas if (!bTop) offset1 = sMsg.GetLength() - sBugLine.GetLength() + sFirstPart.GetLength(); else offset1 = sFirstPart.GetLength(); sBugIDPart.Trim(_T(",")); while (sBugIDPart.Find(',')>=0) { offset2 = offset1 + sBugIDPart.Find(','); CHARRANGE range = {(LONG)offset1, (LONG)offset2}; result.push_back(range); sBugIDPart = sBugIDPart.Mid(sBugIDPart.Find(',')+1); offset1 = offset2 + 1; } offset2 = offset1 + sBugIDPart.GetLength(); CHARRANGE range = {(LONG)offset1, (LONG)offset2}; result.push_back(range); } return result; }
// Cmd line format : /rep="replay file" [/sec] [/sep=,] [/txt="text file"] // // /sec : use seconds instead of ticks // /sep=X : specifies X as the column separator (don't use ',') // /rep="replay file" : replay to analyse (use full path unless bwchart.exe is located in same directory) // /txt="text file" : output text file // // default separator is TAB // default text file is rep file with .txt extension instead of .rep extension // default time measurement is ticks // // Always put replay file name and output text file name between double quotes (eg:"c:\dir\gg.rep"). // // Return code: 0 if ok, 1 for invalid parameter, -1 for output file cant be created, -2 for replay cant be loaded // int CBwchartApp::_CommandLineMode() { char *argv[4]; int argc=0; int err = 0; // extract arguments char *p = m_lpCmdLine; bool inString =false; while(*p!=0) { argv[argc] = p; while(true) { p++; if(*p=='\"') inString=!inString; else if(*p==' ' && !inString) {*p=0; p++; argc++; break;} } while(*p==' ') p++; } // analyse arguments CString repfile; CString txtfile; bool useSeconds = false; char cSep = '\t'; for(int i=0; i<argc; i++) { // extract option and value char *option = strtok(argv[i],"="); char *val = strtok(0,"="); // lowercase option _strlwr(option); if(strcmp(option,"/sec")==0) useSeconds = true; else if(strcmp(option,"/sep")==0) { if(val==0) err = 1; cSep = val[0]; } else if(strcmp(option,"/rep")==0) { if(val==0) err = 1; repfile = val; repfile.Replace('\"',' '); repfile.TrimLeft(); repfile.TrimRight(); } else if(strcmp(option,"/txt")==0) { if(val==0) err = 1; txtfile = val; txtfile.Replace('\"',' '); txtfile.TrimLeft(); txtfile.TrimRight(); } } // if text file is missing if(err == 0 && txtfile.IsEmpty()) { // use replay file name with txt extension txtfile = repfile; txtfile.Replace(".rep",".txt"); txtfile.Replace(".REP",".txt"); } // if we have a replay to export if(!repfile.IsEmpty()) { Replay replay; if(replay.Load(repfile,true,0,true)!=0) err = -2; else err = replay.ExportToText(txtfile,useSeconds,cSep); } return err; }
bool CResMenu::Load(CTextFile &file) { int level = 0; CString buffer;//next line CString line; CAtlArray<CString> Words; while(!file.Eof()) { CString word; if (buffer.IsEmpty()) { file.ReadLine(line); } else { line = buffer; buffer.Empty(); } CutString(line, Words); if (Words[0] == _T("BEGIN")) { continue; } if (Words[0] == _T("END")) { return true; } if (Words[0] == _T("POPUP")) { CResMenu SubMenu; SubMenu.m_String = Words[1]; if (!SubMenu.Load(file)) return false; m_SubMenus.Add(SubMenu); } if (Words[0] == _T("MENUITEM")) { file.ReadLine(buffer); buffer.TrimLeft(); buffer.TrimRight(); while (_tcsncmp(buffer, _T("MENUITEM"), 8) && _tcsncmp(buffer, _T("POPUP"), 5) && _tcsncmp(buffer, _T("BEGIN"), 5) && _tcsncmp(buffer, _T("END"), 3)) { // line += _T(" ") + buffer; CutString(line, Words); file.ReadLine(buffer); buffer.TrimLeft(); buffer.TrimRight(); } ResMenuItem newitem; if (Words.GetCount() > 1) { newitem.m_String = Words[1]; if (newitem.m_String == _T("SEPARATOR") && Words.GetCount() == 2) { } else { newitem.m_String.Replace(_T("\"\""), _T("\"")); newitem.m_ID = Words[2]; if (Words.GetCount() > 3) { newitem.m_Style = Words[3]; } } } m_vItems.Add(newitem); } } return false; }