Пример #1
0
BOOL zstringEx::DelNotNullDir(char* DirName)
{
	CFileFind tempFind; 
	char tempFileFind[1024] ;

	sprintf(tempFileFind,"%s\\*.*",DirName); 
	BOOL IsFinded = tempFind.FindFile(tempFileFind); 
	while (IsFinded) 
	{ 

	IsFinded = tempFind.FindNextFile(); 

	if (!tempFind.IsDots()) 
	{ 
	char foundFileName[1024]; 
	strcpy(foundFileName,tempFind.GetFileName().GetBuffer(1024)); 

	if (tempFind.IsDirectory()) 
	{ 
	char tempDir[1024]; 
	sprintf(tempDir,"%s\\%s",DirName,foundFileName); 
	this->DelNotNullDir(tempDir); 
	} 
	else 
	{ 
	char tempFileName[1024]; 
	sprintf(tempFileName,"%s\\%s",DirName,foundFileName); 
	DeleteFile(tempFileName); 
	} 
	} 
	} 
	tempFind.Close(); 
	if(!RemoveDirectory(DirName)) 
	{ 
	return FALSE; 
	} 

	return TRUE; 
}
Пример #2
0
/******************************************************************************
*	作用:		在指定父节点下插入驱动盘下的所有子项
******************************************************************************/
void CMainFrame::InsertDriveDir(HTREEITEM hParent)
{
    HTREEITEM hChild = m_TreeCtrl.GetChildItem(hParent);
    while(hChild)
    {
        CString strText = m_TreeCtrl.GetItemText(hChild);
        if(strText.Right(1) != L"\\")
            strText += L"\\";
        strText += L"*.*";
        CFileFind file;
        BOOL bContinue = file.FindFile(strText);
        while(bContinue)
        {
            bContinue = file.FindNextFile();
            if(!file.IsDots())
                m_TreeCtrl.InsertItem(file.GetFileName(), hChild);
        }
        InsertDriveDir(hChild);
        hChild = m_TreeCtrl.GetNextItem(hChild, TVGN_NEXT);
        file.Close();
    }
}
Пример #3
0
CReplayFrame::CReplayFrame(void)
{
	__SEH_SET_EXCEPTION_HANDLER

    CTime		time = 0, latest_time = 0;
    int			last_frame_num = -1, frame_num = 0;
    CString		path = "", filename = "", current_path = "";
    CFileFind	hFile;
    BOOL		bFound = false;

	CSLock lock(m_critsec);

	// Find next replay frame number
    _next_replay_frame = -1;

    path.Format("%s\\replay\\session_%lu\\*.bmp", _startup_path, theApp._session_id);
    bFound = hFile.FindFile(path.GetString());
    while (bFound)
    {
        bFound = hFile.FindNextFile();
        if (!hFile.IsDots() && !hFile.IsDirectory())
        {
            filename = hFile.GetFileName();
            hFile.GetLastWriteTime(time);
            sscanf_s(filename.GetString(), "frame%d.bmp", &frame_num);

            if (time>latest_time)
            {
                last_frame_num = frame_num;
                latest_time = time;
            }
        }
    }

    _next_replay_frame = last_frame_num + 1;
    if (_next_replay_frame >= prefs.replay_max_frames())
        _next_replay_frame = 0;
}
Пример #4
0
bool CFileBackUp::FileCopyTo(CString source, CString destination, CString searchStr, BOOL cover)
{
	CString strSourcePath = source;
	CString strDesPath = destination;
	CString strFileName = searchStr;
	CFileFind filefinder;
	CString strSearchPath = strSourcePath + _T("\\") + strFileName;
	CString filename;
	BOOL bfind = filefinder.FindFile(strSearchPath);
	CString SourcePath, DisPath;

	bool bRlt = true;
	while (bfind)
	{
		bfind = filefinder.FindNextFile();
		filename = filefinder.GetFileName();
		SourcePath = strSourcePath + _T("\\") + filename;
		DisPath = strDesPath + _T("\\") + filename;
		bRlt |= CopyFile(SourcePath.GetString(), DisPath.GetString(), cover);
	}
	filefinder.Close();
	return bRlt;
}
Пример #5
0
void CFileView::Refresh(char *dir)
{
	// listview을 모두 지운다.
	CListCtrl& list = GetListCtrl(); // !!!!!!!!!!!
	list.DeleteAllItems();
	SetCurrentDirectory( dir );

	CFileFind f; BOOL b = f.FindFile("*.*");

	while ( b )
	{
		b = f.FindNextFile();

		if ( ! f.IsDirectory() && ! f.IsHidden() )
		{
			list.InsertItem(0, f.GetFileName(), 0);
			
			CString msg;
			msg.Format( "%d KB", (f.GetLength() / 1024) + 1 );
			list.SetItemText(0, 1, msg );
		}
	}
}
void CDirectoryTreeCtrl::AddSubdirectories(HTREEITEM hRoot, CString strDir)
{
	if (strDir.Right(1) != _T("\\"))
		strDir += _T("\\");
	CFileFind finder;
	BOOL bWorking = finder.FindFile(strDir+_T("*.*"));
	while (bWorking)
	{
		bWorking = finder.FindNextFile();
		if (finder.IsDots())
			continue;
		if (finder.IsSystem())
			continue;
		if (!finder.IsDirectory())
			continue;
		
		CString strFilename = finder.GetFileName();
		if (strFilename.ReverseFind(_T('\\')) != -1)
			strFilename = strFilename.Mid(strFilename.ReverseFind(_T('\\')) + 1);
		AddChildItem(hRoot, strFilename);
	}
	finder.Close();
}
Пример #7
0
BOOL CDirTreeCtrl::AddSubDirAsItem(HTREEITEM hParent)
{
	CString strPath,strFileName;
	HTREEITEM hChild;
	//---------------------去除该父项下所有的子项------------   // 因为有dummy项,并且有时子目录再次打开,或子目录会刷新等,因此必须去除。
	while ( ItemHasChildren(hParent))  {
		hChild = GetChildItem(hParent);
		DeleteItem( hChild );
	}  
	//-----------------------装入该父项下所有子项-------------- 
	strPath = GetFullPath(hParent);  // 从本节点开始到根的路径
	CString strSearchCmd = strPath;
	if( strSearchCmd.Right( 1 ) != _T( "\\" ))
		strSearchCmd += _T( "\\" );

	strSearchCmd += _T( "*.*" );
	CFileFind find;
	BOOL bContinue = find.FindFile( strSearchCmd );
	while ( bContinue )  {
		bContinue = find.FindNextFile();
		strFileName = find.GetFileName(); 

		if ( !find.IsHidden() && ! find.IsDots() && find.IsDirectory() )
		{ 
			hChild = AddItem( hParent, strFileName );
			if ( FindSubDir( GetFullPath(hChild) ))
				AddSubDirAsItem1(hChild); 
		}

		if ( !find.IsHidden() && ! find.IsDots() && !find.IsDirectory() )
		{
			InsertItem( strFileName, 0, 0, hParent );
		}
	}

	return TRUE; 
}
Пример #8
0
static void InitLanguages(const CString& rstrLangDir1, const CString& rstrLangDir2, bool bReInit = false)
{
	static BOOL _bInitialized = FALSE;
	if (_bInitialized && !bReInit)
		return;
	_bInitialized = TRUE;

	CFileFind ff;
	bool bEnd = !ff.FindFile(rstrLangDir1 + _T("*.dll"), 0);
	bool bFirstDir = rstrLangDir1.CompareNoCase(rstrLangDir2) != 0;
	while (!bEnd)
	{
		bEnd = !ff.FindNextFile();
		if (ff.IsDirectory())
			continue;
		TCHAR szLandDLLFileName[MAX_PATH];
		_tsplitpath(ff.GetFileName(), NULL, NULL, szLandDLLFileName, NULL);

		SLanguage* pLangs = _aLanguages;
		if (pLangs){
			while (pLangs->lid){
				if (_tcsicmp(pLangs->pszISOLocale, szLandDLLFileName) == 0){
					pLangs->bSupported = TRUE;
					break;
				}
				pLangs++;
			}
		}
		if (bEnd && bFirstDir){
			ff.Close();
			bEnd = !ff.FindFile(rstrLangDir2 + _T("*.dll"), 0);
			bFirstDir = false;
		}

	}
	ff.Close();
}
Пример #9
0
DWORD CImageManager::EnumImage()
{
	DWORD dwCount = 0;
	CString strFile = m_strImagePath + _T("\\*.*");
	CFileFind fileFind;
	BOOL bFind = fileFind.FindFile(strFile);
	CString strName,strSize,strModifyTime,strExt;
	while (bFind)
	{
		bFind = fileFind.FindNextFile();

		if (!fileFind.IsDirectory())
		{
			strName = fileFind.GetFileName();
			strExt = strName.Right(3);

			if (strExt.CompareNoCase(_T("IMG")) == 0
				|| strExt.CompareNoCase(_T("MTP")) == 0)
			{
				CFileStatus status;
				CFile::GetStatus(fileFind.GetFilePath(),status);

				strSize = CUtils::AdjustFileSize(status.m_size);
				strModifyTime = status.m_mtime.Format(_T("%Y-%m-%d %H:%M:%S"));

				m_ListImages.InsertItem(dwCount,strName);
				m_ListImages.SetItemText(dwCount,1,strSize);
				m_ListImages.SetItemText(dwCount,2,strModifyTime);
				dwCount++;
			}
			
		}
	}
	fileFind.Close();

	return dwCount;
}
Пример #10
0
BOOL CExportDialog::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	// TODO: Add extra initialization here
	CFileFind finder;
	INXString fileName;
	int bWorking = finder.FindFile(workDir + USERDEFDIR + "*.prg");
	
	// read in ini files and construct menu tree
	while (bWorking)
	{
		bWorking = finder.FindNextFile();
		fileName = finder.GetFileName();
		// Remove .prg
		fileName.MakeReverse();
		fileName.Delete(0,4);
		fileName.MakeReverse();
		m_Library.AddString(fileName);
	}
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
Пример #11
0
CString VDEIODLL_EXPORT_API GetFileName(CString strPath,int& nCount)
{
	CString strFileName;
	CFileFind cfFile; //执行本地文件查找
	int i = 0;
	if (strPath.Right(1) != "\\")
	{
		strPath += _T("\\*.avi");
	}else
	{
		strPath += _T("*.avi");
	}

	BOOL bf = cfFile.FindFile(strPath);
	while (bf)
	{
		bf = cfFile.FindNextFile();
		CString cstrFileName;
		cstrFileName = cfFile.GetFileName();
		nCount++;
	}
	strFileName.Format(_T("视频%d"),nCount+1);
	return strFileName;
}
Пример #12
0
BOOL CSetList::OnInitDialog()
{
	CDialog::OnInitDialog();
	// TODO:  여기에 추가 초기화 작업을 추가합니다.

	CRect	dlgRect;
	GetClientRect(&dlgRect);
	m_lstSetting.MoveWindow(&dlgRect);

	// 파일 목록을 찾는다.
	CFileFind finder;
	CString strWildCard("*.set");

	BOOL bWorking = finder.FindFile( strWildCard );
	while( bWorking )
	{
		bWorking = finder.FindNextFile();
		if( finder.IsDots() || finder.IsDirectory() )
			continue;  
		else
		{
			CString filePath = finder.GetFileName();
			filePath = filePath.Left(filePath.GetLength() - 4);			// 뒤의 .set 을 지우기 위해서
			m_lstSetting.AddString(filePath);
		}
	} 
	finder.Close();

	if(m_lstSetting.GetCount() == 0)
	{
		AfxMessageBox(STR_NO_SETTING_FILE);
	}

	return TRUE;  // return TRUE unless you set the focus to a control
	// 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다.
}
Пример #13
0
void COutputTabView::FindCurrentDirFiles()
{
	CString currentDir;
	GetCurrentDirectory( MAX_SIZE_PATH, currentDir.GetBufferSetLength(MAX_SIZE_PATH) );
	//AfxMessageBox(currentDir);
	currentDir.ReleaseBuffer();

	CFileFind finder;
	BOOL bContinue;
	CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();

	if( bContinue = finder.FindFile(_T("*.*")) )
	{
		while(bContinue)
		{
			bContinue = finder.FindNextFile();
			CString strName = finder.GetFileName();
			CString strPath = finder.GetFilePath();
			pMainFrame->m_wndOutputTabView.AddMsg1(strName);		
		}

	}
  
}
Пример #14
0
void CFileCtrl::DoCopyFolderFile(CString csSourceFolder, CString csDestFolder, CString csSubFileName )
{
	CFileFind find;	
	csSourceFolder.TrimLeft();
	csSourceFolder.TrimRight();
	csSourceFolder = csSourceFolder + "\\";
	csDestFolder.TrimLeft();
	csDestFolder.TrimLeft();
	csDestFolder = csDestFolder + "\\";
	//
	csSubFileName = "*" + csSubFileName;

	CString csFile = csSourceFolder;
	CString csFinalFile = _T("");
	csFinalFile = csFile + csSubFileName;
	BOOL bResult = find.FindFile( csFinalFile );	
	CString file = _T("");
	while(bResult)
	{
		bResult = find.FindNextFile();
		file = find.GetFileName();	// Get File Name
		::CopyFile( csSourceFolder + file, csDestFolder + file, FALSE );
	}
}
Пример #15
0
CString CDirstatApp::FindAuxiliaryFileByLangid(LPCTSTR prefix, LPCTSTR suffix, LANGID& langid, bool checkResource)
{
	CString number;
	number.Format(_T("%04x"), langid);

	CString exactName;
	exactName.Format(_T("%s%s%s"), prefix, number, suffix);

	CString exactPath= GetAppFolder() + _T("\\") + exactName;
	if (FileExists(exactPath) && (!checkResource || IsCorrectResourceDll(exactPath)))
		return exactPath;

	CString search;
	search.Format(_T("%s*%s"), prefix, suffix);

	CFileFind finder;
	BOOL b= finder.FindFile(GetAppFolder() + _T("\\") + search);
	while (b)
	{
		b= finder.FindNextFile();
		if (finder.IsDirectory())
			continue;

		LANGID id;
		if (!ScanAuxiliaryFileName(prefix, suffix, finder.GetFileName(), id))
			continue;

		if (PRIMARYLANGID(id) == PRIMARYLANGID(langid) && (!checkResource || IsCorrectResourceDll(finder.GetFilePath())))
		{
			langid= id;
			return finder.GetFilePath();
		}
	}

	return _T("");
}
Пример #16
0
//This function was added to CGrandDataFile to recursively retrieve a list of *.BID files in
//a directory.  It reads the file header to populate the CList of tFileRecords that is converted to
//a safe array used by ImportManager.  This was flagrantly stolen from Kelly Michel and modified to
//search for and read in *.BID files. hn 6/8/2005
// 5-Jul-2005 SFK Removed dead code for readability
// 11-Jul-2005 SFK	Copied from GRAND Import and modified for binary
void CBinaryDataFile::GetCompleteFileList(short FacilityID, CList<tFileRecord, tFileRecord> *pFileList, 
									   const CString& Directory,  bool IncludeSubdirs)
{
	//USES_CONVERSION;

	CFileFind Finder;
	BOOL bWorking;
	CString  FileName;
	tFileRecord FileRecord;

	CString DirWithFileMask;
	DirWithFileMask.Format("%s\\*.*", Directory);
	bWorking = Finder.FindFile(DirWithFileMask);

	
	//If this is an "archive" directory, then skip it completely, and everything that may be underneath it.
	int StartSubDirName = Directory.ReverseFind('\\');
	if(StartSubDirName != -1)
	{
		CString SubDirName = Directory.Mid(StartSubDirName + 1);
		if(SubDirName.CompareNoCase("Archive")) //If SubDirName is not Archive...
		{
			do
			{
				bWorking = Finder.FindNextFile();
				
				if(!Finder.IsDots())
				{
					if(Finder.IsDirectory() && IncludeSubdirs)
					{
						//Recurse.
						GetCompleteFileList(FacilityID, pFileList, Finder.GetFilePath(), IncludeSubdirs);
					}
					else //if(Finder.IsNormal())
					{
 						FileName = Finder.GetFileName(); 
						CString Ext = FileName.Mid(FileName.GetLength() - 3, 3);
						if(!Ext.CompareNoCase("BNY"))
						{
							FileRecord.File.bstrVal = (Finder.GetFilePath()).AllocSysString();

							//****************************************************************
							//Open the file and get info on the data in the file.  Load that
							//file data into the FileRecord structure.
							//****************************************************************
							CString err;
							//If we are not able to read the *.BNY header, we fail
							CString cs(FileRecord.File.bstrVal);
							if (!ReadHeader (cs,&err))
							//if (!ReadHeader (W2T(FileRecord.File.bstrVal),&err))
							{
								if (mpFile) CloseDataFile();
							}
							else
							//Otherwise, save the file date and station ID read.
							{
								SYSTEMTIME sysTime;
								COleDateTime fileDate = GetFileDate ();
								fileDate.GetAsSystemTime (sysTime);
								SystemTimeToVariantTime (&sysTime,&FileRecord.Date.date);
								FileRecord.StationID.lVal = (long) GetStationID ();
								pFileList->AddTail (FileRecord);
								CloseDataFile ();
							}
						}
					}
				}		
			}
			while(bWorking != 0);
		}
	}

}
Пример #17
0
void CLocalFolder::GetFileList( )
	{
	m_Childs.Reset( );
	if ( m_pParent )
		{
		CString sPath;
		CreatePath( this, sPath );
		sPath = sPath + "*.*";

		CFileFind Finder;
		if ( !Finder.FindFile( sPath ) )
			// Aucun fichier
			return;

		CLocalFileBase* pNew;
		CLocalFolder* pFolder;
		CLocalFile* pFile;

		bool bNext = Finder.FindNextFile( ) ? true : false;
		bool bOk = true;
		while ( bOk )
			{
			pNew = NULL;
			if ( Finder.IsDirectory( ) )
				{
				if ( !Finder.IsDots( ) )
					{
					pFolder = new CLocalFolder;
					pNew = pFolder;
					}
				}
			else
				{
				pFile = new CLocalFile;
				pNew = pFile;
				pFile->SetFileSize( Finder.GetLength( ) );
				}

			if ( pNew )
				{
				pNew->SetItemName( Finder.GetFileName( ) );
				pNew->SetParent( this );
				m_Childs.Add( pNew );
				}

			bOk = bNext;
			if ( bOk )
				bNext = Finder.FindNextFile( ) ? true : false;
			}
		m_iChildCount = m_Childs.GetSize( );
		m_Childs.Sort( );
		}
	else
		{
		// Racine, on indique les répertoires
		DWORD dwSize = ::GetLogicalDriveStrings( 0, NULL );
		if ( !dwSize )
			// Erreur....
			return;
		char* lpszDrives = new char[ dwSize + 1 ];
		if ( dwSize < ::GetLogicalDriveStrings( dwSize, lpszDrives ) )
			{
			delete [] lpszDrives;
			return;
			}
		char* lpszCurrent = lpszDrives;

		m_Childs.Reset( );
		CLocalFolder* pNew;

		while ( strlen( lpszCurrent ) )
			{
			pNew = new CLocalFolder;
			pNew->SetItemName( lpszCurrent );
			lpszCurrent = lpszCurrent + strlen( lpszCurrent ) + 1;
			m_Childs.Add( pNew );
			pNew->SetParent( this );
			}

		delete [] lpszDrives;
		m_iChildCount = m_Childs.GetSize( );
		}
	}
