void WriteLog(CString strFileName, CString strText) { try { CTime tm = CTime::GetCurrentTime(); CString strTime = tm.Format(_T("%Y-%m-%d %H:%M:%S")); //BOOL bFull = FALSE; CStdioFile file; if( file.Open(strFileName, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite) != 0) { file.SeekToEnd(); file.WriteString(strTime); file.WriteString(strText); file.WriteString(_T("\n\n")); //if(file.GetLength() > 2000000) // bFull = TRUE; file.Close(); } /* if(!bFull) return; if( file.Open(strFileName, CFile::modeCreate|CFile::modeReadWrite) != 0) { file.SeekToEnd(); file.WriteString(strTime); file.WriteString(strText); file.WriteString(_T("\n")); file.Close(); } */ } catch(...) { } }
void CGameDoc::OnWriteScoreFile(CString pszFileName, int mode){ CStdioFile file; CFileException e; CFileStatus status; if(mode != -1) pszFileName.Format(pszFileName+("_%d"), mode); if(CFile::GetStatus(pszFileName, status)){//파일이 존재하는 경우 읽어오기만함 if(!(file.Open(pszFileName, CFile::modeReadWrite | CFile::shareDenyNone, &e))) { TRACE( _T("Can't open file %s, error = %u\n"), pszFileName, e.m_cause ); return; } }else{//파일이 존재하지 않는다면 생성한다 if(!(file.Open(pszFileName, CFile::modeCreate | CFile::modeReadWrite | CFile::shareDenyNone, &e))) { TRACE( _T("Can't open file %s, error = %u\n"), pszFileName, e.m_cause ); return; } } file.SeekToEnd(); // 라인 끝으로 이동한다. CString time; time.Format(_T("%d:%d:%d:%d"), m_nH, m_nM, m_nS, m_nTimeSet); file.WriteString(m_strName); file.WriteString(_T(",")); file.WriteString(time); file.WriteString(_T("\n")); file.Close(); }
bool DBInterface::OpenSupplyConnection(CString ip, CString login, CString pass, CString db) { p_supply_conn = mysql_init(NULL); if (!mysql_real_connect(p_supply_conn, ip, login, pass, db, 0, NULL, 0)) { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " DBInterface::OpenSupplyConnection(...) "; log += "Failed to connect to database: Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } CloseSupplyConnection(); return false; } return true; }
bool FileMisc::AppendLineToFile(LPCTSTR szPathname, LPCTSTR szLine) { // make sure parent folder exists if (!CreateFolderFromFilePath(szPathname)) { return false; } CStdioFile file; if (file.Open(szPathname, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite)) { file.SeekToEnd(); file.WriteString(szLine); if (!_tcsstr(szLine, _T("\n"))) { file.WriteString(_T("\n")); } return true; } return false; }
void OpenLog( LPCTSTR lpstrFolder, LPCTSTR lpstrCommandLine) { try { CString csFileName, csCommand = lpstrCommandLine; if (bOpened) myFile.Close(); bOpened = FALSE; // Check if debug log is required csCommand.MakeLower(); if ((csCommand.Find( _T( "-debug")) == -1) && (csCommand.Find( _T( "/debug")) == -1)) return; csFileName.Format( _T( "%s.log"), lpstrFolder); if (!myFile.Open( csFileName, CFile::shareDenyNone|CFile::modeCreate|CFile::modeWrite|CFile::typeText)) // Unable to open file return; // Seek to End myFile.SeekToEnd(); bOpened = TRUE; } catch (CException *pEx) { pEx->Delete(); myFile.Abort(); bOpened = FALSE; } }
BOOL CReportCameraWorker::LogCaptureFile(CString FileExt) { CString strCaptureFileName = GetCaptureFileName(FileExt); // if there are capture file save it to log if (IsFileExists(strCaptureFileName)) { // save data about file to log CString strClientCameraReportFilesDirectory = GetClientCameraReportsFilesDirectory(); CString strDateTime = m_LastStartedCaptureTime.Format(_T("%a %b %d %H:%M:%S %Y")); CString strCameraLogFileName; strCameraLogFileName.Format(_T("%s\\%s.clog"), GetClientCameraReportsFilesDirectory(), m_CaptureFileName.Mid(0, 8)); TRACE(_T("CAMERA LOG [%s]\n"), strCameraLogFileName); CStdioFile LogFile; if (LogFile.Open(strCameraLogFileName, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite | CFile::typeText)) { CString strOutLogLine; //Wed Sep 28 15:52:22 2011,20110928155222.ogg,1029380,da1381f68be6f165d11358847d68a5f0 strOutLogLine.Format(_T("%s,%s,%I64u,%s\n"), strDateTime, GetFileName(strCaptureFileName), GetBinFileSizeEx(strCaptureFileName), GetMD5Signature(strCaptureFileName)); LogFile.SeekToEnd(); LogFile.WriteString(strOutLogLine); LogFile.Close(); return TRUE; } } return FALSE; }
bool DBInterface::OpenSupplyConnection() { CloseSupplyConnection(); p_supply_conn = mysql_init(NULL); if (!mysql_real_connect(p_supply_conn, m_supply_db_address, m_supply_db_user, m_supply_db_password, m_supply_db_name, 0, NULL, 0)) { /* CString errmsg = "Failed to connect to database: Error: "; errmsg += mysql_error(p_conn); TRACE(errmsg); MessageBox(NULL,errmsg,"Error",MB_OK|MB_ICONERROR); */ CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " DBInterface::OpenSupplyConnection(...) "; log += "Failed to connect to database: Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } return false; } return true; }
BOOL CTextFile::AppendFile( CString& filename, const CStringArray& contents ) /* ============================================================ Function : CTextFile::AppendFile Description : Appends contents to filename. Will create the file if it doesn't already exist. If filename is empty, the standard file dialog will be displayed, and - if OK is selected - filename will contain the selected filename on return. Return : BOOL - TRUE if OK. GetErrorMessage will return errors Parameters : CString& filename - file to write to CStringArray contents - contents to write ============================================================*/ { CStdioFile file; CFileException feError; BOOL result = TRUE; if( filename.IsEmpty() ) result = GetFilename( TRUE, filename ); if( result ) { // Write the file if( file.Open( filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate, &feError ) ) { file.SeekToEnd(); int max = contents.GetSize(); for( int t = 0 ; t < max ; t++ ) file.WriteString( contents[ t ] + m_eol ); file.Close(); } else { // Set error message TCHAR errBuff[256]; feError.GetErrorMessage( errBuff, 256 ); m_error = errBuff; result = FALSE; } } return result; }
int DBInterface::InsertFakeSupplies(VirtualProjectStatusListCtrlItem& data) { CString table = CreateFakeSupplyTable(data.m_project_name.c_str()); int ret; char temp[32]; memset(temp, 0, sizeof(temp)); CString query = "INSERT INTO "; query += table; query += " (track,supply) VALUES "; for(UINT i=0; i<data.v_track_fake_query_hit_count.size(); i++) { query += "("; query += ultoa(i, temp, 10); query += ","; query += ultoa(data.v_track_fake_query_hit_count[i],temp,10); query += ")"; if(i != data.v_track_fake_query_hit_count.size()-1) query += ","; } ret = mysql_query(p_supply_conn,query); if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " InsertFakeSupplies(...) "; log += query; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE(query); TRACE("\n"); } return ret; }
void CTKLauncherDlg::CrashLog() { CStdioFile file; if(file.Open("crash_log.txt", CFile::modeWrite|CFile::modeCreate|CFile::modeNoTruncate|CFile::typeText|CFile::shareDenyWrite)!=0) { file.SeekToEnd(); CString time = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); file.WriteString(time); file.WriteString("\n"); file.Close(); } }
void Trace(int n) { if(!((CXFLR5App*)AfxGetApp())->bTrace) return; CStdioFile tf; tf.Open(((CXFLR5App*)AfxGetApp())->TraceFileName, CFile::modeWrite | CFile::typeText); tf.SeekToEnd(); SYSTEMTIME tm; GetLocalTime(&tm); CString str; str.Format("time = %2d:%2d:%2d.%03d nnn=%d \r\n", tm.wHour, tm.wMinute, tm.wSecond, tm.wMilliseconds,n); tf.WriteString(str); tf.Close(); }
BOOL DealerHistoryLog::SetDealerLog(CString log) { CStdioFile file; CString strfilename; GetFileName(strfilename); if( !file.Open(strfilename, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite) ) { return FALSE; } file.SeekToEnd(); // file.Write("\r\n",2); file.Write(log, log.GetLength()); file.Close(); return TRUE; }
BOOL CLoginDlg::PreTranslateMessage(MSG* pMsg) { // TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다. if(pMsg->message == WM_KEYDOWN) { if(pMsg->wParam == 'A' && GetKeyState(VK_CONTROL) < 0) { CString accountLevel, inputName, inputPwd, inputData; CStdioFile accountFile; unsigned char dataForWrite[1024] = ""; int i = 0, len = 0; if(m_rdUser.GetCheck() == TRUE) accountLevel.Format(_T("%s"), USER_ACCOUNT); else accountLevel.Format(_T("%s"), ADMIN_ACCOUNT); m_edtLoginName.GetWindowText(inputName); m_edtLoginPwd.GetWindowText(inputPwd); if(inputName.IsEmpty() || inputPwd.IsEmpty()) return CDialog::PreTranslateMessage(pMsg); inputData.Format(_T("%s:%s:%s"),inputName, inputPwd, accountLevel); memcpy(dataForWrite, (unsigned char*)(LPCTSTR)inputData, inputData.GetLength()); len = inputData.GetLength(); RTrace(_T("Input Data = %s\n"), inputData); for(i = 0; i < len; i++) { dataForWrite[i] = ~dataForWrite[i]; } dataForWrite[i] = 0x0a; RTrace(_T("Conversioned Data = %s\n"), dataForWrite); accountFile.Open(LOGIN_FILE_NAME, CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate | CFile::typeBinary); accountFile.SeekToEnd(); accountFile.Write(dataForWrite, i + 1); accountFile.Close(); } } return CDialog::PreTranslateMessage(pMsg); }
void DeicepadGroup::RemoveApproachingFlight( AirsideFlightInSim* pFlight ) { #ifdef _DEBUG CStdioFile f; f.Open(_T("C:\\removed_flight.txt"), CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite); f.SeekToEnd(); char cTmp[1024]; pFlight->GetFlightInput()->getAirline(cTmp); pFlight->GetFlightInput()->getDepID(cTmp + strlen(cTmp)); f.WriteString(cTmp); f.WriteString(_T("\n")); #endif AirsideFlightList::iterator ite = std::remove(m_vFlightApproaching.begin(), m_vFlightApproaching.end(), pFlight); ASSERT(ite != m_vFlightApproaching.end() && ite + 1 == m_vFlightApproaching.end()); m_vFlightApproaching.erase(ite, m_vFlightApproaching.end()); }
void DeicepadGroup::AddApproachingFlight( AirsideFlightInSim* pFlight ) { if (m_vFlightApproaching.end() == std::find(m_vFlightApproaching.begin(), m_vFlightApproaching.end(), pFlight)) { #ifdef _DEBUG CStdioFile f; f.Open(_T("C:\\added_flight.txt"), CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite); f.SeekToEnd(); char cTmp[1024]; pFlight->GetFlightInput()->getAirline(cTmp); pFlight->GetFlightInput()->getDepID(cTmp + strlen(cTmp)); f.WriteString(cTmp); f.WriteString(_T("\n")); #endif m_vFlightApproaching.push_back(pFlight); } }
void CGUAHAODlg::OnButton4() { FILE *fp; int i,j; char zhanghao[20],mima[20]; UpdateData(TRUE); char* pFileName="bingli.txt"; CStdioFile bingli; CFileException fileException; if((fp=fopen("yonghu.txt","r"))==NULL) { MessageBox("存储文件出错!"); exit(0); } fscanf(fp,"%s %s",zhanghao,mima); fclose(fp); i=strlen(zhanghao); j=strlen(mima); if(bingli.Open(pFileName,CFile::modeReadWrite |CFile::typeText)) { m_strnum6=m_5; m_strnum7=m_7; m_strnum8=m_11; bingli.SeekToEnd(); bingli.Write(zhanghao,i); bingli.WriteString(" "); bingli.Write(mima,j); bingli.WriteString(" "); bingli.Write(m_strnum6,m_strnum6.GetLength()); bingli.WriteString(" "); bingli.Write(m_strnum7,m_strnum7.GetLength()); bingli.WriteString(" "); bingli.Write(m_strnum8,m_strnum8.GetLength()); bingli.WriteString(" "); bingli.WriteString("\n"); } bingli.Close(); MessageBox("挂号成功!"); CDialog::OnOK(); CLOGDlg dlg; dlg.DoModal(); }
void Trace(CString msg, double f) { if(!((CXFLR5App*)AfxGetApp())->bTrace) return; CStdioFile tf; CString strong; strong.Format(" %f",f); strong = msg + strong; tf.Open(((CXFLR5App*)AfxGetApp())->TraceFileName, CFile::modeWrite | CFile::typeText); tf.SeekToEnd(); SYSTEMTIME tm; GetLocalTime(&tm); CString str; str.Format("time = %2d:%2d:%2d.%03d ", tm.wHour, tm.wMinute, tm.wSecond, tm.wMilliseconds); str += strong; str += "\r\n"; tf.WriteString(str); tf.Close(); }
void CBatchSNDlg::WriteSerialNumber(unsigned long SN){ CStdioFile file; CString filepath; CString SerialDate; CTime time = CTime::GetCurrentTime(); SerialDate.Format(_T("\n%d,%d-%d-%d %d:%d:%d"),SN,time.GetYear(),time.GetMonth(),time.GetDay(),time.GetHour(),time.GetMinute(),time.GetSecond()); filepath=g_strExePth+_T("Sensor Serial Record.txt"); if(!file.Open(filepath, CFile::shareDenyNone|CFile::modeReadWrite)) { return ; } file.SeekToEnd(); file.WriteString(SerialDate.GetBuffer()); // file.Flush(); file.Close(); }
bool CLogFile::Close() { try { // limit log file growth size_t maxLines = (DWORD)m_maxlines; size_t newLines = m_newLines.size(); TrimFile (DWORD(max (maxLines, newLines) - newLines)); // append new info CStdioFile file; int retrycounter = 10; // try to open the file for about two seconds - some other TSVN process might be // writing to the file and we just wait a little for this to finish while (!file.Open(m_logfile.GetWinPath(), CFile::typeText | CFile::modeReadWrite | CFile::modeCreate | CFile::modeNoTruncate) && retrycounter) { retrycounter--; Sleep(200); } if (retrycounter == 0) return false; file.SeekToEnd(); for (std::deque<CString>::const_iterator it = m_newLines.begin(); it != m_newLines.end(); ++it) { file.WriteString(*it); file.WriteString(L"\n"); } file.Close(); } catch (CFileException* pE) { CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CFileException saving log file\n"); pE->Delete(); return false; } return true; }
BOOL CDlgExportDownloads::ExportDownloads_ToURLListFile(LPCSTR pszFile, DLDS_LIST* pvpDlds, BOOL bAppend) { CStdioFile file; UINT mode = CFile::modeWrite; if (bAppend == FALSE || GetFileAttributes (pszFile) == DWORD (-1)) mode |= CFile::modeCreate; if (FALSE == file.Open (pszFile, mode)) { ::MessageBox (NULL, LS (L_CANTOPENFILE), LS (L_ERR), MB_ICONERROR); return FALSE; } if ((mode & CFile::modeCreate) == 0) file.SeekToEnd (); for (size_t i = 0; i < pvpDlds->size (); i++) { try { file.WriteString (pvpDlds->at (i)->pMgr->get_URL ()); file.WriteString ("\n"); } catch (const std::exception& ex) { ASSERT (FALSE); vmsLogger::WriteLog("CDlgExportDownloads::ExportDownloads_ToURLListFile " + tstring(ex.what())); return FALSE; } catch (...) { ASSERT (FALSE); vmsLogger::WriteLog("CDlgExportDownloads::ExportDownloads_ToURLListFile unknown exception"); return FALSE; } } return TRUE; }
////////////////////////////////// // addFaceImgArray():添加固定格式训练、测试图片信息(编号、文件名)到txt文件 // // BOOL faceRecognition::addFaceImgArray(char * fileName,char * imgName){ // CStdioFile fwrite; // CString temp=CString(imgName); // temp=temp+"\n"; // try{ // if(fwrite.Open(fileName,CStdioFile::modeReadWrite)==FALSE) // AfxMessageBox("打开文件 "+CString(fileName)+" 失败!!"); // fwrite.SeekToEnd(); // fwrite.WriteString(temp); //自动加上换行符号 // //close() // fwrite.Close(); // }catch(CFileException e) // { // AfxMessageBox("文件写入失败::"+CString(fileName)); // } // return true; // } ////////////////////////////////// // addFaceImgArray():添加固定格式训练、测试图片信息(编号、文件名)到txt文件 // 上面重载函数 BOOL faceRecognition::addFaceImgArray(char *name,bool flag){ CStdioFile fwrite; CString temp=CString(name); temp=temp+"\n";//自动加上换行符号 try{ if(flag==true) {//for train if(fwrite.Open(learnFileListPath,CFile::modeNoTruncate|CStdioFile::modeReadWrite|CStdioFile::modeCreate)==FALSE) AfxMessageBox("打开文件 "+CString(learnFileListPath)+" 失败!!"); }else{ if(fwrite.Open(testFileListPath,CStdioFile::modeReadWrite)==FALSE) AfxMessageBox("打开文件 "+CString(testFileListPath)+" 失败!!"); } fwrite.SeekToEnd(); fwrite.WriteString(temp); //close() fwrite.Close(); }catch(CFileException e) { AfxMessageBox("文件写入失败::"+CString(name)); } return true; }
int DBInterface::InsertRawGnutellaSupply(/*CString& file_name,UINT file_size,*/ int ip, CString& timestamp, char* sha1,/* GUID& guid,*/ CString& project,int track/*, bool spoof*/) { //file_name.Replace("\\","\\\\"); //file_name.Replace("'", "\\'"); //truncate the project name if its length is greater than 50 if(project.GetLength() > 50) { project.Truncate(50); } CString table = "SUPPLY_TABLE_"; table += project; table.Replace('\\','_'); // replace the backslash with _ table.Replace('\'', '_'); // replace the single quote "'" with _ table.Replace(' ', '_'); table.Replace('-', '_'); table.Replace('&', '_'); table.Replace('!', '_'); table.Replace('$', '_'); table.Replace('@', '_'); table.Replace('%', '_'); table.Replace('(', '_'); table.Replace(')', '_'); table.Replace('+', '_'); table.Replace('~', '_'); table.Replace('*', '_'); table.Replace('.', '_'); table.Replace(',', '_'); table.Replace('?', '_'); table.Replace(':', '_'); table.Replace(';', '_'); table.Replace('"', '_'); table.Replace('/', '_'); table.Replace('#', '_'); //UINT guid_index = GetGUIDIndex(guid); //get the guid index from the guid index table; int ret; char temp[32]; memset(temp, 0, sizeof(temp)); CString query = "INSERT IGNORE INTO "; query += table; query += " (timestamp,sha1,track,ip) VALUES ('"; query += timestamp; query += "','"; query += sha1; query += "',"; query += itoa(track,temp,10); query += ","; query += itoa(ip,temp,10); query += ")"; ret = mysql_query(p_supply_conn,query); if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " InsertRawGnutellaSupply(...) "; log += query; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); if(log.Find("doesn't exist")>=0) { CreateProjectSupplyTable(project); mysql_query(p_supply_conn,query); } } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE(query); TRACE("\n"); } return ret; }
int DBInterface::InsertRawSupply(vector<QueryHit>& query_hits) { // file_name.Replace("\\","\\\\"); // file_name.Replace("'", "\\'"); //truncate the project name if its length is greater than 50 CString project = query_hits[0].m_project; if(project.GetLength() > 50) { project.Truncate(50); } CString table = "SUPPLY_TABLE_"; table += project; table.Replace('\\','_'); // replace the backslash with _ table.Replace('\'', '_'); // replace the single quote "'" with _ table.Replace(' ', '_'); table.Replace('-', '_'); table.Replace('&', '_'); table.Replace('!', '_'); table.Replace('$', '_'); table.Replace('@', '_'); table.Replace('%', '_'); table.Replace('(', '_'); table.Replace(')', '_'); table.Replace('+', '_'); table.Replace('~', '_'); table.Replace('*', '_'); table.Replace('.', '_'); table.Replace(',', '_'); table.Replace('?', '_'); table.Replace(':', '_'); table.Replace(';', '_'); table.Replace('"', '_'); table.Replace('/', '_'); table.Replace('#', '_'); int ret; char temp[32]; memset(temp, 0, sizeof(temp)); CString query = "INSERT INTO "; query += table; query += " (filename,filesize,hash,ip,port,search_id,timestamp,track,bitrate,frequency,duration) VALUES "; for(UINT i=0; i<query_hits.size(); i++) { query += "('"; CString filename = query_hits[i].m_filename; filename.Replace("\\", "\\\\"); filename.Replace("'", "\\'"); query+= filename; query += "',"; query += ultoa(query_hits[i].m_file_size, temp, 10); query += ",'"; char hash[41]; memset(&hash,0,sizeof(hash)); for (int j = 0; j < 16; j++) { sprintf((char *)&hash[j*2],"%02x",((int)query_hits[i].m_hash[j])&0xFF); } query += hash; query += "',"; query += itoa(query_hits[i].m_ip,temp,10); query += ","; query += itoa(query_hits[i].m_port,temp,10); query += ","; query += itoa(query_hits[i].m_search_id,temp,10); query += ",'"; CString timestamp = query_hits[i].m_timestamp.Format("%Y%m%d%H%M%S"); query += timestamp; query += "',"; query += itoa(query_hits[i].m_track,temp,10); query += ","; query += itoa(query_hits[i].m_bitrate,temp,10); query += ","; query += itoa(query_hits[i].m_sample_frequency,temp,10); query += ","; query += itoa(query_hits[i].m_duration,temp,10); query += ")"; if(i != query_hits.size()-1) query += ","; } ret = mysql_query(p_supply_conn,query); if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " InsertRawSupply(...) "; log += query; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE(query); TRACE("\n"); } return ret; }
int DBInterface::CreateProjectSupplyTable(CString& project_supply_table) { project_supply_table.Replace('\\','_'); // replace the backslash with _ project_supply_table.Replace('\'', '_'); // replace the single quote "'" with _ project_supply_table.Replace(' ', '_'); project_supply_table.Replace('-', '_'); project_supply_table.Replace('&', '_'); project_supply_table.Replace('!', '_'); project_supply_table.Replace('$', '_'); project_supply_table.Replace('@', '_'); project_supply_table.Replace('%', '_'); project_supply_table.Replace('(', '_'); project_supply_table.Replace(')', '_'); project_supply_table.Replace('+', '_'); project_supply_table.Replace('~', '_'); project_supply_table.Replace('*', '_'); project_supply_table.Replace('.', '_'); project_supply_table.Replace(',', '_'); project_supply_table.Replace('?', '_'); project_supply_table.Replace(':', '_'); project_supply_table.Replace(';', '_'); project_supply_table.Replace('"', '_'); project_supply_table.Replace('/', '_'); project_supply_table.Replace('#', '_'); //truncate the project name if its length is greater than 50 if(project_supply_table.GetLength() > 50) { project_supply_table.Truncate(50); } CString table = "SUPPLY_TABLE_"; table += project_supply_table; int ret; //create table IF NOT EXISTS table_name (track tinyint unsigned, query varchar(255), timestamp timestamp, index (track,timestamp), index(timestamp,track)) CString query = "create table IF NOT EXISTS "; query += table; query += " (filename varchar(255),filesize int unsigned,hash varchar(33),ip int,port smallint unsigned,search_id int unsigned,timestamp timestamp,track tinyint unsigned,bitrate smallint, frequency int, duration int,index(search_id, timestamp,track),index(timestamp,search_id,track),index(hash,track),index(hash,track),index(track,hash))"; ret = mysql_query(p_supply_conn, query); if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " CreateProjectSupplyTable(...) "; log += query; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE(query); TRACE("\n"); } return ret; }
int DBInterface::InsertRawGnutellaDemand(vector<Query>& project_queries) { if(!project_queries.size()) return 0; //truncate the project name if its length is greater than 50 if(project_queries[0].m_project.GetLength() > 50) { project_queries[0].m_project.Truncate(50); } //query.Replace("\\","\\\\"); //query.Replace("'", "\\'"); CString table = "DEMAND_TABLE_"; table += project_queries[0].m_project; table.Replace('\\','_'); // replace the backslash with _ table.Replace('\'', '_'); // replace the single quote "'" with _ table.Replace(' ', '_'); table.Replace('-', '_'); table.Replace('&', '_'); table.Replace('!', '_'); table.Replace('$', '_'); table.Replace('@', '_'); table.Replace('%', '_'); table.Replace('(', '_'); table.Replace(')', '_'); table.Replace('+', '_'); table.Replace('~', '_'); table.Replace('*', '_'); table.Replace('.', '_'); table.Replace(',', '_'); table.Replace('?', '_'); table.Replace(':', '_'); table.Replace(';', '_'); table.Replace('"', '_'); table.Replace('/', '_'); table.Replace('#', '_'); int ret; char temp[32]; memset(temp, 0, sizeof(temp)); CString query_str = "INSERT INTO "; query_str += table; query_str += " (track,query,timestamp) VALUES "; for(UINT i=0; i<project_queries.size(); i++) { query_str += "("; query_str += itoa(project_queries[i].m_track, temp, 10); query_str += ",'"; project_queries[i].m_query.Replace("\\","\\\\"); project_queries[i].m_query.Replace("'", "''"); query_str += project_queries[i].m_query; query_str += "','"; CString timestamp = project_queries[i].m_timestamp.Format("%Y%m%d%H%M%S"); query_str += timestamp; query_str += "')"; if(i != project_queries.size()-1) { query_str += ","; } } ret = mysql_query(p_demand_conn,query_str); if(mysql_error(p_demand_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " InsertRawGnutellaDemand(...) "; log += query_str; log += "\n"; log += "Error: "; log += mysql_error(p_demand_conn); log += "\n\n"; file.WriteString(log); file.Close(); if(log.Find("doesn't exist")>=0) { CreateProjectDemandTable(project_queries[0].m_project); mysql_query(p_demand_conn,query_str); } } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_demand_conn)); TRACE("\n"); TRACE(query_str); TRACE("\n"); } return ret; }
int DBInterface::InsertRawGnutellaSupply(vector<QueryHit>& query_hits) { // file_name.Replace("\\","\\\\"); // file_name.Replace("'", "\\'"); //truncate the project name if its length is greater than 50 CString project = query_hits[0].m_project; if(project.GetLength() > 50) { project.Truncate(50); } CString table = "SUPPLY_TABLE_"; table += project; table.Replace('\\','_'); // replace the backslash with _ table.Replace('\'', '_'); // replace the single quote "'" with _ table.Replace(' ', '_'); table.Replace('-', '_'); table.Replace('&', '_'); table.Replace('!', '_'); table.Replace('$', '_'); table.Replace('@', '_'); table.Replace('%', '_'); table.Replace('(', '_'); table.Replace(')', '_'); table.Replace('+', '_'); table.Replace('~', '_'); table.Replace('*', '_'); table.Replace('.', '_'); table.Replace(',', '_'); table.Replace('?', '_'); table.Replace(':', '_'); table.Replace(';', '_'); table.Replace('"', '_'); table.Replace('/', '_'); table.Replace('#', '_'); int ret; char temp[32]; memset(temp, 0, sizeof(temp)); CString query = "INSERT IGNORE INTO "; query += table; query += " (timestamp,sha1,track,ip) VALUES "; for(UINT i=0; i<query_hits.size(); i++) { query += "('"; CString timestamp = query_hits[i].m_timestamp.Format("%Y%m%d%H%M%S"); query += timestamp; query += "','"; CString sha1 = query_hits[i].m_sha1; sha1.Replace("\\", "\\\\"); sha1.Replace("'", "''"); query += sha1; query += "',"; query += itoa(query_hits[i].m_track,temp,10); query += ","; query += itoa(query_hits[i].m_ip,temp,10); query += ")"; if(i != query_hits.size()-1) { query += ","; } } ret = mysql_query(p_supply_conn,query); if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " InsertRawGnutellaSupply(...) "; log += query; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); if(log.Find("doesn't exist")>=0) { CreateProjectSupplyTable(project); mysql_query(p_supply_conn,query); } } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE(query); TRACE("\n"); } return ret; }
bool SupplyEntryDBInterface::RetrieveSupplyEntry(ProjectKeywords& keyword, vector<QueryHit>& supplies, HWND hwnd) { int ret = -1; CString project = keyword.m_project_name.c_str(); // project.Replace("\\","\\\\"); // replace the backslash with a "_" // project.Replace("\'", "\\\'"); // replace the single quote "'" if(project.GetLength() > 50) { project.Truncate(50); } CString table = "SUPPLY_TABLE_"; table += project; table.Replace('\\','_'); // replace the backslash with _ table.Replace('\'', '_'); // replace the single quote "'" with _ table.Replace(' ', '_'); table.Replace('-', '_'); table.Replace('&', '_'); table.Replace('!', '_'); table.Replace('$', '_'); table.Replace('@', '_'); table.Replace('%', '_'); table.Replace('(', '_'); table.Replace(')', '_'); table.Replace('+', '_'); table.Replace('~', '_'); table.Replace('*', '_'); table.Replace('.', '_'); table.Replace(',', '_'); table.Replace('?', '_'); table.Replace(':', '_'); table.Replace(';', '_'); table.Replace('"', '_'); table.Replace('/', '_'); table.Replace('#', '_'); char temp[32]; CString query_str; int track; for(int i=0; i==0 || i<keyword.m_supply_keywords.v_keywords.size(); i++) { if(keyword.m_supply_keywords.v_keywords.size() > 0) track = keyword.m_supply_keywords.v_keywords[i].m_track; else track = 0; //post the query status to the main window char status[256+1]; sprintf(status, "%s - Track: %d", keyword.m_project_name.c_str(), track); PostMessage(hwnd,WM_SUPPLY_MANAGER_THREAD_PROJECT,(WPARAM)status,0); query_str = "SELECT distinct hash, filename, filesize, bitrate, frequency, duration, count(*) as total from "; query_str += table; query_str += " where track = "; query_str += itoa(track, temp, 10); if(keyword.m_search_type == ProjectKeywords::audio) query_str += " and filesize <= 10000000 "; query_str += " group by hash"; query_str += " order by total desc limit "; //if this is single, doubling up the limit if(track!=0) { if(keyword.m_supply_keywords.v_keywords[i].m_single == true) query_str += itoa(400, temp, 10); else //query_str += itoa(200, temp, 10); continue; //not protecting non-singles } else query_str += itoa(200, temp, 10); ret = mysql_query(p_supply_conn, query_str); if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Supply_Entry_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " RetrieveSupplyEntry(...) "; log += query_str; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } else { DWORD error = GetLastError(); //MessageBox(NULL, "File Open Error: SQL_Supply_Entry_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE(query_str); TRACE("\n"); //retry this query and reconnect to db mysql_ping(p_supply_conn); i--; if(i<0) i=0; continue; } MYSQL_RES *res=NULL; MYSQL_ROW row; res=mysql_store_result(p_supply_conn); // allocates memory if(res != NULL) { UINT num_row = (UINT)mysql_num_rows(res); if(num_row > 0) { while ((row = mysql_fetch_row(res))) { QueryHit info; if(row[0]!=NULL) { HashConversion fthash; fthash.HashDecode16(row[0]); memset(&info.m_hash,0,sizeof(info.m_hash)); memcpy(info.m_hash,fthash.m_data,sizeof(info.m_hash)); } if(row[1]!=NULL) info.m_filename = row[1]; if(row[2]!=NULL) info.m_file_size = atol(row[2]); if(row[3]!=NULL) info.m_bitrate = atoi(row[3]); if(row[4]!=NULL) info.m_sample_frequency = atoi(row[4]); if(row[5]!=NULL) info.m_duration = atoi(row[5]); info.m_track = track; info.m_project_id = keyword.m_id; info.m_project = keyword.m_project_name.c_str(); switch(keyword.m_search_type) { case ProjectKeywords::search_type::audio: { info.m_media_type = MEDIA_TYPE_AUDIO; break; } case ProjectKeywords::search_type::video: { info.m_media_type = MEDIA_TYPE_VIDEO; break; } case ProjectKeywords::search_type::software: { info.m_media_type = MEDIA_TYPE_SOFTWARE; break; } } /* int popularity=0; //share more popular title if(row[3]!=NULL) popularity=atoi(row[3]); popularity /= 100; if(popularity > 100) popularity = 100; if(popularity <= 0) popularity = 1; for(int j=0;j<popularity;j++) supplies.push_back(info); */ supplies.push_back(info); } } } mysql_free_result(res); // free memory } if(ret==0) return true; else return false; }
int DBInterface::InsertDistinctFastTrackSupply(vector<QueryHit>& query_hits,const char* today_date) { // file_name.Replace("\\","\\\\"); // file_name.Replace("'", "\\'"); //truncate the project name if its length is greater than 50 CString project = query_hits[0].m_project; if(project.GetLength() > 50) { project.Truncate(50); } CString table = "SUPPLY_TABLE_"; table += project; table.Replace('\\','_'); // replace the backslash with _ table.Replace('\'', '_'); // replace the single quote "'" with _ table.Replace(' ', '_'); table.Replace('-', '_'); table.Replace('&', '_'); table.Replace('!', '_'); table.Replace('$', '_'); table.Replace('@', '_'); table.Replace('%', '_'); table.Replace('(', '_'); table.Replace(')', '_'); table.Replace('+', '_'); table.Replace('~', '_'); table.Replace('*', '_'); table.Replace('.', '_'); table.Replace(',', '_'); table.Replace('?', '_'); table.Replace(':', '_'); table.Replace(';', '_'); table.Replace('"', '_'); table.Replace('/', '_'); table.Replace('#', '_'); int ret; char temp[32]; memset(temp, 0, sizeof(temp)); CString query = "INSERT IGNORE INTO "; query += table; query += " (filename,filesize,hash,timestamp,track) VALUES "; for(UINT i=0; i<query_hits.size(); i++) { query += "('"; CString filename = query_hits[i].m_filename; filename.Replace("\\", "\\\\"); filename.Replace("'", "\\'"); query+= filename; query += "',"; query += ultoa(query_hits[i].m_file_size, temp, 10); query += ",'"; char hash[41]; memset(&hash,0,sizeof(hash)); for (int j = 0; j < 20; j++) { sprintf((char *)&hash[j*2],"%02x",((int)query_hits[i].m_hash[j])&0xFF); } query += hash; query += "','"; CString timestamp = query_hits[i].m_timestamp.Format("%Y%m%d%H%M%S"); query += timestamp; query += "',"; query += itoa(query_hits[i].m_track,temp,10); query += ")"; if(i != query_hits.size()-1) query += ","; } ret = mysql_query(p_supply_conn,query); #ifdef _DEBUG if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " InsertDistinctFastTrackSupply(...) "; log += query; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE(query); TRACE("\n"); } #endif CString daily_table = "fasttrack_daily_unique_hashes."; CString daily_table_name = today_date + table; if(daily_table_name.GetLength() > 64) { daily_table_name.Truncate(64); } daily_table += daily_table_name; query = "create table IF NOT EXISTS "; query += daily_table; query += " (filename varchar(255),filesize int unsigned,hash varchar(41) NOT NULL PRIMARY KEY,timestamp timestamp,track int unsigned)"; ret = mysql_query(p_supply_conn,query); query = "INSERT IGNORE INTO "; query += daily_table; query += " (filename,filesize,hash,timestamp,track) VALUES "; for(UINT i=0; i<query_hits.size(); i++) { query += "('"; CString filename = query_hits[i].m_filename; filename.Replace("\\", "\\\\"); filename.Replace("'", "\\'"); query+= filename; query += "',"; query += ultoa(query_hits[i].m_file_size, temp, 10); query += ",'"; char hash[41]; memset(&hash,0,sizeof(hash)); for (int j = 0; j < 20; j++) { sprintf((char *)&hash[j*2],"%02x",((int)query_hits[i].m_hash[j])&0xFF); } query += hash; query += "','"; CString timestamp = query_hits[i].m_timestamp.Format("%Y%m%d%H%M%S"); query += timestamp; query += "',"; query += itoa(query_hits[i].m_track,temp,10); query += ")"; if(i != query_hits.size()-1) query += ","; } ret = mysql_query(p_supply_conn,query); #ifdef _DEBUG if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " InsertDistinctFastTrackSupply(...) "; log += query; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE(query); TRACE("\n"); } #endif return ret; }
UINT DBInterface::GetGUIDIndex(GUID& guid) { int ret =0; UINT guid_index=0; CString query = "SELECT guid_index from "; query += GNUTELLA_GUID_INDEX_TALBE; query += " where guid='"; char escape_string[sizeof(GUID)*2+1]; memset(&escape_string,0,sizeof(escape_string)); UINT guid_size = mysql_real_escape_string(p_supply_conn, escape_string, (const char*)&guid, sizeof(GUID)); UINT query_length = (UINT)query.GetLength() + guid_size + strlen("'")+1; char* temp_buf = new char[query.GetLength()+1]; memset(temp_buf,0,query.GetLength()+1); strcpy(temp_buf,query); byte* query_buf = new byte[query_length]; memset(query_buf, 0, query_length); memcpy(query_buf, temp_buf, query.GetLength()); memcpy(&query_buf[query.GetLength()], &escape_string, guid_size); query_buf[query_length-2] = '\''; query_buf[query_length-1] = '\0'; ret = mysql_real_query(p_supply_conn, (const char*)query_buf, query_length); if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " GetGUIDIndex(...) "; log += (const char*)query_buf; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE((const char*)query_buf); TRACE("\n"); return 0; } else { MYSQL_RES *res_set; MYSQL_ROW row; unsigned int i; res_set = mysql_store_result(p_supply_conn); if(res_set != NULL) { unsigned int numrows = (unsigned int)mysql_num_rows(res_set); while ((row = mysql_fetch_row(res_set)) != NULL) { for (i=0; i<mysql_num_fields(res_set); i++) { sscanf((char*)row[i], "%u", &guid_index); } } mysql_free_result(res_set); // free memory } } delete temp_buf; delete query_buf; return guid_index; }
int DBInterface::InsertGUID(char* table, GUID& guid, CString& project, const char* timestamp) { project.Replace("\\","_"); // replace the backslash with a "_" project.Replace("\'", "\\\'"); // replace the single quote "'" int ret; CString query = "INSERT INTO "; query += table; query += " (project,timestamp,guid) VALUES ('"; query += project; query += "','"; query += timestamp; query += "','"; char escape_string[sizeof(GUID)*2+1]; memset(&escape_string,0,sizeof(escape_string)); UINT guid_size = mysql_real_escape_string(p_supply_conn, escape_string, (const char*)&guid, sizeof(GUID)); UINT query_length = (UINT)query.GetLength() + guid_size + strlen("')")+1; char* temp_buf = new char[query.GetLength()+1]; memset(temp_buf,0,query.GetLength()+1); strcpy(temp_buf,query); byte* query_buf = new byte[query_length]; memset(query_buf, 0, query_length); memcpy(query_buf, temp_buf, query.GetLength()); memcpy(&query_buf[query.GetLength()], &escape_string, guid_size); memcpy(&query_buf[query.GetLength()+guid_size], "')", 2); query_buf[query_length-1] = '\0'; ret = mysql_real_query(p_supply_conn, (const char*)query_buf, query_length); if(mysql_error(p_supply_conn)[0] != '\0') { CStdioFile file; if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0) { file.SeekToEnd(); CString log; log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"); log += " InsertGUID(...) "; log += (const char*)query_buf; log += "\n"; log += "Error: "; log += mysql_error(p_supply_conn); log += "\n\n"; file.WriteString(log); file.Close(); } else { DWORD error = GetLastError(); MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK); } TRACE(mysql_error(p_supply_conn)); TRACE("\n"); TRACE((const char*)query_buf); TRACE("\n"); } delete temp_buf; delete query_buf; return ret; }