Esempio n. 1
0
void CSVString( const TStringVector &sv, TString &string, char adelimiter )
{
  TString     word;
  int        i;
  int        n = sv.size();
  int        totallength = 0;
//  int        pos = 0;
  char       *pos;

  if( sv.size()==0 ) {
    string = "\"\"";
    return;
  }

  for( unsigned int i=0; i<n; i++ )
  {
    word = CSVString( sv[i], adelimiter );
    totallength += word.Length();
  }
  if( n>0 )
    totallength += n-1;

  string.SetLength( totallength );
  pos = string.c_str();
  for( unsigned int i=0; i<n; i++ )
  {
    word = CSVString( sv[i], adelimiter );
    strcpy( pos, word.c_str() );
    pos += word.Length();
    if( i<(n-1) ) {
      *pos = adelimiter;
      pos++;
    }
  }
}
Esempio n. 2
0
void TStringVector2TStringSet( const TStringVector& tstringVector, TStringSet& tstringSet )
{
	TStringVector::const_iterator iter = tstringVector.begin();
	for (; iter != tstringVector.end(); iter++)
	{
		tstringSet.insert(*iter);
	}
}
void
CMsWin32Editbox::AppendLines( TStringVector& lines )
{GUCEF_TRACE;

    TStringVector::iterator i = lines.begin();
    while ( i != lines.end() )
    {
        AppendLine( (*i) );
        ++i;
    }    
}
TStringSet
VectorToSet( const TStringVector& src )
{GUCEF_TRACE;

    TStringSet set;
    TStringVector::const_iterator i = src.begin();
    while ( i != src.end() )
    {
        set.insert( (*i) );
        ++i;
    }
    return set;
}
Esempio n. 5
0
// D: convert a string list of attribute values into a STRING2STRING 
//    representation
STRING2STRING StringToS2SHash(string sString, string sSeparator, 
                              string sEquals) {
    // extract the pairs
    TStringVector vsPairs = 
        PartitionString(sString, (char *)sSeparator.c_str());
    // form the hash
    STRING2STRING s2s;
    for(unsigned int i = 0; i < vsPairs.size(); i++) {
        string sAttr, sValue;
        SplitOnFirst(vsPairs[i], (char *)sEquals.c_str(), sAttr, sValue);        
        s2s.insert(STRING2STRING::value_type(Trim(sAttr), Trim(sValue)));
    }
    // finally, return the constructed hash
    return s2s;
}
Esempio n. 6
0
BOOL Shell::RefershPartitions()
{
	for (int i = 0; i < 26; i++)
	{
		m_partitions[i].bValid = FALSE;
	}

	CommData request;
	request.SetMsgID(MSGID_DISKS);
	CommData commData;
	if (! AskAndWaitForReply(request, commData))
	{
		return FALSE;
	}

	DECLARE_STR_PARAM(result);
	TStringVector partitionVector;
	splitByChar(result.c_str(), partitionVector, ':');
	BOOL bFoundOne = FALSE;
	TStringVector::iterator partitionIter = partitionVector.begin();
	for (; partitionIter != partitionVector.end(); partitionIter++)
	{
		tstring& partitionStr = *partitionIter;

		TStringVector infoVector;
		splitByChar(partitionStr.c_str(), infoVector, '|');
		if (infoVector.size() != 4) continue;

		//partition(str)|drivertype(uint)|totalbytes(uint64)|freebytes(uint64):
		if (infoVector[0].size() == 0) continue;
		TCHAR partition = infoVector[0][0];
		int index = 0;
		if (partition >= 'a' && partition <= 'z') index = partition - 'a';
		else if (partition >= 'A' && partition <= 'Z') index = partition - 'A';
		else continue;

		if (1 != _stscanf_s(infoVector[1].c_str(), _T("%u"), &m_partitions[index].drivertype)) continue;
		if (1 != _stscanf_s(infoVector[2].c_str(), _T("%I64u"), &m_partitions[index].totalBytes)) continue;
		if (1 != _stscanf_s(infoVector[3].c_str(), _T("%I64u"), &m_partitions[index].freeBytes)) continue;
		m_partitions[index].curPath = ('A' + index);
		m_partitions[index].curPath += _T(":\\");

		m_partitions[index].bValid = TRUE;
		bFoundOne = TRUE;
	}

	return bFoundOne;
}
Esempio n. 7
0
bool
CPing::Start( const CORE::CString& remoteHost           ,
              const Int32 maxPings /* = 0 */            ,
              const UInt32 bytesToSend /* = 32 */       ,
              const UInt32 timeout /* = 1000 */         ,
              const UInt32 minimalPingDelta /* = 500 */ )
{GUCEF_TRACE;

    TStringVector hostList;
    hostList.push_back( remoteHost );
    return Start( hostList         ,
                  maxPings         ,
                  bytesToSend      ,
                  timeout          ,
                  minimalPingDelta );
}
void
BuildSourceFileList( const CORE::CString& srcDir                 ,
                     const TStringVector& listOfRootSubDirsToUse ,
                     TMatchEntryVector& matches                  ,
                     const TStringSet* fileTypes                 ,
                     const TStringSet* dirsToIgnore              )
{GUCEF_TRACE;

    // get a list of all the files
    TFileEntryVector files;
    BuildFileList( srcDir, files, fileTypes, dirsToIgnore );
    
    TStringVector::const_iterator i = listOfRootSubDirsToUse.begin();
    while ( i != listOfRootSubDirsToUse.end() )
    {
        CORE::CString subRoot = srcDir;
        CORE::AppendToPath( subRoot, (*i) );

        // get a list of all the files
        TFileEntryVector subFiles;
        BuildFileList( subRoot, subFiles, fileTypes, dirsToIgnore );
        
        // Fix relative paths to include rootdir
        TFileEntryVector::iterator n = subFiles.begin();
        while ( n != subFiles.end() )
        {
            // Put root dir prefix in place again to fix relative path
            CORE::CString actualRelPath = (*i);
            CORE::AppendToPath( actualRelPath, (*n).filedir );
            (*n).filedir = actualRelPath;
            
            ++n;
        }
        
        ++i;
    }
    
    // add entry for each file
    TFileEntryVector::iterator m = files.begin();
    while ( m != files.end() ) 
    {
        TMatchEntry matchEntry;
        matchEntry.source = (*m);        
        matches.push_back( matchEntry );        
        ++m;
    }
}
Esempio n. 9
0
BOOL CommandManager::Execute( LPCTSTR cmdline, tstring& replyText )
{
    //分割并整理命令行的各个部分
    TStringVector parts;
    splitByChar(cmdline, parts, ' ');

    TStringVector::iterator iter = parts.begin();
    while (iter != parts.end())
    {
        tstring& part = *iter;
        trim(part);
        if (part.size() == 0)
        {
            iter = parts.erase(iter);
        }
        else
        {
            iter++;
        }
    }

    //检查是否有可用的部分
    if (parts.size() == 0)
    {
        replyText = _T("invalid command.");
        return FALSE;
    }

    //查找可用的命令
    tstring& cmdname = parts[0];
    makeLower(cmdname);

    CommandMap::iterator cmdIter = m_cmdMap.find(cmdname);
    if (cmdIter == m_cmdMap.end())
    {
        replyText = _T("no such command.");
        return FALSE;
    }

    //执行命令
    ICmd* pCmd = cmdIter->second;
    BOOL bExecuteOK = pCmd->Execute(parts, replyText, m_env);

    return bExecuteOK;
}
Esempio n. 10
0
void CAppWindow::TruncateLastReported()
{
	ASSERT(m_lpView != NULL);

	const TWaveMap & vReported = m_lpReportedView->GetWaves();
	const TWaveMap & vCurrent = m_lpView->GetWaves()->GetWaves();
	TStringVector vRemove;

	for (TWaveMapConstIter iter = vReported.begin(); iter != vReported.end(); iter++)
	{
		if (vCurrent.find(iter->first) == vCurrent.end())
		{
			vRemove.push_back(iter->first);
		}
	}

	m_lpReportedView->RemoveWaves(vRemove);
}
Esempio n. 11
0
void Shell::MakeAbsolutePath( LPCTSTR filepath, tstring& absoPath )
{
	TStringVector parts;
	splitByChar(filepath, parts, '\\');

	std::list<tstring> dirStack;
	TStringVector::iterator iter = parts.begin();
	for (; iter != parts.end(); iter++)
	{
		tstring& part = *iter;
		trim(part, ' ');
		if (part.size() == 0)
		{
			if (dirStack.size() > 0)
			{
				tstring partition = dirStack.front();
				dirStack.clear();
				dirStack.push_back(partition);
			}
		}
		else if (part == _T(".")) 
		{
			continue;
		}
		else if (part == _T(".."))
		{
			if (dirStack.size() > 0) dirStack.pop_back();
		}
		else
		{
			dirStack.push_back(part);
		}
	}

	tostringstream toss;
	std::list<tstring>::iterator stackIter = dirStack.begin();
	for (; stackIter != dirStack.end(); stackIter++)
	{
		toss << stackIter->c_str() << '\\';
	}

	absoPath = toss.str();
	trim(absoPath, '\\');
}
Esempio n. 12
0
CDataNode::TStringVector
CDataNode::GetChildrenValuesByName( const CString& name ) const
{
    TStringVector results;
    
    TConstDataNodeSet childNodes = FindChildrenOfType( name, false );
    TConstDataNodeSet::iterator i = childNodes.begin();
    while ( i != childNodes.end() )
    {
        const CString& childValue = (*i)->GetValue();
        if ( !childValue.IsNULLOrEmpty() )
        {
            results.push_back( childValue );
        }
        ++i;
    }

    return results;
}
HRESULT CTsTeleportShellExt::TeleportFiles(TStringVector& vFileNames)
{
    HRESULT hr = S_OK;

    TStringVector::iterator iter = vFileNames.begin();

    //
    // Open virtual channel
    //

    if (!_hDVC)
    {
        hr = GetVirtualChannelHandle(&_hDVC);
    }
    LEAVE_IF_FAILED("GetVirtualChannelHandle failed");

    for (; iter != vFileNames.end(); iter++)
    {
        hr = TeleportFile((LPTSTR) (*iter).c_str());
        LEAVE_IF_FAILED("TeleportFile (%s) failed", (*iter).c_str());
    }

_Function_Exit:

    if (_hDVC)
    {
        //
        // Close virtual channel
        //

        CloseHandle(_hDVC);
        _hDVC = NULL;
    }

    return hr;
}
bool
CComboboxImp::SetListItems( const TStringVector& items )
{GUCE_TRACE;

    if ( NULL != m_combobox )
    {
        m_combobox->resetList();
        for ( UInt32 i=0; i<items.size(); ++i )
        {
            m_combobox->addItem( new ListItem( items[ i ].C_String() ) );
        }
        return true;
    }
    return false;
}
bool
CComboboxImp::GetListItems( TStringVector& items ) const
{GUCE_TRACE;

    if ( NULL != m_combobox )
    {
        CEGUI::ListboxItem* item = NULL;
        size_t itemCount = m_combobox->getItemCount();
        for ( size_t i=0; i<itemCount; ++i )
        {
            item = m_combobox->getListboxItemFromIndex( i );
            items.push_back( item->getText().c_str() );
        }
        return true;
    }
    return false;
}
Esempio n. 16
0
void CommManager::ListAvailableClient( TStringVector& clientidList, DWORD dwDiffS /*= 60 * 5*/ )
{
	__time64_t now;
	_time64(&now);

	m_mapSection.Enter();
	{
		HeartbeatMap::iterator iter = m_heartbeatMap.begin();
		for (; iter != m_heartbeatMap.end(); iter++)
		{
			__time64_t lastHeartbeat = iter->second.time;
			if (now >= lastHeartbeat && now - lastHeartbeat < dwDiffS)
			{
				clientidList.push_back(iter->first);
			}
		}
	}
	m_mapSection.Leave();
}
Esempio n. 17
0
bool
CPing::Start( const TStringVector& remoteHosts          ,
              const Int32 maxPings /* = 0 */            ,
              const UInt32 bytesToSend /* = 32 */       ,
              const UInt32 timeout /* = 1000 */         ,
              const UInt32 minimalPingDelta /* = 500 */ )
{GUCEF_TRACE;

    if ( !m_isActive && ( remoteHosts.size() > 0 ) )
    {
        m_remoteHosts = remoteHosts;
        m_maxPings = maxPings;
        m_timeout = timeout;
        m_bytesToSend = bytesToSend;
        m_minimalPingDelta = minimalPingDelta;

        CPingTaskConsumer::CPingTaskData taskData( remoteHosts, maxPings, bytesToSend, timeout, minimalPingDelta );
        return CORE::CCoreGlobal::Instance()->GetTaskManager().StartTask( m_pingTaskConsumer ,
                                                                          &taskData          );
    }
    return false;
}
Esempio n. 18
0
void splitByChar(LPCTSTR str, TStringVector& parts, TCHAR sepChar)
{
	if (NULL == str) return;

	tstring temp = str;
	temp += sepChar;

	tstring::size_type begin = 0;
	tstring::size_type pos = temp.find(sepChar);

	while (pos != tstring::npos)
	{
		tstring part;
		if (pos > begin)
		{
			part = temp.substr(begin, pos - begin);
		}

		parts.push_back(part);

		begin = pos + 1;
		pos = temp.find(sepChar, begin);
	}
}
Esempio n. 19
0
void ClientInfoManager::CheckInfoProc()
{
	TStringVector clientidList;
	CommManager::GetInstanceRef().ListAvailableClient(clientidList);

	TStringSet clientidSet;
	TStringVector2TStringSet(clientidList, clientidSet);

	m_infoMapSection.Enter();
	{
		//从m_clientBaseInfoMap中删除已经不可用的clientinfo
		ClientBaseInfoMap::iterator infoIter = m_clientBaseInfoMap.begin();
		while (infoIter != m_clientBaseInfoMap.end())
		{
			if (clientidSet.find(infoIter->first) == clientidSet.end())
			{
				CLIENT_INFO clientInfo = {0};
				TransferInfo(infoIter->first.c_str(), &infoIter->second, clientInfo);
				if (NULL != m_fnCallback && (infoIter->second.bAdd == FALSE))
					m_fnCallback(WM_DEL_CLIENT, (LPVOID)&clientInfo, m_lpParameter);
				infoIter = m_clientBaseInfoMap.erase(infoIter);
			}
			else
			{
				infoIter++;
			}
		}

		//遍历clientidList,更新m_clientBaseInfoMap
		TStringVector::iterator clientidIter = clientidList.begin();
		for (; clientidIter != clientidList.end(); clientidIter++)
		{
			const tstring& clientid = *clientidIter;

			infoIter = m_clientBaseInfoMap.find(clientid.c_str());

			//如果m_clientBaseInfoMap中没有该客户端的信息,则请求客户端上报
			if (infoIter == m_clientBaseInfoMap.end())
			{
				CLIENT_BASE_INFO info;
				info.bValid = FALSE;
				info.bAdd = TRUE;
				RequestReportInfo(clientid.c_str());
				m_clientBaseInfoMap[clientid] = info;
			}
			else
			{
				if (infoIter->second.installModMsgIDMap.size() > 0)
				{
					HandleInstalMsg(clientid,infoIter->second);
				}

				if (infoIter->second.bValid && infoIter->second.bAdd)
				{
					CLIENT_INFO info;
					TransferInfo(clientid.c_str(),&m_clientBaseInfoMap[clientid.c_str()],info);
					if (NULL != m_fnCallback) m_fnCallback(WM_ADD_CLIENT, (LPVOID)&info, m_lpParameter);
					infoIter->second.bAdd = FALSE;
				}
			}

		}
	}
	m_infoMapSection.Leave();
}
HRESULT CTsTeleportShellExt::GetFileNames(
    IDataObject *pDataObj,
    TStringVector& vFileNames)
{
    HRESULT hr;

    //
    // init for cleanup
    //

    STGMEDIUM mdm;
    mdm.pUnkForRelease = NULL;
    mdm.hGlobal = NULL;

    HDROP hdrop = NULL;

    STRRET strret;
    strret.pOleStr = NULL;

    LPTSTR szFileName = NULL;

    try
    {
        FORMATETC fmt = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };

        hr = pDataObj->GetData(&fmt, &mdm);
        LEAVE_IF_FAILED("pDataObj->GetData failed");

        hdrop = (HDROP) GlobalLock(mdm.hGlobal);

        if (!hdrop)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
        }
        LEAVE_IF_FAILED("GetFileNames failed");

        UINT nFiles = DragQueryFile(hdrop, (UINT)-1, NULL, 0);

        for(UINT nNames = 0; nNames < nFiles; nNames++)
        {
            UINT   cchFileName = DragQueryFile(hdrop, 
                nNames, 
                NULL,
                0);

            ASSERT(cchFileName);

            szFileName = new TCHAR[cchFileName+1]; 

            ASSERT(szFileName); // using C++ throwing new 

            UINT tmp = DragQueryFile(hdrop, 
                nNames, 
                szFileName,
                cchFileName+1);

            DBG_UNREFERENCED_LOCAL_VARIABLE(tmp); // for fre builds

            ASSERT(tmp == cchFileName);
            ASSERT(szFileName[cchFileName] == '\0');

            TString strFileName(szFileName);

            vFileNames.push_back(strFileName);
            
            delete [] szFileName;
            szFileName = NULL;
        }
    }
    catch (std::bad_alloc&)
    {
        hr = E_OUTOFMEMORY;
    }
    catch (std::exception&)
    {
        hr = E_UNEXPECTED;
    }