Пример #18
0
int CPartFileConvert::performConvertToeMule(CString folder)
{
	BOOL bWorking;
	CString filepartindex,newfilename;
	CString buffer;
	UINT fileindex;
	CFileFind finder;
	
	CString partfile=folder;
	folder.Delete(folder.ReverseFind('\\'),folder.GetLength());
	partfile=partfile.Mid(partfile.ReverseFind('\\')+1,partfile.GetLength());


	UpdateGUI(0,GetResString(IDS_IMP_STEPREADPF),true);

	filepartindex=partfile.Left(partfile.Find('.'));
	//int pos=filepartindex.ReverseFind('\\');
	//if (pos>-1) filepartindex=filepartindex.Mid(pos+1,filepartindex.GetLength()-pos);

	UpdateGUI(4,GetResString(IDS_IMP_STEPBASICINF));

	CPartFile* file=new CPartFile();
	EPartFileFormat eFormat = PMT_UNKNOWN;
		
	if (file->LoadPartFile(folder, partfile, &eFormat) == PLR_CHECKSUCCESS)
	{
		pfconverting->partmettype = (uint8_t)eFormat;
		switch (pfconverting->partmettype)
		{
			case PMT_UNKNOWN:
			case PMT_BADFORMAT:
				delete file;
				return CONV_BADFORMAT;
				break;
		}
	}
	else
	{
		delete file;
		return CONV_BADFORMAT;
	}

	CString oldfile=folder+_T("\\")+partfile.Left(partfile.GetLength()- ((pfconverting->partmettype==PMT_SHAREAZA)?3:4) );

	pfconverting->size=file->GetFileSize();
	pfconverting->filename=file->GetFileName();
	pfconverting->filehash= EncodeBase16( file->GetFileHash() ,16);
	UpdateGUI(pfconverting);

	if (theApp.downloadqueue->GetFileByID(file->GetFileHash())!=0) {
		delete file;
		return CONV_ALREADYEXISTS;
	}
	
	if (pfconverting->partmettype==PMT_SPLITTED ) {
		try {
			CByteArray ba;
			ba.SetSize(PARTSIZE);

			CFile inputfile;
			int pos1,pos2;
			CString filename;

			// just count
			UINT maxindex=0;
			UINT partfilecount=0;
			bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part"));
			while (bWorking)
			{
				bWorking = finder.FindNextFile();
				++partfilecount;
				buffer=finder.GetFileName();
				pos1=buffer.Find('.');
				pos2=buffer.Find('.',pos1+1);
				fileindex=_tstoi(buffer.Mid(pos1+1,pos2-pos1) );
				if (fileindex==0) continue;
				if (fileindex>maxindex) maxindex=fileindex;
			}
			float stepperpart;
			if (partfilecount>0) {
				stepperpart=(80.0f / partfilecount );
				if ((uint64_t)maxindex*PARTSIZE<=pfconverting->size) pfconverting->spaceneeded=(uint64_t)maxindex*PARTSIZE;
					else pfconverting->spaceneeded=((uint64_t)(pfconverting->size / PARTSIZE) * PARTSIZE)+(pfconverting->size % PARTSIZE);
			} else {
				stepperpart=80.0f;
				pfconverting->spaceneeded=0;
			}
			
			UpdateGUI(pfconverting);

			if (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < ((uint64_t)maxindex*PARTSIZE) ) {
				delete file;
				return CONV_OUTOFDISKSPACE;
			}

			// create new partmetfile, and remember the new name
			file->CreatePartFile();
			newfilename=file->GetFullName();

			UpdateGUI(8,GetResString(IDS_IMP_STEPCRDESTFILE));
			file->m_hpartfile.SetLength( pfconverting->spaceneeded );

			uint16_t curindex=0;
			bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part"));
			while (bWorking)
			{
				bWorking = finder.FindNextFile();
				
				//stats
				++curindex;
				buffer.Format(GetResString(IDS_IMP_LOADDATA),curindex,partfilecount);
				UpdateGUI( 10+(curindex*stepperpart) ,buffer);

				filename=finder.GetFileName();
				pos1=filename.Find('.');
				pos2=filename.Find('.',pos1+1);
				fileindex=_tstoi(filename.Mid(pos1+1,pos2-pos1) );
				if (fileindex==0) continue;

				uint32_t chunkstart=(uint32_t)(fileindex-1) * PARTSIZE ;

				// open, read data of the part-part-file into buffer, close file
				inputfile.Open(finder.GetFilePath(),CFile::modeRead|CFile::shareDenyWrite);
				uint32_t readed=inputfile.Read( ba.GetData() ,PARTSIZE);
				inputfile.Close();

				buffer.Format(GetResString(IDS_IMP_SAVEDATA),curindex,partfilecount);
				UpdateGUI( 10+(curindex*stepperpart) ,buffer);

				// write the buffered data
				file->m_hpartfile.Seek(chunkstart, CFile::begin );
				file->m_hpartfile.Write(ba.GetData(),readed);
			}
		}
		catch(CFileException* error) {
			CString strError(GetResString(IDS_IMP_IOERROR));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (error->GetErrorMessage(szError, _countof(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(false, _T("%s"), strError);
			error->Delete();
			delete file;
			return CONV_IOERROR;
		}
		file->m_hpartfile.Close();
	}
	// import an external common format partdownload
	else //if (pfconverting->partmettype==PMT_DEFAULTOLD || pfconverting->partmettype==PMT_NEWOLD || Shareaza  ) 
	{
		
		if (!pfconverting->removeSource) 
			pfconverting->spaceneeded = (UINT)GetDiskFileSize(oldfile);

		UpdateGUI(pfconverting);

		if (!pfconverting->removeSource && (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < pfconverting->spaceneeded) ) {
			delete file;
			return CONV_OUTOFDISKSPACE;
		}

		file->CreatePartFile();
		newfilename=file->GetFullName();

		file->m_hpartfile.Close();

		BOOL ret=FALSE;
		UpdateGUI( 92 ,GetResString(IDS_COPY));
		DeleteFile(newfilename.Left(newfilename.GetLength()-4));

		if (!PathFileExists(oldfile)) {
			// data file does not exist. well, then create a 0 byte big one
			HANDLE hFile = CreateFile( newfilename.Left(newfilename.GetLength()-4) ,    // file to open
							GENERIC_WRITE,          // open for reading
							FILE_SHARE_READ,       // share for reading
							NULL,                  // default security
							CREATE_NEW,         // existing file only
							FILE_ATTRIBUTE_NORMAL, // normal file
							NULL);                 // no attr. template
			 
			ret= !(hFile == INVALID_HANDLE_VALUE) ;

			CloseHandle(hFile);
		}
			else 
		if (pfconverting->removeSource) 
			ret=MoveFile( oldfile, newfilename.Left(newfilename.GetLength()-4) );
		else 
			ret=CopyFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ,false);

		if (!ret) {
			file->DeleteFile();
			//delete file;
			return CONV_FAILED;
		}

	}


	UpdateGUI( 94 ,GetResString(IDS_IMP_GETPFINFO));

	DeleteFile(newfilename);
	if (pfconverting->removeSource)
		MoveFile(folder+_T("\\")+partfile,newfilename);
	else CopyFile(folder+_T("\\")+partfile,newfilename,false);


	file->m_hasharray.release();
	for ( GapList::iterator it = file->gaplist.begin(); it != file->gaplist.end(); ++it ) {
		delete *it;
	}
	file->gaplist.clear();

	if (file->LoadPartFile(thePrefs.GetTempDir(), file->GetPartMetFileName()) != PLR_LOADSUCCESS) {
		//delete file;
		file->DeleteFile();
		return CONV_BADFORMAT;
	}

	if (pfconverting->partmettype==PMT_NEWOLD || pfconverting->partmettype==PMT_SPLITTED ) {
		file->completedsize = file->m_uTransferred;
		file->m_uCompressionGain = 0;
		file->m_uCorruptionLoss = 0;
	}

	UpdateGUI( 100 ,GetResString(IDS_IMP_ADDDWL));

	theApp.downloadqueue->AddDownload(file,thePrefs.AddNewFilesPaused());
	file->SavePartFile();
	
	if (file->GetStatus(true) == PS_READY)
		theApp.sharedfiles->SafeAddKFile(file); // part files are always shared files


	if (pfconverting->removeSource) {

		bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*"));
		while (bWorking)
		{
			bWorking = finder.FindNextFile();
			VERIFY( _tunlink(finder.GetFilePath()) == 0 );
		}

		if (pfconverting->partmettype==PMT_SPLITTED)
			RemoveDirectory(folder+_T("\\"));
	}

	return CONV_OK;
}
Пример #19
0
BSTR CCMSUtils::doGetPathFiles(BSTR path_name)
{
	USES_CONVERSION;
	Value root;
	FastWriter fw;
	string retStr;
	CString pattern(path_name);
	pattern+=L"\\*.*";
	//CMSBOXW(pattern);
	Value images;
	int dir_index=0;
	int image_index=0;
	CString res;
	if(NULL!=path_name&&_file_exists(W2A(path_name))==0)
	{
		SetCurrentDirectory(path_name);
		CFileFind cff;
		BOOL found=cff.FindFile(pattern);
		while(found)
		{   
			found=cff.FindNextFile();
			//res+=L"  "+cff.GetFilePath();
			if(cff.IsDirectory()&&!cff.IsDots()){
				CString full_path=cff.GetFilePath();
				//full_path.Append(cff.GetFileName());
				if(!full_path.IsEmpty())
				{ 
					//res+=L"--"+full_path+L"--";
					char *file=W2A(full_path.AllocSysString());
					if(NULL!=file)
					{
						char buff[128]={0};
						_itoa_s(dir_index++,buff,128,10);
						root[buff]=file;
					}
				}
			}
			if( cff.GetFileName().Find(L".jpg")>0||
				cff.GetFileName().Find(L".gif")>0||
				cff.GetFileName().Find(L".png")>0||
				cff.GetFileName().Find(L".bmp")>0
				)
			{
				/*		  CMSBOX("image");
				return NULL;*/
				//CMSBOXW(cff.GetFilePath());
				char l_buff[128]={0};
				_itoa_s(image_index++,l_buff,128,10);
				images[l_buff]=W2A(cff.GetFilePath());
			}
		}
		cff.Close();
	}

	if(images.size()>=1)
	{
		root["images"]=images;
	}
	retStr=fw.write(root);
	//CMSBOXW(res);
	if(retStr.length()>0)
	{
		return SysAllocString(A2W(retStr.c_str()));
	}
	return CString("1").AllocSysString();
}
Пример #20
0
int SearchForFilesMFC::recursiveSearch(LPCTSTR path)
{
	USES_CONVERSION;

	CString cstr_path = path;
	if (cstr_path.GetLength() == 0) return 0;
	int files_found = 0;

#ifdef USE_LOW_LEVEL_DIRECTORY_SCANNING_METHOD

	HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA ffd;
	wstring spec = cstr_path;

	if (mThreadYielder != 0) mThreadYielder->peekAndPump();

	hFind = FindFirstFile(spec.c_str(), &ffd);

	if (mThreadYielder != 0) mThreadYielder->peekAndPump();

    if (hFind == INVALID_HANDLE_VALUE)  {
        return 0;
    }

	cstr_path.Replace(_T("\\*.*"), _T(""));

	do
	{
		if (mThreadYielder != 0) mThreadYielder->peekAndPump();

		// received a stop signal
		if (mbShouldStop == true) break;

        if (wcscmp(ffd.cFileName, L".") != 0 && 
            wcscmp(ffd.cFileName, L"..") != 0)
		{
            if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				if (isRecursiveSearch())
				{
					CString str = ffd.cFileName;
					// this folder, which exists on vista, makes the search routine crash
					if (str.Find(_T("winsxs")) != -1)
						continue;
					//this is the recycle bin, which should also not be searched (causes a crash)
					else if (str.Find(_T("recycler")) != -1)
						continue;
					else
						files_found += recursiveSearch(cstr_path + L"\\" + ffd.cFileName + _T("\\*.*"));
				}
            }
            else
			{
				std::string str_filename = T2A(ffd.cFileName);
				if (matchesSearchCriteria(str_filename) && !matchesSearchExclusionCriteria(str_filename)) 
				{
					if (mThreadYielder != 0) mThreadYielder->peekAndPump();

					files_found++;
					CString file_path = cstr_path + L"\\" + ffd.cFileName;
					std::string file_path_string = T2A(file_path);
					
					//we assume that the search returns local files
					ambulant::net::url file_path_url = ambulant::net::url::from_filename(file_path_string);
					addSearchResult(&file_path_url);
				}
            }
        }

		if (mThreadYielder != 0) mThreadYielder->peekAndPump();
    }
	while (FindNextFile(hFind, &ffd) != 0);

	if (mThreadYielder != 0) mThreadYielder->peekAndPump();

	if (GetLastError() != ERROR_NO_MORE_FILES) {
        FindClose(hFind);
        return 0;
    }

    FindClose(hFind);
    hFind = INVALID_HANDLE_VALUE;

#else

	CFileFind finder;
	BOOL b_is_working = finder.FindFile(cstr_path);

	if (mThreadYielder != 0) mThreadYielder->peekAndPump();

	while (b_is_working)
	{
		if (mThreadYielder != 0) mThreadYielder->peekAndPump();

		b_is_working = finder.FindNextFile();

		if (mThreadYielder != 0) mThreadYielder->peekAndPump();

		// received a stop signal
		if (mbShouldStop == true) break;

		if (finder.IsDots()) continue;

		// if it's a directory, recursively search it
		if (finder.IsDirectory())
		{
			if (isRecursiveSearch())
			{
				CString str = finder.GetFilePath();
				// this folder, which exists on vista, makes the search routine crash
				if (str.Find(_T("winsxs")) != -1)
					continue;
				//this is the recycle bin, which should also not be searched (causes a crash)
				else if (str.Find(_T("recycler")) != -1)
					continue;
				else
					files_found += recursiveSearch(str + _T("\\*.*"));
			}
		}
		else
		{
			CString filename;
			filename = finder.GetFileName();
			std::string str_filename = T2A(filename);
			if (matchesSearchCriteria(str_filename) && !matchesSearchExclusionCriteria(str_filename)) 
			{
				files_found++;
				//save the file path
				CString file_path = finder.GetFilePath();
				std::string file_path_string = T2A(file_path);
				
				//we assume that the search returns local files
				ambulant::net::url file_path_url = ambulant::net::url::from_filename(file_path_string);
				addSearchResult(&file_path_url);
			}
			
			if (mThreadYielder != 0) mThreadYielder->peekAndPump();
		}
	}
#endif

	amis::UrlList* results = getSearchResults();
	return results->size();
}
Пример #21
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);
}
Пример #22
0
bool AttachmentTest(CSocket* socket,CDlgMain* dlg,char* buffer,CDlgSettings* dlg2)
{
	bool filtering = false;

	dlg->console+=_T("\r\n*Starting Attachment filtering Test.");
	dlg->UpdateData(FALSE);
	ScrollToBottom(dlg);

	if(dlg2->auth_use)
	{
		if(!Auth(socket,dlg,buffer,dlg2->auth_use,dlg2->set_authuser,dlg2->set_authpass))
		{
			dlg->result_attachm = _T("?");
			dlg->MessageBox(_T("Couldn't test attachment filtering because provided authentication data are incorrect"));
			return false;
		}
	}
	else
	{
		Send(socket,dlg,"HELO mozilla");
		Receive(socket,dlg,buffer);
	}

	CString temp, temp2;
	char* msg;

	temp = dlg2->set_attach_path;
	temp+= _T("/*.*");

	char* path = StringToChar(temp);

	CFileFind Finder;
	BOOL found1 = Finder.FindFile(temp);
	DWORD Error1 = GetLastError();
	DWORD Error2 = -1;
	BOOL found2 = TRUE;
	CString sName = _T("(not found)");
	int check = 0;

	CString sEncoded;
	char* encoded;

	if(found1)
	{
		while(found2)
		{
			check++;
			found2 = Finder.FindNextFile();
			Error2 = GetLastError();

			if(!Finder.IsDirectory())
			{
				sName = Finder.GetFileName();

				FILE* pFile;
				long fSize;
				char* fbuffer;
				size_t fresult;
				temp = dlg2->set_attach_path;
				temp+= _T("/");
				temp+=sName;
				msg = StringToChar(temp);
				pFile = fopen((const char*)msg,"rb");
				if(!pFile)
				{
					dlg->result_attachm = _T("?");
					dlg->UpdateData(FALSE);
					ScrollToBottom(dlg);

					dlg->MessageBox(_T("Attachment filtering test error: Unable to open file"));
					break;
				}
				else
				{
					fseek(pFile , 0 , SEEK_END);
					fSize = ftell(pFile);
					rewind(pFile);

					fbuffer = new char[fSize];
					fresult = fread(fbuffer,1,fSize,pFile);
					fclose (pFile);
					sEncoded = Base64Encode((unsigned char*)fbuffer,fSize);
					free (fbuffer);

					Send(socket,dlg,"RSET");
					Receive(socket,dlg,buffer);

					temp = _T("MAIL FROM:<");
					temp+=dlg2->set_attach_from;
					temp+=_T(">");

					msg = StringToChar(temp);
					Send(socket,dlg,msg);
					Receive(socket,dlg,buffer);

					if(strcmp((const char*)MidStr(buffer,0,3),"250")!=0)
					{
						dlg->result_attachm = _T("?");
						dlg->UpdateData(FALSE);

						dlg->MessageBox(_T("Attachment filtering test error: Bad FROM field"));
						break;
					}
					else // [FROM] OK
					{
						temp = _T("RCPT TO:<");
						temp+=dlg2->set_attach_to;
						temp+=_T(">");
						msg = StringToChar(temp);
						Send(socket,dlg,msg);
						Receive(socket,dlg,buffer);

						if(strcmp((const char*)MidStr(buffer,0,3),"250")!=0)
						{
							dlg->result_attachm = _T("?");
							dlg->UpdateData(FALSE);

							dlg->MessageBox(_T("Attachment filtering test error: Bad RCPT TO field"));
							break;
						}
						else // [TO] OK
						{
							Send(socket,dlg,"DATA");
							Receive(socket,dlg,buffer);

							Send(socket,dlg,"MIME-Version: 1.0");

							temp = _T("From: ");
							temp+=dlg2->set_attach_from;
							msg = StringToChar(temp);
							Send(socket,dlg,msg);

							temp = _T("To: ");
							temp+=dlg2->set_attach_to;
							msg = StringToChar(temp);
							Send(socket,dlg,msg);

							temp = _T("Subject: Check Nr ");
							temp2.Format(_T("%d"),check);
							temp+=temp2;
							temp+= _T(" with \"");
							temp+=sName;
							temp+= _T("\"");
							msg = StringToChar(temp);
							Send(socket,dlg,msg);

							Send(socket,dlg,"Content-Type: multipart/mixed; boundary=\"xxxHELLOxWORLDxxx\"");
							Send(socket,dlg,"");
							Send(socket,dlg,"I am MIME message.");
							Send(socket,dlg,"--xxxHELLOxWORLDxxx");
							Send(socket,dlg,"Content-type: text/plain;");
							Send(socket,dlg,"");
							Send(socket,dlg,"SMTP Tool test.");
							Send(socket,dlg,"--xxxHELLOxWORLDxxx");
							Send(socket,dlg,"Content-Type: application/octet-stream");
							Send(socket,dlg,"Content-Transfer-Encoding: base64");

							temp = _T("Content-Disposition: attachment; filename=\"");
							temp+=sName;
							temp+= _T("\"");
							msg = StringToChar(temp);
							Send(socket,dlg,msg);

							Send(socket,dlg,"");

							// data
							encoded = StringToChar(sEncoded);
							Send(socket,dlg,encoded);
							delete encoded;

							Send(socket,dlg,"--xxxHELLOxWORLDxxx--");
							Send(socket,dlg,"");
							Send(socket,dlg,".");

							Receive(socket,dlg,buffer);

							filtering = (strcmp((const char*)MidStr(buffer,0,3),"250")!=0);
							
							if(filtering)
							{
								//break;
							}

							if((dlg2->set_attach_delay!=_T(""))||(dlg2->set_attach_delay!=_T("0")))
							{
								temp = _T("\r\nWaiting ");
								int ag = _wtoi(dlg2->set_attach_delay);
								temp2.Format(_T("%d"),ag);
								temp+=temp2;
								temp+= _T(" seconds...");
								dlg->console+=temp;
								dlg->UpdateData(FALSE);
								ScrollToBottom(dlg);
								
								Sleep(ag*1000);
							}
						}
					}
				}
			}
		}
	}

	if(dlg->result_attachm!=_T("?"))
		dlg->result_attachm = filtering?_T("YES"):_T("NO");

	Send(socket,dlg,"QUIT");
	Receive(socket,dlg,buffer);

	return true;
}
Пример #23
0
int CPlugins::Load( LPCTSTR lpstrPath)
{
	CString	csPath;
	int		nPlugin = 0,
			nCount = 0;
	BOOL	bFoundPlugins = FALSE,
			bValidPlugin;

	try
	{
		CFileFind			cFinder;

		// plugin struct array initialization
		for (int i=0; i<MAX_PLUGINS; i++ )
		{
			m_plugin[i].hDll		= NULL;
			m_plugin[i].pInventory	= NULL;
			m_plugin[i].pPrologResp	= NULL;
			m_plugin[i].pPrologWrite= NULL;
			m_plugin[i].pStart		= NULL;
			m_plugin[i].pEnd		= NULL;
			m_plugin[i].pClean		= NULL;
		}
		if ((lpstrPath == NULL) || (_tcslen( lpstrPath) == 0))
			// Use standard install path
			csPath.Format( _T( "%s\\plugins"), getInstallFolder());
		else
			// Use provided path to search for plugins
			csPath = lpstrPath;
		// Search for DLL into path
		m_pLogger->log( LOG_PRIORITY_DEBUG,  _T( "DLL PLUGIN => Searching for Plug-in DLL(s) in folder <%s>"), csPath);
		csPath +=  _T( "\\*.dll");
		bFoundPlugins = cFinder.FindFile( csPath);
		while (bFoundPlugins)
		{
			bValidPlugin = FALSE;
			// One DLL found, try to load it
			bFoundPlugins = cFinder.FindNextFile();
			m_pLogger->log(LOG_PRIORITY_DEBUG,  _T( "DLL PLUGIN => Trying to validate DLL <%s> as a Plug-in"), cFinder.GetFileName());
			if( (m_plugin[nPlugin].hDll = LoadLibrary( cFinder.GetFilePath())) == NULL )
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => Failed loading Plug-in DLL <%s>, %s"), cFinder.GetFileName(), LookupError( GetLastError()));
				continue;
			}
			// Get name
			m_plugin[nPlugin].csName = cFinder.GetFileTitle();
			// Try to load each API entry
			if( (m_plugin[nPlugin].pEnd = (HOOK_END)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_END_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No End hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pStart = (HOOK_START)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_START_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Start hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pClean = (HOOK_CLEAN)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_CLEAN_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Clean hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pInventory = (HOOK_INVENTORY)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_INVENTORY_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Inventory hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pPrologWrite = (HOOK_PROLOG_WRITE)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_PROLOGWRITE_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Prolog Read hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pPrologResp = (HOOK_PROLOG_RESP)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_PROLOGRESP_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Prolog response hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if (bValidPlugin)
			{
				// At least one hook available and plugin valid
				m_pLogger->log( LOG_PRIORITY_NOTICE,  _T( "DLL PLUGIN => Plug-in <%s> loaded"), m_plugin[nPlugin].csName);
				// Store and increase plugin number
				nPlugin++;
			}
			else
			{
				// Do not store DLL as a plugin
				m_pLogger->log(LOG_PRIORITY_DEBUG,  _T( "DLL PLUGIN => DLL <%s> is not a valid Plug-in"), cFinder.GetFileName());
				FreeLibrary( m_plugin[nPlugin].hDll );
			}
			nCount++;
		}
		cFinder.Close();
		m_pLogger->log(LOG_PRIORITY_DEBUG,  _T( "DLL PLUGIN => %d DLL Plug-in(s) succesfully loaded on %d DLL(s) found"), nPlugin, nCount);
		return nPlugin;
	}
	catch (CException *pEx)
	{
		m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => Error while parsing Plug-in directory <%s>"), LookupError( pEx));
		pEx->Delete();
		return -1;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	 CFileFind finder;
	 string img_dirPath;
	 img_dirPath="C:/Users/Sayan/Dropbox/GSoC_2015_Implementation/data_to_segment/";
	 //Reading number of files in the directory
	 int num_img=0;
	 DIR *dir;
	 struct dirent *ent;
	 
	 if ((dir = opendir ("C:\\Users\\Sayan\\Dropbox\\GSoC_2015_Implementation\\data_to_segment\\")) != NULL) {
		/* print all the files and directories within directory */
		 while ((ent = readdir (dir)) != NULL) {
		 printf ("%s\n", ent->d_name);
		 num_img=num_img+1;
		 }
		 closedir (dir);
	 } else {
		/* could not open directory */
		 perror ("");
		 return EXIT_FAILURE;
	 }
	 num_img=num_img-2;//First two entries are path
	 //Uptohere
	 CString dirPath_1,dirPathC,dirPathC1;
	 CString cstr,cstrf;	 	 	 
	 dirPathC1 = img_dirPath.c_str();
	 dirPathC = dirPathC1 + "\\*.bmp";
	 BOOL bWorking = finder.FindFile(dirPathC);
	 while (bWorking)

	{
		 //Read the registered image
		CString dirPathC2;
		dirPathC2="C:/Users/Sayan/Dropbox/GSoC_2015_Implementation/data_to_segment/";
		bWorking = finder.FindNextFile();
		cstr = finder.GetFileName();
		CStringA cstr1(cstr);
		CString finpath=dirPathC1+cstr;
		_tprintf_s(_T("%s\n"), (LPCTSTR) finpath);
		_tprintf_s(_T("%s\n"), (LPCTSTR) cstr);
		dirPathC2=dirPathC2+cstr;
	    CT2CA pszConvertedAnsiString (dirPathC2);
	    string image_name1(pszConvertedAnsiString);
		char *imagename=&image_name1[0];
		cv::Mat imgGray;//Initialize a matrix to store the gray version of color image
		cv::Mat img = imread(imagename); //Load the registered Image
		cout<<depthToStr(img.depth())<<endl;
		Size s = img.size();
		
		
		//define OD matrix; each column is associated with one stain (i.e. Hematoxylin, DAB, and red_marker)
		vector<vector<double>> stains;
		
		double blue[3] = {0.286, 0.731, 0.711};
		vector<double> Blue(&blue[0], &blue[0]+3);
		double green[3] = {0.704, 0.570, 0.696};
		vector<double> Green(&green[0], &green[0]+3);
		double red[3] = {0.650, 0.368, 0.103};
		vector<double> Red(&red[0], &red[0]+3);

		stains.push_back(Blue);		
		stains.push_back(Green);		
		stains.push_back(Red);

		cv::Mat intensity1=Ocv_ColorDeconvolution( stains,img, s);
		vector<cv::Mat> Deconvolved(3);
		split(intensity1, Deconvolved);
		cv::Mat DAB=Deconvolved[1];
		
		cv::Mat outIm=ocv_multiScaleFilter2D( DAB, s);
		
		//***Save outIm***
		char *extn1=".P.yml"; 
		string file11 = string(imagename2)+string(extn1);
		const char *file22=file11.c_str();
		cv::FileStorage storage1(file22, cv::FileStorage::WRITE);
		storage1 << "P" << outIm;
		storage1.release();
		
		
		
		//process lumens
		double G = 225;
		double eccThr = 1;
		vector <double> lumenAreaThr;
		double myints[] = {50,150000};
		lumenAreaThr.assign(myints,myints+2);
		vector<cv::Mat> imgch(3);
		split(img, imgch);
		imgch[0].convertTo(imgch[0], CV_64FC1);
		cv::Mat mask1 = (imgch[0] >G);
		imgch[1].convertTo(imgch[1], CV_64FC1);
		cv::Mat mask2 = (imgch[1] >G);
		imgch[2].convertTo(imgch[2], CV_64FC1);
		cv::Mat mask3 = (imgch[2] >G);
		cv::Mat mask2inv = (mask2==0);
		cv::Mat mask3inv = (mask3==0);
		mask1.setTo(0,mask2inv);
		mask1.setTo(0,mask3inv);

		cv::Mat bwLumenMask(s,CV_64FC1);
		bwLumenMask.setTo(0);
		bwLumenMask.setTo(1,mask1);

		Size img_size(s.height/2,s.width/2);//50% redeuction size initialization
		cv::Mat img1;
		resize(bwLumenMask, img1, img_size);//50% redeuction in display to fit in display-view
		imshow("bwLumenMask", img1);
		waitKey(5);

		  

		//imclearborder

		//Matlab
		//a matrix of same size with 1
		 
		cv::Mat im2(bwLumenMask.size(),CV_64FC1);
		im2.setTo(1);
		
		//copy make border with 0
		copyMakeBorder(im2,im2,1,1,1,1,BORDER_CONSTANT,Scalar(0));
		
		cv::Mat im21;
		erode(im2,im21,getStructuringElement(MORPH_RECT, Size (3,3)));
		
		//make a idx vector 
		cv::Mat im22(bwLumenMask.size(),CV_64FC1);
		im21(Rect(1, 1, im21.cols-2,im21.rows-2)).copyTo(im22);
		
		//Morphological reconstruction


		cv::Mat imgBWcopy =bwLumenMask;
		vector<Vec4i> hierarchy;
		vector<vector<Point>> contours;
		cv::Mat img225;
		imgBWcopy.convertTo(img225,CV_8U);
		findContours(img225,contours,hierarchy,CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);
		int imgRows=imgBWcopy.rows;int imgCols=imgBWcopy.cols;int radius1=650;int radius2=650;
		vector<int> contourList; // ID list of contours that touch the border
		// For each contour...
		for (int i = 0; i < contours.size(); i++ ) 
		{
			//Get the i'th contour
			vector<Point> cnt=contours[i];
			// Look at each point in the contour
			for (int j = 0; j < cnt.size(); j++) 
			{
				bool check1,check2;
				check1=(cnt[j].x>=0 & cnt[j].x<radius1)|(cnt[j].x>=imgRows-1-radius1 & cnt[j].x<imgRows);
				check2=(cnt[j].y>=0 & cnt[j].y<radius2)|(cnt[j].y>=imgRows-1-radius2 & cnt[j].y<imgRows);

				if (check1|check2)
				{
					contourList.push_back(i);
					break;
				}
			}
		}
		cv::Mat imclrbrdr1(bwLumenMask.size(),CV_64FC1);
		imclrbrdr1.setTo(1);
		for (int i = 0; i < contourList.size(); i++ ) 
		{
			//drawContours(imgBWcopy,contours,i,Scalar(0),CV_FILLED);
			drawContours(imclrbrdr1,contours,i,Scalar(0),CV_FILLED);
		}
		
		cv::Mat img21;
		resize(imclrbrdr1, img21, img_size);//50% redeuction in display to fit in display-view
		imshow("imclrbrdr1", img21);
		waitKey(5);
		
		cout<<depthToStr(bwLumenMask.depth())<<endl;
		cout<<depthToStr(imgBWcopy.depth())<<endl;

		cv::Mat imclrbrdr(bwLumenMask.size(),CV_64FC1);
		imclrbrdr= bwLumenMask - imclrbrdr1;

		cout<<depthToStr(imclrbrdr.depth())<<endl;



		
		cv::Mat img3;
		resize(imclrbrdr, img3, img_size);//50% redeuction in display to fit in display-view
		imshow("imclrbrdr", img3);
		waitKey(5);
		cv::Mat imclrbrdr2(bwLumenMask.size(),CV_64FC1);
		bwmorph_majority(imclrbrdr,imclrbrdr2);
		cv::Mat img4;
		resize(imclrbrdr2, img4, img_size);//50% redeuction in display to fit in display-view
		imshow("imclrbrdr2", img4);
		waitKey(5);
		vector<Vec4i> hierarchy1;
		vector<vector<Point>> contours1;
		cv::Mat img226;
		imclrbrdr2.convertTo(img226,CV_8U);
		findContours(img226,contours1,hierarchy1,CV_RETR_LIST,CV_CHAIN_APPROX_NONE);
		cv::Mat imclrbrdr3(bwLumenMask.size(),CV_64FC1);
		imclrbrdr3.setTo(0);

		for (int i = 0; i < contours1.size(); i++ ) 
		{
			if ((contours1[i].size()>3)&(contourArea(contours1[i])>30))//add (contourArea(contours1[i])<150000)
				drawContours(imclrbrdr3,contours1,i,Scalar(1),CV_FILLED);
		}

		

		cv::Mat img5;
		resize(imclrbrdr3, img5, img_size);//50% redeuction in display to fit in display-view
		imshow("imclrbrdr2_fill", img5);	
		waitKey(5);

		cv::Mat imclrbrdr4;
		morphologyEx(imclrbrdr3,imclrbrdr4,MORPH_CLOSE,getStructuringElement(MORPH_ELLIPSE , Size (5,5)));

		cv::Mat img6;
		resize(imclrbrdr4, img6, img_size);//50% redeuction in display to fit in display-view		
		imshow("imclrbrdr4", img6);	
		waitKey(5);
		
		cv::Mat imclrbrdr5;
		dilate(imclrbrdr4,imclrbrdr5,getStructuringElement(MORPH_ELLIPSE , Size (9,9)));

		cv::Mat img7;
		resize(imclrbrdr5, img7, img_size);//50% redeuction in display to fit in display-view		
		imshow("imclrbrdr5", img7);	
		waitKey(5);

		cv::Mat ringBW(bwLumenMask.size(),CV_64FC1);
		ringBW=imclrbrdr5-imclrbrdr4;

		cv::Mat img8;
		resize(ringBW, img8, img_size);//50% redeuction in display to fit in display-view		
		imshow("ringBW", img8);	
		waitKey(5);//***Save ringBW***

		CT2CA pszConvertedAnsiString1 (cstr);
	    string image_name11(pszConvertedAnsiString1);
		char *imagename2=&image_name11[0];
		char *extn=".phi0.yml"; 
		string file1 = string(imagename2)+string(extn);
		const char *file2=file1.c_str();
		cv::FileStorage storage(file2, cv::FileStorage::WRITE);
		storage << "ringBW" << ringBW;
		storage.release();

		

		
		

	}

	return 0;
}
Пример #25
0
void CKmlDlg::GetDataFiles(BOOL autoChecked)
{
    CFileFind finder;
    CString sFilterName = sPath + "*.*";
    int num = 0;
    BOOL bExist = finder.FindFile(sFilterName);
    m_fileList.ResetContent();
    while (bExist) {
        bExist = finder.FindNextFile(); 
        if(finder.IsDirectory())
        {
          continue;
        }

        CString ext = Utility::GetFileExt(finder.GetFileName());
        if(ext != "txt" && ext != "out")
        {
          continue;
        }
        FileName[num] = finder.GetFileName();
			  FilePath[num] = sPath + finder.GetFileName();
        if(autoChecked == FALSE && num < NumOfCheckBox)
        {
          if(KML_USE_CHECKLISTBOX)
          {
            m_fileList.AddString(FileName[num]);
            m_fileList.SetCheck(num, BST_CHECKED);
          }
          else
          {
            m_check[num].SetWindowText(FileName[num]);
            m_check[num].ShowWindow(SW_SHOW);
            m_check[num].SetCheck(BST_CHECKED);	
          }
        }
        ++num;
    }
    finder.Close();
	  NumOfFile = num + 1;

    if(!KML_USE_CHECKLISTBOX)
    {
      if(autoChecked)
      {
	      CString msg, txt;
        msg.Format("Total (#%d) output files selected.\r\n\r\n", NumOfFile);

	      for(int i = 0; i < NumOfFile; ++i)
	      {		
		      int x = i%10;
          txt.Format("%s%s", FileName[i], (i != 0 && (i % 10) == 0) ? " \r\n" : " ");
  	      msg += txt;
	      }
	      m_alltxt.SetWindowText(msg);
      }
      else
      {
	      for(int i = NumOfFile; i < NumOfCheckBox; ++i)
        {
          m_check[i].ShowWindow(SW_HIDE);
        }
      }
    }
}
Пример #26
0
void COpenFileDlg::AddRecursiveFiles( const CUString& strDir,int nItem )
{
	CFileFind	fileFind;
	CUString		pathAndFileType = strDir + CUString( _W( "\\*.*" ));
	BOOL		bStop=FALSE;

    CUStringConvert strCnv;

	// Iterate through the items in the listbox and populate the listconrol.
	if (fileFind.FindFile( strCnv.ToT( pathAndFileType ) ) )
	{
		do
		{
			bStop=(fileFind.FindNextFile()==0);
			CUString strFileName = CUString( fileFind.GetFileName() );
			CUString strFileRoot = CUString( fileFind.GetRoot() );
			CUString strFileType;

			if (	TRUE == fileFind.IsDirectory() && 
					FALSE == fileFind.IsDots() &&
					TRUE == m_bRecursiveDir )
			{
				AddRecursiveFiles( strDir + CUString( _W( "\\" ) ) + strFileName, nItem );
			}

			if (fileFind.IsDirectory()==FALSE && fileFind.IsDots()==FALSE)
			{
				int nPos=strFileName.ReverseFind( _T( '.' ) );
				

				if (nPos>0)
				{
					CUString strExt;
					strExt = strFileName.Right(strFileName.GetLength()-nPos-1);

					strFileType = strExt;

					strExt.MakeUpper();

					if ( CompareExt( strExt ) == TRUE )
					{
						CUString strFileSize;
						CUString strFileDate;
						CTime	fileTime;

						// Get the data/time stamp of this file
						fileFind.GetLastWriteTime( fileTime );

						// Format date time string
						strFileDate.Format( _W( "%4d/%02d/%02d %02d:%02d" ), fileTime.GetYear(), fileTime.GetMonth(), fileTime.GetDay(), fileTime.GetHour(), fileTime.GetMinute() );

						strFileSize.Format( _W( "%10.2f" ), fileFind.GetLength() / ( 1024.0 * 1024.0 ) );

                        CUStringConvert strCnv;

						m_ctrlRequestedFiles.InsertItem( nItem, strCnv.ToT( strFileName ));

						m_ctrlRequestedFiles.SetItemText( nItem, FILE_OPEN_TYPE, strCnv.ToT( strFileType ) );

						m_ctrlRequestedFiles.SetItemText( nItem, FILE_OPEN_DATE ,strCnv.ToT( strFileDate ) );

						m_ctrlRequestedFiles.SetItemText( nItem, FILE_OPEN_PATH, strCnv.ToT( strFileRoot ) );

						m_ctrlRequestedFiles.SetItemText( nItem, FILE_OPEN_SIZE, strCnv.ToT( strFileSize ) );

						m_ctrlRequestedFiles.SetItemData( nItem, (DWORD)fileTime.GetTime() );

						nItem++;
					}
				}
			}
		} while (bStop!=TRUE);
	}	


	m_bSortAscending=TRUE;
}
Пример #27
0
//把录像文件按时间逆序,然后反应到控件上  yjj 090304
void CAppealDlg::ProcessRecordFile(const CString& strUserName)
{
    if (strUserName == "")
    {
        return;
    }
    GetDlgItem(IDC_EDIT_USERNAME)->SetWindowText(strUserName);
    GetDlgItem(IDC_EDIT_PHONE_NUM)->SetWindowText("");
    GetDlgItem(IDC_EDIT_APPEAL_EMAIL)->SetWindowText("");
    GetDlgItem(IDC_EDIT_APPEAL_CONTENT)->SetWindowText("");



    CString strPath = CBcfFile::GetAppPath(); //得到当前的目录

    strPath += "log";
    strPath += "\\";

    CString gamenamefile = strPath + "gamename.bcf";
    DWORD dwHandle = cfgOpenFile(gamenamefile);

    if(dwHandle < 0x10)
        return;

    strPath += "log_";
    strPath += strUserName;
    strPath += "\\";

    CTime tCurTime = CTime::GetCurrentTime();
    CString direct = tCurTime.Format("%Y-%m-%d");

    CString strCurDir = strPath + direct;

    strCurDir += "\\";
    CFileFind finder;
    strCurDir += _T("*.*");
    int iFindFileCount = 0;
    m_fileList.clear();

    //从当前,向前找6个目录
    for (int i=0; i<6; i++)
    {
        BOOL bWorking = finder.FindFile(strCurDir);
        while (bWorking)
        {
            bWorking = finder.FindNextFile();
            if (finder.IsDots())
                continue;




            //找到一个文件
            //CString sFileName = finder.GetFileName();
            //CString sFilePath = finder.GetFilePath();
            RecordFileStruct recordfile;

            recordfile.strWholeName = finder.GetFilePath(); //得到完整名字
            recordfile.strFileName = finder.GetFileName();     //得到文件名字

            //wushuqun 2009.5.20
            recordfile.strGamePath = finder.GetFilePath();

            //if (recordfile.strFileName.Find(".zxh") == -1)
            //{
            //	continue;
            //}
            CString strNameId = GetFileNameID(recordfile.strFileName);
            recordfile.strGameName = GetGameName(dwHandle,strNameId); //得到游戏名字

            if (recordfile.strGameName == "")
            {
                continue;
            }
            finder.GetCreationTime(recordfile.timeCreatTime);    //得到创建文件时间
            recordfile.strGameTime = recordfile.timeCreatTime.Format("%m-%d %H:%M ");
            m_fileList.push_back(recordfile);  //把文件信息加入链表
            iFindFileCount ++;
        }
        //找完整个目录
        if (iFindFileCount >= 20)
        {
            break;
        }
        //
        CTimeSpan ts(1,   0,   0,   0);
        tCurTime -= ts;
        direct = tCurTime.Format("%Y-%m-%d");
        strCurDir = strPath + direct;

        strCurDir += "\\";
        strCurDir +=_T("*.*");
        //找上一天的目录
    }

    //按升序排列



    m_fileList.sort();
    m_FileListCtrl.DeleteAllItems();


    list<RecordFileStruct>::iterator iter = m_fileList.begin();
    int iCount = 0;
    for (; iter != m_fileList.end(); iter++)
    {
        RecordFileStruct recordfile = *iter;

        //RecordFileStruct* pRecordFile = iter;
        //iter ++;
        //CString strListNmae;
        //strListNmae.Format("%s  %s",recordfile.strGameName,recordfile.strGameTime);

        int iItem = m_FileListCtrl.InsertItem(m_FileListCtrl.GetItemCount(),recordfile.strGameName);
        m_FileListCtrl.SetItemText(iItem,1,recordfile.strGameTime);

        //wushuqun 2009.5.20
        //新增加一列“文件名称"
        m_FileListCtrl.SetItemText(iItem,2,recordfile.strFileName);

        //m_FileListCtrl.SetItemData(iItem,(DWORD)&iter);
        iCount++;
        //m_ListBox.AddString(strListNmae);
        //m_ListBox.InsertString(iCount++,strListNmae);
        if (iCount == 20)
        {
            break;
        }
    }









    cfgClose(dwHandle);
    finder.Close();



}
Пример #28
0
void CDBManageTrueDlg::OnBnClickedButtonOpendatapackageTrue()
{
	// TODO: 在此添加控件通知处理程序代码
	BROWSEINFO bi;
	char Buffer[MAX_PATH];
	//CString m_DatasetFoldPath ;//将路径保存在一个CString对象里
	bi.hwndOwner = this->m_hWnd;
	bi.pidlRoot =NULL;//初始化制定的root目录很不容易
	bi.pszDisplayName =(LPWSTR)Buffer;//此参数如为NULL则不能显示对话框
	bi.lpszTitle = L"选择光谱数据集文件夹路径";
	bi.ulFlags =BIF_USENEWUI ; //BIF_EDITBOX;//带编辑框的风格
	bi.lpfn = NULL;
	bi.lParam = 0;
	bi.iImage=IDR_MAINFRAME;
	//初始化入口参数bi结束
	LPITEMIDLIST pIDList = SHBrowseForFolder(&bi);//调用显示选择对话框

	if(pIDList==NULL)
	{	
		return;
	}
	SHGetPathFromIDList(pIDList,(LPWSTR)Buffer);
	//取得文件夹路径到Buffer里
	m_SpecDataFoldPath.Format(L"%s",Buffer);
	// free memory used      
	IMalloc * imalloc = 0;
	if (SUCCEEDED(SHGetMalloc(&imalloc)))
	{
		imalloc->Free (pIDList);
		imalloc->Release();
	}
	//从文件夹中导入光谱数据及相关信息
	CString strDir=m_SpecDataFoldPath;
	strDir.Replace(L"\\",L"\\\\");
	strDir += "\\*.*";

	// 遍历得到所有子文件夹名
	CFileFind finder; 
	BOOL bWorking = finder.FindFile(strDir);

	/*m_ary_PicturesPath.RemoveAll();
	m_ary_SpecFileName.RemoveAll();
	m_ary_SpecFilePath.RemoveAll();
	m_ListSpectrumToAdd.DeleteAllItems();
	//m_ary_ProjectPathNew.RemoveAll();*/
	while (bWorking)  
	{
		bWorking = finder.FindNextFile();
		CString str=finder.GetFileName();
		if(str.Right(4)==L".CSV"||str.Right(4)==L".csv" &&L"." !=str &&L".." != str)//注意该句需要排除“.”“..”
		{
			CString filename;
			CString fileTitle;
			//CString str=finder.GetFileName();
			m_ary_SpecFilePath.Add(finder.GetFilePath());
			//获取文件名(不包含后缀)  
			//采用CString的Left(int count)截取CString中从左往右数的count个字符  
			//fileName.GetLength()-4中的4表示".csv"四个字符  
			m_ary_SpecFileName.Add(finder.GetFileTitle());//将文件名(不包含后缀)添加到数组中  
		}
		if(str.Right(4)==L".jpg" ||str.Right(4)==L".bmp"||str.Right(4)==L".gif"&&L"." !=str &&L".." != str)m_ary_PicturesPath.Add(finder.GetFilePath());
		if(str==L"数据说明.xls"||str==L"数据说明.xlsx"&&L"." !=str &&L".." != str)m_ExcelInfoPath=finder.GetFilePath();
	}
	finder.Close();
	if(m_ary_SpecFileName.GetCount()==0)
	{
		MessageBox(L"该文件夹中没有规定格式的光谱数据,请重新选择!",L"警告",MB_ICONWARNING);
		return;
	}
	if(m_ary_SpecFileName.GetCount()<30)
	{
		MessageBox(L"光谱数量太少",L"警告",MB_ICONWARNING);
	}
	m_PicIndex=0;
	CString Winename;
	CString Wineinfo=L"";
	CString Comfrom;
	CString ReceiveDate;
	CString Wineinfotemp;
	if(m_ExcelInfoPath.IsEmpty())
	{
		if(IDOK==MessageBox(L"数据包中缺少必要的光谱说明文件,是否自行填写?",L"信息缺失",MB_OKCANCEL|MB_ICONQUESTION))
		{
			CInputSpecDatasetInfoDlg InputSpecDatasetInfoDlg;
			if(IDOK==InputSpecDatasetInfoDlg.DoModal())
			{
				m_WineName=InputSpecDatasetInfoDlg.m_WineName;
				m_AlcoholContent=InputSpecDatasetInfoDlg.m_AlcoholContent;
				Wineinfo=m_AlcoholContent+L"度,";
				m_Flavour=InputSpecDatasetInfoDlg.m_Flavour;
				Wineinfo+=m_Flavour;
				Wineinfo+=L",";
				m_Brand=InputSpecDatasetInfoDlg.m_Brand;
				Wineinfo+=m_Brand;
				m_Comfrom=L"管理员";
				SYSTEMTIME tm;		
				GetDirTime(m_SpecDataFoldPath,tm);			
				ReceiveDate.Format(L"%d-%d-%d",tm.wYear,tm.wMonth,tm.wDay);			
			}
			else
			{
				m_ary_SpecFilePath.RemoveAll();
				m_ary_SpecFileName.RemoveAll();
				m_ary_PicturesPath.RemoveAll();
				return;
			}
		}
		else
		{
			m_ary_SpecFilePath.RemoveAll();
			m_ary_SpecFileName.RemoveAll();
			m_ary_PicturesPath.RemoveAll();
			return;
		}

	}
	else
	{
		CString strDirExcel=m_ExcelInfoPath;
		//strDirExcel.Replace(L"\\",L"\\\\");
		CExcelOperator ExcelOperator;
		ExcelOperator.LoadExcel(strDirExcel);

		ExcelOperator.GetItem(1,1,L"String",m_WineName);


		ExcelOperator.GetItem(2,1,L"int",m_AlcoholContent);
		Wineinfo+=m_AlcoholContent;
		Wineinfo+=L"度,";
		ExcelOperator.GetItem(3,1,L"String",m_Flavour);
		Wineinfo+=m_Flavour;
		Wineinfo+=L",";
		ExcelOperator.GetItem(4,1,L"String",m_Brand);
		Wineinfo+=m_Brand;

		ExcelOperator.GetItem(5,1,L"Date",m_ProductionDate);
		//Wineinfo+=Wineinfotemp;

		ExcelOperator.GetItem(6,1,L"String",m_BatchNo);
		//Wineinfo+=Wineinfotemp;

		ExcelOperator.GetItem(7,1,L"String",m_Comfrom);
		ExcelOperator.GetItem(8,1,L"Date",ReceiveDate);

		ExcelOperator.ReleaseExcel();
	}


	SortCArrayByFirst(m_ary_SpecFileName,m_ary_SpecFilePath);

	for(int i=0;i<m_ary_SpecFileName.GetCount();i++)
	{
		//CString Current=m_ary_SpecFilePath[i];

		m_ListSpectrumToAdd.InsertItem(i,m_ary_SpecFileName[i]);
		m_ListSpectrumToAdd.SetItemText(i,1,m_WineName);
		m_ListSpectrumToAdd.SetItemText(i,2,Wineinfo);
		m_ListSpectrumToAdd.SetItemText(i,3,m_ProductionDate);
		m_ListSpectrumToAdd.SetItemText(i,4,m_BatchNo);
		m_ListSpectrumToAdd.SetItemText(i,5,m_Comfrom);
		m_ListSpectrumToAdd.SetItemText(i,6,ReceiveDate);
	}

}
Пример #29
0
LRESULT CIMoteTerminal::OnReceiveSerialData(WPARAM wParam, LPARAM lParam)
{
	//following couple of lines allow us to debug a raw datastream
	char *rxstring = (char *)lParam;
	DWORD numBytesReceived = (DWORD) wParam;
	BufferAppend(rxstring, numBytesReceived);
	delete []rxstring;
	return TRUE;

#if 0
	DWORD i,offset;
	//TRACE("Rx...Buffer = %#X\tNumBytesReceived = %d\n",rxstring,numBytesReceived);
	/*****
	data format for the accelerometer data looks something like:
	0{2 bit addr}{5 data bits} {1}{7 data bits}
	******/
	for(offset=0; offset<numBytesReceived; offset++)
	{
		//find the correct first bytes
		if((rxstring[offset]  & 0xE0) == 0)
		{
			break;
		}
	}
	//offset current points to the correct first element for us to look at
	//start reconstructing the 16 bit numbers and doing the divide
	
	for(i=offset;(i+6)<numBytesReceived; i+=6)
	{	
		static bool init = false;
		POINT point;
		DWORD B,C,D,Tx, Ty,T;
		int Rx, Ry;
		B = ((rxstring[i] & 0x1F)<<7) | (rxstring[i+1] & 0x7F);
		C = ((rxstring[i+2] & 0x1F)<<7) | (rxstring[i+3] & 0x7F);
		D = ((rxstring[i+4] & 0x1F)<<7) | (rxstring[i+5] & 0x7F);
		Tx = B;
		Ty = D-C;
		T = C/2 + D/2 - B/2;

		Rx = ((Tx << 16) / T) - (65536/2);
		Ry = ((Ty << 16) / T) - (65536/2);
		//point.x =(LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]) -(65536/2);
		//point.x = (LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]);
		//TRACE("%d %d = %d\n",rxstring[i], rxstring[i+1], point.x);
		//TRACE("Found T, index %d \n", byte_index);
		//TRACE("Tx = %d, Ty = %d, T = %d, Rx = %d, Ry = %d\n",Tx, Ty, T, Rx, Ry);
		point.x = (LONG) Rx;
		point.y = (LONG) Ry;

		if(!init)
		{
			CIMoteCartesianPlot *pFrame=CreateNewView(0,0xDEADBEEF,0);
			pFrame->SetMappingFunction(-2,2);
			init = true;
		}
		AddPoint(point, 0);
	}
		
	delete rxstring;

	
	return TRUE;
//#endif;
	POINT point;
	static bool bGotBeef = 0;
	static bool bFirstTime = true;
	static unsigned short NumDataBytes;
	static unsigned short NumBytesProcessed;
	//static int MoteIDs[NUMCHANNELS];
	static unsigned short SensorID;
	static unsigned int MoteID;
	static unsigned int SensorType;
	static unsigned int ExtraInfo;
	static unsigned int TimeID;
	static unsigned int ChannelID;
	static unsigned char HeaderIndex;
	static unsigned char Header[16];
	unsigned short *short_ptr;
	unsigned int *int_ptr;
	DWORD byte_index;
	static unsigned char LastByte = 0;
//	unsigned int ProblemIndex;
	unsigned int EmptyChannel;
	static unsigned int NumProblems = 0;
	CString logentry;
	static bool bPrintheader=true;
	CTime time;
	static int Tx, Ty, T, Rx, Ry, Tb, Tc, Td, b0, b1;
	static int CurrentCounter, CurrentByte;
	// Hack, for now statically allocate 
	static unsigned char *CameraBuffer;
	static unsigned int CurrentCameraID;
	static unsigned int CameraBufferIndex;
	static unsigned int SegmentIndex;
	static bool PictureInProgress;
	static unsigned int LastPicID;

#define MAX_PIC_SIZE 80000
#define INVALID_SENSOR 0
#define PH_SENSOR 1
#define PRESSURE_SENSOR 2
#define ACCELEROMETER_SENSOR 3
#define CAMERA_SENSOR 4

#define FIRST_SEGMENT 0x1111
#define MID_SEGMENT 0
#define END_OF_PIC 0xffff

	for(int channel = 0; (channel < NUMCHANNELS) && bFirstTime; channel++) {
		MoteIDs[channel] = 0;
		HeaderIndex = 0;
		CurrentCameraID = 0;
		CameraBuffer = NULL;
		CameraBufferIndex = 0;
		PictureInProgress = false;
	}

	if (bFirstTime) {
		// Figure out the start of the file names
		CFileFind finder;
		CString TempName;
		unsigned int TempID;
		LastPicID = 0;
		BOOL bResult = finder.FindFile("c:\\icam\\*.jpg");

		while (bResult) {
			bResult = finder.FindNextFile();
			TempName = finder.GetFileName();
			if (sscanf((LPCSTR)TempName, "%d.jpg", &TempID) == 1) {
				// valid pic id
				if (LastPicID < TempID) {
					LastPicID = TempID;
				}
			}
		}
		LastPicID++;
	}


	bFirstTime = false;
	TRACE("Rx...Buffer = %#X\tNumBytesReceived = %d\n",rxstring,numBytesReceived);
	byte_index = 0;
	while(byte_index < numBytesReceived) {
		// Look for DEADBEEF, get all header info
		for(; (byte_index < numBytesReceived) && !bGotBeef; byte_index++) {
			switch (HeaderIndex) {
			case 0:
				if (rxstring[byte_index] == 0xEF) {
					HeaderIndex = 1;
				}
				break;
			case 1:
				if (rxstring[byte_index] == 0xBE) {
					HeaderIndex = 2;
				} else {
					HeaderIndex = 0;
				}
				break;
			case 2:
				if (rxstring[byte_index] == 0xAD) {
					HeaderIndex = 3;
				} else {
					HeaderIndex = 0;
				}
				break;
			case 3:
				if (rxstring[byte_index] == 0xDE) {
					HeaderIndex = 4;
				} else {
					HeaderIndex = 0;
				}
				break;
			case 13:
				// Done with header
				CurrentCounter = 0;
				CurrentByte = 0;
				bGotBeef = 1;
				Header[HeaderIndex] = rxstring[byte_index];
				/*
				* Header :
				* DEADBEEF (4B)
				* MOTE ID (4B)
				* Sensor TYPE (2B)
				* LENGTH (2B)
				* Extra Info (2B)
				* 
				*/
				int_ptr = (unsigned int *) &(Header[4]);
				MoteID = *int_ptr;
				short_ptr = (unsigned short *) &(Header[8]);
				SensorType = *short_ptr;
				short_ptr++;
				NumDataBytes = *short_ptr;
				short_ptr++;
				ExtraInfo = *short_ptr;
				NumBytesProcessed = 0;
				ChannelID = NUMCHANNELS;
				EmptyChannel = NUMCHANNELS;

				if (SensorType == CAMERA_SENSOR) {
					// check with segment
					TRACE("Camera seg %x, buf Index %d, NumDataBytes %d\r\n",
						ExtraInfo, CameraBufferIndex, NumDataBytes);
					if (ExtraInfo == FIRST_SEGMENT) {
						// first segment
						CurrentCameraID = MoteID;
						CameraBufferIndex = 0;						
						if (!PictureInProgress) {
							// create buffer
							CameraBuffer = new unsigned char[MAX_PIC_SIZE];
							PictureInProgress = true;
						}
					}
					SegmentIndex = 0;	// Per segment index
					break;	// don't process the channel stuff
				}
				// Find mote channel, 
				for(int channel = 0; channel < NUMCHANNELS; channel++) {
					if (MoteIDs[channel] == MoteID) {
						ChannelID = channel;
						break;
					} else {
						if (MoteIDs[channel] == 0) {
							EmptyChannel = channel;
						}
					}
				}
				

				if (ChannelID == NUMCHANNELS) {
					// Didn't find a channel
					if (EmptyChannel < NUMCHANNELS) {
						// assign the mote id to this channel
						MoteIDs[EmptyChannel] = MoteID;
						ChannelID = EmptyChannel;
						CIMoteCartesianPlot *pFrame=CreateNewView(ChannelID,MoteID,SensorID);
						/*
							Note to LAMA:  below is an example of how to use the setmapping function
							pFrame->SetMappingFunction(slope, offset, minrange, maxrange
						*/
						switch(SensorType) {
							case PH_SENSOR:
								pFrame->SetMappingFunction(0,14);
								rawdata = false;
								break;
							case PRESSURE_SENSOR:
								pFrame->SetMappingFunction(0,20.684);
								//pFrame->SetMappingFunction(0,300);
								rawdata = false;
								break;
							case ACCELEROMETER_SENSOR:
								pFrame->SetMappingFunction(-2,2);
								rawdata = false;
								break;
							default :
								//pFrame->SetMappingFunction(1,1,0,14);
								pFrame->SetMappingFunction(-32768,32768);
						}
						//UpdateAllViews(NULL);
					}  
					/*
					* NOTE: if ChannelID is not assigned, 
					* the processing will remain the same, but the data won't
					* be displayed.
					* TODO : handle later
					*/
				}
				//log transaction info to file here:
				if(bPrintheader)
				{
					logentry.Format("Timestamp, iMoteID, # of Bytes\r\n");
					//logfile<<logentry<<endl;
					SaveLogEntry(&logentry);
					bPrintheader=false;
				}
				time=time.GetCurrentTime();
				//logfile<<time.Format("%c");
				SaveLogEntry(&time.Format("%c"));
				logentry.Format(", %#X, %d\r\n",MoteID, NumDataBytes);
				//logfile<<logentry<<endl;
				SaveLogEntry(&logentry);				
				break;
			default:
				Header[HeaderIndex] = rxstring[byte_index];
				HeaderIndex++;
				break;
			}
		}
		if (!bGotBeef) {
			delete []rxstring;
			return TRUE;
		}
		// Got DEADBEEF, process data
		for(; byte_index <numBytesReceived; byte_index++,NumBytesProcessed ++) {
			if (NumBytesProcessed >= NumDataBytes) {
				// go back to start, look for DEADBEEF again
				bGotBeef = false;
				HeaderIndex = 0;
				TRACE("Mote ID %lx, NumBytes %ld, byte index %d \n", MoteID, NumDataBytes, byte_index);
				//MoteID = 0;
				//NumDataBytes = 0;
				break;
			}
			if (rawdata) {	//RAW_BYTES mode, no processing
				// Assume data is 2 bytes long, and back to back
				if (CurrentByte == 0) {
					b0 = rxstring[byte_index];
					CurrentByte = 1;
				} else {
					b1 = rxstring[byte_index];
					CurrentByte = 0;
					int sample_data;
					sample_data = (b1 <<8) + b0;
					//sample_data -= 0x2000;
					//sample_data = sample_data << 2;
					point.x = (LONG) sample_data;
					point.y = 0;
					//TRACE("sample is %d\r\n", sample_data);
					if (ChannelID < NUMCHANNELS) {
						// valid channel
						AddPoint(point, ChannelID);
					}
				}
			} else {
				if (CurrentByte == 0) {
					b0 = rxstring[byte_index];
					CurrentByte = 1;
					if (SensorType == CAMERA_SENSOR) {
						// just copy data
						CameraBuffer[CameraBufferIndex] = b0;
						SegmentIndex++;
						CameraBufferIndex++;
					}
				} else {
					b1 = rxstring[byte_index];
					CurrentByte = 0;
					switch(SensorType) {
						case PH_SENSOR:
							/*
							* A/D maps 0-5V range to 0-32 K 
							* pH = -7.752 * V + 16.237
							* V = raw_data * 5 / 32768
							* The plot output expects the 0 - 14 range to be represented in -32 - 32 K
							* point.x = (-7.752 * (raw_data * 5/32768) + 16.237) * 64K / 14 - 32K
							*/
							double ph_data;
							ph_data = (b1 <<8) + b0;
							ph_data = -7.752 * (ph_data/ 32768) * 5 + 16.237;
							ph_data = (ph_data * 65536 / 14) - 32768;
							point.x = (LONG) ph_data;
							point.y = 0;
							if (ChannelID < NUMCHANNELS) {
								// valid channel
								AddPoint(point, ChannelID);
							}
							break;
						case PRESSURE_SENSOR:
							/*
							* A/D maps 0-5V range to 0-32 K 
							* The plot output expects the 0 - 20.684 range to be represented in -32 - 32 K
							* point.x = (raw_data * 5/32768) * 64K / 20.684 - 32K
							*/
							int pressure_data;
							pressure_data = (b1 <<8) + b0;
							pressure_data = pressure_data * 2 - 32768;
							point.x = (LONG) pressure_data;
							point.y = 0;
							if (ChannelID < NUMCHANNELS) {
								// valid channel
								AddPoint(point, ChannelID);
							}
							break;
						case ACCELEROMETER_SENSOR:
							// TRACE("CurrentCounter %d, ByteIndex %d \n", CurrentCounter, byte_index);
							switch (CurrentCounter) {
								case 0:
									Tx = (b0 <<8) + b1;;	
									CurrentCounter = 1;
									//TRACE("Found Tx, index %d \n", byte_index);
									break;
								case 1:
									Ty = (b0 <<8) + b1;
									CurrentCounter = 2;
									//TRACE("Found Ty, index %d \n", byte_index);
									break;
								case 2:
									T = (b0 <<8) + b1;
									Rx = ((Tx << 16) / T) - (65536/2);
									Ry = ((Ty << 16) / T) - (65536/2);
									//point.x =(LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]) -(65536/2);
									//point.x = (LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]);
									//TRACE("%d %d = %d\n",rxstring[i], rxstring[i+1], point.x);
									//TRACE("Found T, index %d \n", byte_index);
									//TRACE("Tx = %d, Ty = %d, T = %d, Rx = %d, Ry = %d\n",Tx, Ty, T, Rx, Ry);
									point.x = (LONG) Rx;
									point.y = (LONG) Ry;
									if (ChannelID < NUMCHANNELS) {
										// valid channel
										AddPoint(point, ChannelID);
									}
									CurrentCounter = 0;
									break;
								default:
									break;
							}
							break;
						
						case CAMERA_SENSOR:
							// just copy data
							CameraBuffer[CameraBufferIndex] = b1;
							SegmentIndex++;
							CameraBufferIndex++;
							break;
						
					}
				}
			//for now, just save the point in the x field of the structure
			}
			//NumBytesProcessed += 2;		
		}
		TRACE("NumBytesProcessed %d, NumDataBytes %d\r\n", NumBytesProcessed, NumDataBytes);
		// Check if we reached the end of a picture, write it to file
		if ((SensorType == CAMERA_SENSOR) && (NumBytesProcessed == NumDataBytes) &&
			(ExtraInfo == END_OF_PIC)) {
				// Create output buffer , assume header < 1000
				unsigned char *JpgImage;
				int JpgImageLen;
				JpgImage = new unsigned char[CameraBufferIndex+1000];
				// build jpeg image
				BuildJPG(CameraBuffer, CameraBufferIndex, JpgImage, &JpgImageLen);
				// write to file
				char pszFileName[200];
				CFile PictureFile;
				CFileException fileException;

				sprintf(pszFileName, "c:\\icam\\%d.jpg", LastPicID);
				LastPicID++;

				if ( !PictureFile.Open( pszFileName, CFile::modeCreate |   
									CFile::modeWrite | CFile::typeBinary,
									&fileException ) )
				{
					TRACE( "Can't open file %s, error = %u\n",
								pszFileName, fileException.m_cause );
				}
				//PictureFile.Write(CameraBuffer, CameraBufferIndex);
				PictureFile.Write(JpgImage, JpgImageLen);
				PictureFile.Close();
				TRACE("Wrote Jpeg image raw %d\r\n", CameraBufferIndex);
				
				delete []CameraBuffer;
				delete []JpgImage;
				PictureInProgress = false;
		}
	}
	delete []rxstring;
	return TRUE;
#endif;
}
Пример #30
0
BOOL CPPgDirectories::OnApply()
{
	bool testtempdirchanged=false;
	CString testincdirchanged = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR);

	CString strIncomingDir;
	GetDlgItemText(IDC_INCFILES, strIncomingDir);
	MakeFoldername(strIncomingDir);
	if (strIncomingDir.IsEmpty()){
		strIncomingDir = thePrefs.GetDefaultDirectory(EMULE_INCOMINGDIR, true); // will create the directory here if it doesnt exists
		SetDlgItemText(IDC_INCFILES, strIncomingDir);
	}
	else if (thePrefs.IsInstallationDirectory(strIncomingDir)){
		AfxMessageBox(GetResString(IDS_WRN_INCFILE_RESERVED));
		return FALSE;
	}
	else if (strIncomingDir.CompareNoCase(testincdirchanged) != 0 && strIncomingDir.CompareNoCase(thePrefs.GetDefaultDirectory(EMULE_INCOMINGDIR, false)) != 0){
		// if the user chooses a non-default directory which already contains files, inform him that all those files
		// will be shared
		CFileFind ff;
		CString strSearchPath;
		strSearchPath.Format(_T("%s\\*"),strIncomingDir);
		bool bEnd = !ff.FindFile(strSearchPath, 0);
		bool bExistingFile = false;
		while (!bEnd)
		{
			bEnd = !ff.FindNextFile();
			if (ff.IsDirectory() || ff.IsDots() || ff.IsSystem() || ff.IsTemporary() || ff.GetLength()==0 || ff.GetLength()>MAX_EMULE_FILE_SIZE)
				continue;

			// ignore real LNK files
			TCHAR szExt[_MAX_EXT];
			_tsplitpath(ff.GetFileName(), NULL, NULL, NULL, szExt);
			if (_tcsicmp(szExt, _T(".lnk")) == 0){
				SHFILEINFO info;
				if (SHGetFileInfo(ff.GetFilePath(), 0, &info, sizeof(info), SHGFI_ATTRIBUTES) && (info.dwAttributes & SFGAO_LINK)){
					if (!thePrefs.GetResolveSharedShellLinks())
						continue;
				}
			}

			// ignore real THUMBS.DB files -- seems that lot of ppl have 'thumbs.db' files without the 'System' file attribute
			if (ff.GetFileName().CompareNoCase(_T("thumbs.db")) == 0)
				continue;

			bExistingFile = true;
			break;
		}
		if (bExistingFile
			&& AfxMessageBox(GetResString(IDS_WRN_INCFILE_EXISTS), MB_OKCANCEL | MB_ICONINFORMATION) == IDCANCEL)
		{
			return FALSE;
		}
	}
	
	// checking specified tempdir(s)
	CString strTempDir;
	GetDlgItemText(IDC_TEMPFILES, strTempDir);
	if (strTempDir.IsEmpty()){
		strTempDir = thePrefs.GetDefaultDirectory(EMULE_TEMPDIR, true); // will create the directory here if it doesnt exists
		SetDlgItemText(IDC_TEMPFILES, strTempDir);
	}

	int curPos=0;
	CStringArray temptempfolders;
	CString atmp=strTempDir.Tokenize(_T("|"), curPos);
	while (!atmp.IsEmpty())
	{
		atmp.Trim();
		if (!atmp.IsEmpty()) {
			if (CompareDirectories(strIncomingDir, atmp)==0){
					AfxMessageBox(GetResString(IDS_WRN_INCTEMP_SAME));
					return FALSE;
			}	
			if (thePrefs.IsInstallationDirectory(atmp)){
				AfxMessageBox(GetResString(IDS_WRN_TEMPFILES_RESERVED));
				return FALSE;
			}
			bool doubled=false;
			for (int i=0;i<temptempfolders.GetCount();i++)	// avoid double tempdirs
				if (temptempfolders.GetAt(i).CompareNoCase(atmp)==0) {
					doubled=true;
					break;
				}
			if (!doubled) {
				temptempfolders.Add(atmp);
				if (thePrefs.tempdir.GetCount()>=temptempfolders.GetCount()) {
					if( atmp.CompareNoCase(thePrefs.GetTempDir(temptempfolders.GetCount()-1))!=0	)
						testtempdirchanged=true;
				} else testtempdirchanged=true;

			}
		}
		atmp = strTempDir.Tokenize(_T("|"), curPos);
	}

	if (temptempfolders.IsEmpty())
		temptempfolders.Add(strTempDir = thePrefs.GetDefaultDirectory(EMULE_TEMPDIR, true));

	if (temptempfolders.GetCount()!=thePrefs.tempdir.GetCount())
		testtempdirchanged=true;

	// applying tempdirs
	if (testtempdirchanged) {
		thePrefs.tempdir.RemoveAll();
		for (int i=0;i<temptempfolders.GetCount();i++) {
			CString toadd=temptempfolders.GetAt(i);
			MakeFoldername(toadd);
			if (!PathFileExists(toadd))
				CreateDirectory(toadd,NULL);
			if (PathFileExists(toadd))
				thePrefs.tempdir.Add(toadd);
		}
	}
	if (thePrefs.tempdir.IsEmpty())
		thePrefs.tempdir.Add(thePrefs.GetDefaultDirectory(EMULE_TEMPDIR, true));

	thePrefs.m_strIncomingDir = strIncomingDir;
	MakeFoldername(thePrefs.m_strIncomingDir);
	thePrefs.GetCategory(0)->strIncomingPath = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR);

	thePrefs.shareddir_list.RemoveAll();
	m_ShareSelector.GetSharedDirectories(&thePrefs.shareddir_list);
	for (int i = 0; i < m_ctlUncPaths.GetItemCount(); i++)
		thePrefs.shareddir_list.AddTail(m_ctlUncPaths.GetItemText(i, 0));

	// check shared directories for reserved folder names
	POSITION pos = thePrefs.shareddir_list.GetHeadPosition();
	while (pos){
		POSITION posLast = pos;
		const CString& rstrDir = thePrefs.shareddir_list.GetNext(pos);
		if (!thePrefs.IsShareableDirectory(rstrDir))
			thePrefs.shareddir_list.RemoveAt(posLast);
	}

	if (testtempdirchanged)
		AfxMessageBox(GetResString(IDS_SETTINGCHANGED_RESTART));
	
	// on changing incoming dir, update incoming dirs of category of the same path
	if (testincdirchanged.CompareNoCase(thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR)) != 0) {
		CString oldpath;
		bool dontaskagain=false;
		for (int cat=1; cat<=thePrefs.GetCatCount()-1;cat++){
			oldpath=CString(thePrefs.GetCatPath(cat));
			if (oldpath.Left(testincdirchanged.GetLength()).CompareNoCase(testincdirchanged)==0) {

				if (!dontaskagain) {
					dontaskagain=true;
					if (AfxMessageBox(GetResString(IDS_UPDATECATINCOMINGDIRS),MB_YESNO)==IDNO)
						break;
				}
				thePrefs.GetCategory(cat)->strIncomingPath = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR) + oldpath.Mid(testincdirchanged.GetLength());
			}
		}
	}

	theApp.emuledlg->sharedfileswnd->Reload();
	
	SetModified(0);
	return CPropertyPage::OnApply();
}