_Function_Exit:

    //
    // Cleanup
    // 

    if (hdrop)
    {
        GlobalUnlock(hdrop);
    }

    if (mdm.hGlobal)
    {
        ReleaseStgMedium(&mdm);
    }

    if (strret.pOleStr)
    {
        CoTaskMemFree(strret.pOleStr);
    }

    if (szFileName)
    {
        delete [] szFileName;
    }

    return hr;
}
Esempio n. 21
0
void DecodeCSVString( TStringVector &strings, const TString& astring, char adelimiter )
{
  TString str;
  str.SetLength( astring.Length() );

  strings.clear();

  if( astring.Length()==0 )
    return;

  enum { normal, parenthesis } state;
  state = normal;

  const char *beg = astring.c_str();
  const char *c = beg;
  char *destbeg = str.c_str();
  char *dest = destbeg;

  while( *c )
  {
    switch( state )
    {
      case normal:
        switch( *c )
        {
          case '"':
            state = parenthesis;
            c++;
            break;
          default:
            if( *c == adelimiter )
            {
              strings.push_back( TString( destbeg, dest-destbeg ) );
              dest = destbeg;
            }
            else {
              *dest = *c;
              dest++;
            }
            c++;
        }
        break;
      case parenthesis:
        if( *c == '"' )
        {
          c++;
          state = normal;
        }
        else {
          *dest = *c;
          c++;
          dest++;
        }
        break;
      default:
        strings.clear();
/* TODO : Nen� upln� jasn�, zda v p��pad� failu smazat to, co se dosud ud�lalo... */
        throw TException( "Unknown error in DecodeCSVString." );
    }
  }
  strings.push_back( TString( destbeg, dest-destbeg ) );

  unsigned int nstrings = strings.size();
  unsigned int ui;
  for( ui=0; ui<nstrings; ui++ )
    ReplaceHexFormWithOrdinals( strings[ui] );
}
Esempio n. 22
0
void CAppWindow::SynchronisePopups(CUnreadWaveCollection * lpUnreads, BOOL fManual)
{
	ASSERT(lpUnreads != NULL);

	BOOL fQueuedNewWaves = FALSE;
	TPopupVector vMustCancel;
	TStringVector vSeen;

	if (CPopupWindow::Instance() != NULL)
	{
		TPopupVector vPopups;
		
		CPopupWindow::Instance()->GetPopups(vPopups);

		for (TPopupVectorIter iter = vPopups.begin(); iter != vPopups.end(); iter++)
		{
			if (((CPopupBase *)(*iter))->GetType() == PT_WAVE)
			{
				CUnreadWavePopup * lpPopup = (CUnreadWavePopup *)*iter;
				wstring szPopupWaveId = lpPopup->GetUnread()->GetID();
				CUnreadWave * lpNewUnreadWave = lpUnreads->GetChange(szPopupWaveId);

				if (lpNewUnreadWave == NULL)
				{
					// Cancel the popup if it isn't changed anymore.

					vMustCancel.push_back(lpPopup);
				}
				else
				{
					// Else, update with the current changed status.

					lpPopup->UpdateUnread(lpNewUnreadWave);

					vSeen.push_back(szPopupWaveId);
				}
			}
		}
	}

	// Cancel all popups.

	for (TPopupVectorIter iter = vMustCancel.begin(); iter != vMustCancel.end(); iter++)
	{
		CPopup * lpPopup = *iter;

		if (!lpPopup->IsDisplaying())
		{
			lpPopup->Cancel();
		}
	}

	// Add all new popups.

	TUnreadWaveVector vUnreads = lpUnreads->GetChanges();

	// Waves can only be reported if has been reported within the
	// timeout period.

	CDateTime dtRereportLimit(CDateTime::Now() - CTimeSpan::FromMilliseconds((DOUBLE)TIMER_REREPORT_TIMEOUT));

	for (TUnreadWaveVectorIter iter1 = vUnreads.begin(); iter1 != vUnreads.end(); iter1++)
	{
		// If we haven't seen this before ...

		wstring szId((*iter1)->GetID());

		if (find(vSeen.begin(), vSeen.end(), szId) == vSeen.end())
		{
			// ... create a new popup

			TStringDateTimeMapIter pos = m_vReportedTimes.find(szId);

			// Verify whether this popup hasn't been reported for
			// the required time.

			if (pos == m_vReportedTimes.end() || pos->second < dtRereportLimit)
			{
				CUnreadWavePopup * lpPopup = new CUnreadWavePopup(*iter1);

				lpPopup->Show();

				if (pos != m_vReportedTimes.end())
				{
					m_vReportedTimes.erase(pos);
				}

				// We've queued a new popup, so make a noise.

				fQueuedNewWaves = TRUE;
			}
			else
			{
				// Silence the wave by reporting it as reported.

				HaveReportedWave(szId);

				// Delete the unread wave because we're going
				// to detach everything lateron.

				delete *iter1;
			}
		}
	}

	// Detach all unread objects because the popups have taken
	// them over

	lpUnreads->DetachAll();

	// Re-index the popups to correctly display the index and count number
	// shown of the popups.

	if (CPopupWindow::Instance() != NULL)
	{
		TPopupVector vPopups;
		
		CPopupWindow::Instance()->GetPopups(vPopups);

		UINT uCount = 0;

		for (TPopupVectorIter iter = vPopups.begin(); iter != vPopups.end(); iter++)
		{
			if (((CPopupBase *)(*iter))->GetType() == PT_WAVE)
			{
				uCount++;
			}
		}

		UINT uIndex = 1;

		for (TPopupVectorIter iter1 = vPopups.begin(); iter1 != vPopups.end(); iter1++)
		{
			if (((CPopupBase *)(*iter1))->GetType() == PT_WAVE)
			{
				CUnreadWavePopup * lpPopup = (CUnreadWavePopup *)*iter1;

				lpPopup->SetCountIndex(uIndex, uCount);

				uIndex++;
			}
		}
	}

	if (fManual)
	{
		// When the check was queued manually, we will report it when
		// there were no unread waves to report.

		if (!fQueuedNewWaves)
		{
			(new CMessagePopup(L"No unread Waves."))->Show();
		}
	}
	else
	{
		// When the check was not done manually, we will play a sound
		// when there were unread waves to report.

		if (fQueuedNewWaves && CNotifierApp::Instance()->GetPlaySoundOnNewWave())
		{
			PlaySound(
				MAKEINTRESOURCE(IDR_NEWWAVE),
				CNotifierApp::Instance()->GetInstance(),
				SND_ASYNC | SND_NOSTOP | SND_NOWAIT | SND_RESOURCE);
		}
	}
}
Esempio n. 23
0
BOOL Shell::ExecuteCommand( LPCTSTR cmdlinestr, tstring& reply )
{
	//分割并整理命令行的各个部分
	tstring cmdline = cmdlinestr;
	trim(cmdline, ' ');
	trim(cmdline, '\n');
	trim(cmdline, '\r');
	TStringVector parts;
	splitByChar(cmdline.c_str(), parts, ' ');

	//清理无效参数
	TStringVector::iterator iter = parts.begin();
	while (iter != parts.end())
	{
		tstring& part = *iter;
		trim(part);
		if (part.size() == 0)
		{
			iter = parts.erase(iter);
		}
		else
		{
			iter++;
		}
	}

	//检查是否有可用的部分
	if (parts.size() == 0)
	{
		reply = _T("");
		return TRUE;
	}

	//查找可用的命令
	tstring& cmdname = parts[0];
	makeLower(cmdname);

	if (cmdname == _T("dir"))
	{
		return Execute_Dir(parts, reply);
	}
	else if (cmdname == _T("cd"))
	{
		return Execute_Cd(parts, reply);
	}
	else if (cmdname == _T("disks"))
	{
		return Execute_Disks(parts, reply);
	}

	//将命令发到客户端去执行
	CommData commandCommData;
	commandCommData.SetMsgID(MSGID_EXECUTE_CMDLINE);
	commandCommData.SetData(_T("cmdline"), cmdline.c_str());
	CommData replyCommData;
	if (! AskAndWaitForReply(commandCommData, replyCommData))
	{
		reply = _T("等待客户端回应超时");
		return FALSE;
	}
	else
	{
		tstring result;
		replyCommData.GetStrData(_T("result"), result);
		if (result == _T("OK"))
		{
			reply = s2ws(std::string((LPCSTR)(LPBYTE)replyCommData.GetByteData(), replyCommData.GetByteData().Size()));
			return TRUE;
		}
		else
		{
			reply = result;
			return FALSE;
		}
	}
}
Esempio n. 24
0
BOOL Shell::Execute_Dir( const TStringVector& cmdparts, tstring& reply )
{
	tstring findstr = _T("*");
	if (cmdparts.size() > 1)
	{
		findstr = cmdparts[1];
	}

	findstr = m_currentPath + _T("\\") + findstr;
	MakeAbsolutePath(findstr.c_str(), findstr);
	if (findstr.find('*') == tstring::npos 
		&& findstr.find('?') == tstring::npos)
	{
		trim(findstr, '\\');
		findstr += _T("\\*");
	}

	CommData request;
	request.SetMsgID(MSGID_LIST_FILES);
	request.SetData(_T("findstr"), findstr.c_str());

	CommData commData;
	if (! AskAndWaitForReply(request, commData))
	{
		reply = _T("客户端响应超时");
		return FALSE;
	}

	DECLARE_STR_PARAM(result);
	//	result		str	目录内容	filename(str)|attr(dword)|filesize(uint64)|lastWriteTime(uint64 filetime):
	tostringstream toss;
	TStringVector fileParts;
	splitByChar(result.c_str(), fileParts, ':');
	TStringVector::iterator fileIter = fileParts.begin();
	for (; fileIter != fileParts.end(); fileIter++)
	{
		tstring& fileInfo = *fileIter;
		TStringVector attrParts;
		splitByChar(fileInfo.c_str(), attrParts, '|');
		if (attrParts.size() != 4) continue;

		tstring& filename = attrParts[0];
		DWORD dwAttrs = 0;
		ULARGE_INTEGER filesize = {0};
		ULARGE_INTEGER lastWriteTime = {0};
		if (1 != _stscanf_s(attrParts[1].c_str(), _T("%u"), &dwAttrs)) continue;
		if (1 != _stscanf_s(attrParts[2].c_str(), _T("%I64u"), &filesize.QuadPart)) continue;
		if (1 != _stscanf_s(attrParts[3].c_str(), _T("%I64u"), &lastWriteTime.QuadPart)) continue;

		SYSTEMTIME systime;
		FILETIME ftLastWriteTime;
		ftLastWriteTime.dwLowDateTime = lastWriteTime.LowPart;
		ftLastWriteTime.dwHighDateTime = lastWriteTime.HighPart;
		FILETIME ftLocalLastWriteTime;
		FileTimeToLocalFileTime(&ftLastWriteTime, &ftLocalLastWriteTime);
		FileTimeToSystemTime(&ftLocalLastWriteTime, &systime);

		BOOL bDir = (dwAttrs & FILE_ATTRIBUTE_DIRECTORY);

		TCHAR line[MAX_PATH * 2] = {0};
		_stprintf_s(line, _T("%04d/%02d/%02d %02d:%02d:%02d %20s %s\r\n"), 
			systime.wYear, systime.wMonth, systime.wDay,
			systime.wHour, systime.wMinute, systime.wSecond,
			(bDir ? _T("<DIR>   ") : FormatSizeWithUnit(filesize.QuadPart).c_str()), filename.c_str());

		toss << line;
	}

	reply = toss.str();

	return TRUE;
}
Esempio n. 25
0
BOOL Shell::Execute_Cd( const TStringVector& cmdparts, tstring& reply )
{
	if (cmdparts.size() == 1)
	{
		reply = m_currentPath;
		return TRUE;
	}
	else if (cmdparts.size() > 1)
	{
		tstring target = cmdparts[1];
		if (target.size() == 2 && target[1] == ':')
		{
			//切换当前分区
			int index = 0;
			TCHAR partition = target[0];
			if (partition >= 'a' && partition <= 'z') index = partition - 'a';
			else if (partition >= 'A' && partition <= 'Z') index = partition - 'A';
			else
			{
				reply = _T("invalid partition");
				return FALSE;
			}

			if (! m_partitions[index].bValid)
			{
				reply = _T("invalid partition");
				return FALSE;
			}

			m_currentPath = m_partitions[index].curPath;
			reply = m_currentPath;

			return TRUE;
		}
		else 
		{
			tstring testPath;
			if (target.size() > 2 && target[1] == ':')
			{
				//绝对路径
				testPath = target;
			}
			else
			{
				//相对路径
				testPath = m_currentPath;
				testPath += '\\';
				testPath += target;
				MakeAbsolutePath(testPath.c_str(), testPath);
			}
			
			BOOL bExists = FALSE;
			BOOL bDir = FALSE;
			if (FileExistsInClient(testPath.c_str(), bExists, bDir))
			{
				if (bExists && bDir)
				{
					SetCurrentPath(testPath.c_str());
					reply = m_currentPath;
					return TRUE;
				}
				else
				{
					reply = _T("invalid filepath");
					return FALSE;
				}
			}
			else
			{
				reply = _T("等待客户端回应超时");
				return FALSE;
			}
		}
	}

	return FALSE;
}