Beispiel #1
0
BOOL EM_FILEINFO::AddFile(LPCTSTR lpszFileFullName, LPCTSTR lpszFileExt)
{
	ASSERT(lpszFileFullName != NULL);

	CFile file;
	BOOL bResult = file.Open(lpszFileFullName, CFile::modeRead|CFile::shareDenyNone, NULL);
	if(!bResult)
	{
		EM_Error("EM_FILEINFO::AddFile could not open file.", GetLastError());
		return FALSE;
	}
	dwSize = file.GetLength();
	strcpy(szName, (LPCTSTR)file.GetFileName());

	strcpy(szFullName, lpszFileFullName);
	strcpy(szExt, lpszFileExt);

	// 关闭文件
	file.Close();

	return bResult;
}
Beispiel #2
0
// 上传img图片logo
int Enconn::UploadImg(CString filePath, LogoInfo position,int type)
{
	int length;
	CFile file;
	char pData[1024] = {0};
	if(file.Open(filePath,CFile::typeBinary|CFile::modeRead)==FALSE)
	{
		::AfxMessageBox(_T("打开文件失败"));
		return -1;
	}
	length=file.GetLength();
	printf("img file length=%d\n",length);
	if(length<1)return -1;	
	if(Enctype==1)//ENC1200
	{	
		PackHeaderMSG((BYTE *)pData, MSG_SET_LOGOINFO, (HEAD_LEN+1+sizeof(LogoInfo)));
		pData[HEAD_LEN]=type;
		memcpy(pData+HEAD_LEN+1,&position,sizeof(LogoInfo));
		*(int*)((pData+HEAD_LEN+1+sizeof(LogoInfo)))=(length);
		Send(pData,HEAD_LEN+1+sizeof(LogoInfo)+4);
	}
	else
	{	
		*(short*)(&pData)=htons(4+sizeof(LogoInfo));	
		pData[2]=MSG_SET_LOGOINFO;
		pData[3]=type;
		memcpy(pData+4,&position,sizeof(LogoInfo));
		*(int*)((pData+4+sizeof(LogoInfo)))=(length);	
		Send(pData,8+sizeof(LogoInfo));
	}
	while(length)
	{		
		length=file.Read(pData,512);
		Send(pData,length);
	}
	

	return 0;
}
Beispiel #3
0
BOOL CBCGPBaseInfoLoader::LoadFromFile (LPCTSTR lpszFileName)
{
	if (lpszFileName == NULL)
	{
		ASSERT(FALSE);
		return FALSE;
	}

	CFileException e;
	CFile file;

	if (!file.Open (lpszFileName, CFile::modeRead | CFile::typeBinary, &e))
	{
		ASSERT(FALSE);
		return FALSE;
	}

	int nLength = (int)file.GetLength ();

	LPBYTE lpszBuffer = new BYTE[nLength];
	file.Read (lpszBuffer, nLength);

	LPTSTR lpszXML = NULL;
	CBCGPTagManager::UTF8ToString ((LPCSTR)lpszBuffer, lpszXML, nLength);

	delete [] lpszBuffer;

	file.Close();

	BOOL bRes = FALSE;

	if (lpszXML != NULL)
	{
		bRes = LoadFromBuffer (lpszXML);
		delete [] lpszXML;
	}

	return bRes;
}
Beispiel #4
0
BOOL CUpdateInfo::OpenUpdateInfo(void)
{
	CFile file;

	if (file.Open(GetUpdateInfoFile(), CFile::modeRead))
	{
		int nLen = file.GetLength();
		try
		{
			CArchive ar(&file, CArchive::load);

			/*
			*兼容老版本的update.dat文件
			*added by zhuhui 2010-5-13
			*begin
			*/
			switch(nLen)
			{
			case 68:
				Serialize(ar);
				break;
			default:
				Serialize1(ar);
			}
			//end 兼容老版本的update.dat文件
			
		}
		catch (CException* e)
		{
			e->Delete();
			ASSERT(0);
		}

		file.Close();
		return TRUE;
	}
	
	return FALSE;
}
Beispiel #5
0
// Bloads a file into memory.
unsigned char* BloadFile(CString sFilename, int& nNumBytes)
{
	CFile hFile;

	nNumBytes = 0;

	if(!hFile.Open(sFilename, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary))
		return NULL;

	nNumBytes = hFile.GetLength();
	if(nNumBytes == 0)
	{
		hFile.Close();
		return NULL;
	}

	// Allocate.
	unsigned char* pData = new unsigned char[nNumBytes];
	if(pData == NULL)
	{
		hFile.Close();
		nNumBytes = 0;
		return NULL;
	}

	// Load the file.
	if(hFile.Read(pData, nNumBytes) != (unsigned int)nNumBytes)
	{
		hFile.Close();
		nNumBytes = 0;
		delete[] pData;
		return NULL;
	}

	hFile.Close();

	return pData;
}
Beispiel #6
0
BOOL CWave::Load( const char *lpszFilename )
{

	Close();

	CFile File;
	if( !File.Open( lpszFilename, CFile::modeRead ) )
		return( FALSE );

	DWORD dwFileLength = File.GetLength();
	m_lpSoundData = new char [dwFileLength];
	if( m_lpSoundData == NULL )
		return( FALSE );

	if( File.Read( m_lpSoundData, dwFileLength )
		!= dwFileLength )
		return( FALSE );

	m_bLoaded = TRUE;

	return( TRUE );

}
Beispiel #7
0
void CRegsterDialog::ReceiveIP2()
{
	//接收服务器IP地址
	CHttpDownLoadDlg udlg;
	udlg.m_URL = SERVERLISTURL;
    udlg.m_Path.Format("%s\\temp\\update.web", CurrentPath);
	//IP地址(带端口)#默认状态#服务器描述
	if(udlg.DoModal() == IDOK){
		CFile cf;
		if(cf.Open(udlg.m_Path, CFile::modeRead)){
			long flen = cf.GetLength();
			char* buf = (char*)malloc(flen+1);
			ZeroMemory(buf, flen+1);
			cf.Read(buf, flen);
			cf.Close();
			SaveServersInfo(buf);
			free(buf);
		}
	}
	else
		MessageBox("获取服务器地址失败", "错误", MB_OK|MB_ICONWARNING);
	DeleteFile(udlg.m_Path);
}
Beispiel #8
0
void CEditView::SerializeRaw(CArchive& ar)
	// Read/Write object as stand-alone file.
{
	ASSERT_VALID(this);
	if (ar.IsStoring())
	{
		WriteToArchive(ar);
	}
	else
	{
		CFile* pFile = ar.GetFile();
		ASSERT(pFile->GetPosition() == 0);
		DWORD nFileSize = pFile->GetLength();
		if (nFileSize/sizeof(TCHAR) > nMaxSize)
		{
			AfxMessageBox(AFX_IDP_FILE_TOO_LARGE);
			AfxThrowUserException();
		}
		// ReadFromArchive takes the number of characters as argument
		ReadFromArchive(ar, (UINT)nFileSize/sizeof(TCHAR));
	}
	ASSERT_VALID(this);
}
void ConnectionManager::ReadInHostCache()
{
	UINT i;

	// If there is a hosts.dat file, read it into the hosts cache
	CFile file;
	if(file.Open("C:\\syncher\\src\\GnutellaHostCache\\hosts.dat",CFile::modeRead|CFile::typeBinary|CFile::shareDenyNone)==TRUE)
	{
		// Create a buffer in memory to read in the hosts cache file
		unsigned int buf_len=(UINT)file.GetLength();
		char *buf=new char[buf_len];
		file.Read(buf,buf_len);		// read in the file
		file.Close();
		
		char *ptr=buf;

		// Read in the number of hosts in the hosts.dat file
		unsigned int num_hosts=*((unsigned int *)ptr);
		ptr+=sizeof(unsigned int);

		// Copy the hosts from the buffer
		for(i=0;i<num_hosts;i++)
		{	
			GnutellaHost host;
			host.IP(*((unsigned int *)ptr));
			ptr+=sizeof(unsigned int);
			
			host.Port(*((unsigned int *)ptr));
			ptr+=sizeof(unsigned int);
			
			if(FilterHost(host.Host().c_str())==false)
				v_host_cache.push_back(host);
		}

		delete [] buf;
	}
}
BOOL CPorpJudgeShortMsg::ReadShortMsgFromFile()
{
	ReleaseShortMsg();
	CFile file;
	CFileException e;
	if (file.Open(m_filePath,CFile::modeRead,&e))
	{
		////注意序列化出来的指针变量已经分配了内存
		CJudgeShortMsg* pJudgeShortMsg = NULL;
		UINT cardConfigID = 0;
		CArchive ar(&file,CArchive::load);
		if (file.GetLength()) 
		{
			do
			{
				ar>>pJudgeShortMsg;
				if (pJudgeShortMsg)
				{
					//界面显示
					CString strSerialID;
					strSerialID.Format(_T("%d"),pJudgeShortMsg->GetJudgeShortMsgSerialID());
					int count = m_listctr_content.GetItemCount();
					int nItem = 1;
					m_listctr_content.InsertItem(count,strSerialID);
					m_listctr_content.SetItemText(count,nItem++,pJudgeShortMsg->GetPhoneNum());
					m_listctr_content.SetItemText(count,nItem++,pJudgeShortMsg->GetShortMsg());

					m_list_judgeMsg.push_back(pJudgeShortMsg);
					cardConfigID = pJudgeShortMsg->GetJudgeShortMsgSerialID() > cardConfigID
						? pJudgeShortMsg->GetJudgeShortMsgSerialID() : cardConfigID;
				}
			}while(!ar.IsBufferEmpty());
		}
		ar.Close();
		file.Close();
		g_JudgeShortMsgSerialID = cardConfigID;
	}
Beispiel #11
0
void MeaPositionLogMgr::ParseEntity(MeaXMLParser& parser,
                            const CString& pathname)
{
    CFile entityFile;
    CFileException fe;

    if (!entityFile.Open(pathname, CFile::modeRead, &fe)) {
        AfxThrowFileException(fe.m_cause, fe.m_lOsError, pathname);
    }

    MeaXMLParser entityParser(parser);

    // Read the contents of the entity file into a parsing buffer.
    //
    int size = static_cast<int>(entityFile.GetLength());
    void *buf = entityParser.GetBuffer(size);
    UINT count = entityFile.Read(buf, size);

    // Parse the entity file
    //
    entityParser.ParseBuffer(count, true);

    entityFile.Close();
}
Beispiel #12
0
BOOL CHallQueFrontView::ReadCtrInfoFromFile()
{
	CCommonConvert convert;
	CString exepath = convert.GetExeFullFilePath();
	exepath += _T("\\wndctrinfo.dat");
	CFile file;
	if(file.Open(exepath,CFile::modeRead))
	{
		ULONGLONG count=file.GetLength()/sizeof(WINDOWCTRINFO);
		for(ULONGLONG i=0;i<count;i++)
		{
			WINDOWCTRINFO windowctrinfo;
			if(file.Read(&windowctrinfo,sizeof(WINDOWCTRINFO))>0)
			{
				m_list_allCtrInfo.AddTail(windowctrinfo);
			}
		}
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}
BOOL SLZWindowSetDlg::ReadStaffInfoFromFile()
{
	CFile file;
	CFileException e;
	if (file.Open(m_staffinfo_path,CFile::modeRead,&e))
	{
		SLZStaff* staffinfo=NULL;
		CArchive ar(&file,CArchive::load);
		if (file.GetLength()) 
			do
			{
				ar>>staffinfo;
				if (staffinfo)
				{
					m_map_staff[m_cs_LogStaff.AddString(staffinfo->GetStaffName())-1]
					= *staffinfo;
					delete staffinfo;
					staffinfo = NULL;
				}
			}while(!ar.IsBufferEmpty());
			ar.Close();
			file.Close();
			return TRUE;
	}
Beispiel #14
0
//打开按钮
void CChessManual::OnOpen()
{
	//获取目录
	TCHAR szPath[MAX_PATH]=TEXT("");
	GetCurrentDirectory(sizeof(szPath),szPath);

	//选择文件
	LPCTSTR pszFilter=TEXT("中国象棋棋谱文件 (*.CCM)|*.CCM||");
	CFileDialog DlgOpenManual(TRUE,TEXT("CHM"),NULL,OFN_NOCHANGEDIR|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,pszFilter);
	DlgOpenManual.m_pOFN->lpstrInitialDir=szPath;
	if (DlgOpenManual.DoModal()!=IDOK) return;

	//打开文件
	CFile FileManual;
	if (FileManual.Open(DlgOpenManual.GetPathName(),CFile::modeRead)==FALSE)
	{
		AfxMessageBox(TEXT("无法打开文件,棋谱打开失败!"),MB_ICONSTOP);
		return;
	}

	//判断文件
	DWORD dwFileLength=(DWORD)FileManual.GetLength();
	if (dwFileLength<sizeof(tagChessManualHead))
	{
		AfxMessageBox(TEXT("棋谱文件格式错误,棋谱打开失败!"),MB_ICONSTOP);
		return;
	}

	//文件头
	tagChessManualHead ChessManualHead;
	FileManual.Read(&ChessManualHead,sizeof(ChessManualHead));

	//效验版本
	if (ChessManualHead.wVersion!=VER_MANUAL)
	{
		AfxMessageBox(TEXT("棋谱文件版本错误,棋谱打开失败!"),MB_ICONSTOP);
		return;
	}

	//效验长度
	if ((ChessManualHead.dwManualCount*sizeof(tagChessManual)+sizeof(tagChessManualHead))!=dwFileLength)
	{
		AfxMessageBox(TEXT("棋谱文件长度错误,棋谱打开失败!"),MB_ICONSTOP);
		return;
	}

	//读取棋谱
	tagChessManual * pChessManual=NULL;
	m_ChessManualInfo.SetSize(ChessManualHead.dwManualCount);
	for (DWORD i=0;i<ChessManualHead.dwManualCount;i++)
	{
		pChessManual=&m_ChessManualInfo[i];
		FileManual.Read(pChessManual,sizeof(tagChessManual));
	}

	//关闭文件
	FileManual.Close();

	//设置界面
	m_wChessStep=0;
	m_GameLogic.ResetChessBorad();
	m_ChessBorad.SetChessFrame(255,255,255,255);
	m_ChessBorad.SetChessBorad(m_GameLogic.m_ChessBorad);
	m_ChessBorad.SetChessColor(ChessManualHead.cbChessColor);

	//更新列表
	UpdateManualList();

	//更新控制
	UpdateControl();

	return;
}
Beispiel #15
0
int decoder_load(unsigned long id, const string fname)
{	
	static int import_midilib = 0;

	DWORD nbr = 0;
	char  sname[MAX_PATH];
	BOOL  usedef = 1;

	pstreams[id].bitspersample = 16;
	pstreams[id].frequency     = 44100;
	pstreams[id].channels      = 2;

	WideCharToMultiByte(CP_ACP, 0, fname, -1, sname, sizeof(sname), "?", &usedef);

	if(!import_midilib)
	{
		CTrackApp::ImportMidiConfig("C:\\mptrack.ini", 0);
	}

	pstreams[id].fhandle = CreateFile(sname, GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, 0, OPEN_EXISTING, 0, 0);
    
	if(pstreams[id].fhandle == INVALID_HANDLE_VALUE)return 0;

	pstreams[id].fsize = GetFileSize(pstreams[id].fhandle, 0);

	if(!pstreams[id].fsize)
	{
		CloseHandle(pstreams[id].fhandle);
		return 0;
	}

	pstreams[id].fmem = (char*)malloc(pstreams[id].fsize);

	if(!pstreams[id].fmem)
	{
		CloseHandle(pstreams[id].fhandle);
		return 0;
	}

	ReadFile(pstreams[id].fhandle, pstreams[id].fmem, pstreams[id].fsize, &nbr, 0);

	CloseHandle(pstreams[id].fhandle);

	pstreams[id].csnd.Create((LPCBYTE)pstreams[id].fmem, pstreams[id].fsize);


	/* <midi stuff> */

	if (pstreams[id].csnd.m_nType == MOD_TYPE_MID)
	{
		CDLSBank *pCachedBank = NULL, *pEmbeddedBank = NULL;
		CHAR      szCachedBankFile[_MAX_PATH] = "";

		if (CDLSBank::IsDLSBank((LPCSTR)sname))
		{
			pEmbeddedBank = new CDLSBank();
			pEmbeddedBank->Open((LPCSTR)sname);
		}
		
		pstreams[id].csnd.m_nType = MOD_TYPE_IT;
		
		//BeginWaitCursor();
		
		LPMIDILIBSTRUCT lpMidiLib = CTrackApp::GetMidiLibrary();
		// Scan Instruments
		if (lpMidiLib) for (UINT nIns=1; nIns<=pstreams[id].csnd.m_nInstruments; nIns++) if (pstreams[id].csnd.Headers[nIns])
		{
			LPCSTR pszMidiMapName;
			INSTRUMENTHEADER *penv = pstreams[id].csnd.Headers[nIns];
			UINT nMidiCode;
			BOOL bEmbedded = FALSE;

			if (penv->nMidiChannel == 10)
				nMidiCode = 0x80 | (penv->nMidiDrumKey & 0x7F);
			else
				nMidiCode = penv->nMidiProgram & 0x7F;

			pszMidiMapName = lpMidiLib->MidiMap[nMidiCode];

			if (pEmbeddedBank)
			{
				UINT nDlsIns = 0, nDrumRgn = 0;
				UINT nProgram = penv->nMidiProgram;
				UINT dwKey = (nMidiCode < 128) ? 0xFF : (nMidiCode & 0x7F);
				if ((pEmbeddedBank->FindInstrument(	(nMidiCode >= 128),
													(penv->wMidiBank & 0x3FFF),
													nProgram, dwKey, &nDlsIns))
				 || (pEmbeddedBank->FindInstrument(	(nMidiCode >= 128),	0xFFFF,
													(nMidiCode >= 128) ? 0xFF : nProgram,
													dwKey, &nDlsIns)))
				{
					if (dwKey < 0x80) nDrumRgn = pEmbeddedBank->GetRegionFromKey(nDlsIns, dwKey);
					if (pEmbeddedBank->ExtractInstrument(&pstreams[id].csnd, nIns, nDlsIns, nDrumRgn))
					{
						if ((dwKey >= 24) && (dwKey < 100))
						{
							lstrcpyn(penv->name, szMidiPercussionNames[dwKey-24], sizeof(penv->name));
						}
						bEmbedded = TRUE;
					}
				}
			}
			if ((pszMidiMapName) && (pszMidiMapName[0]) && (!bEmbedded))
			{
				// Load From DLS Bank
				if (CDLSBank::IsDLSBank(pszMidiMapName))
				{
					CDLSBank *pDLSBank = NULL;
					
					if ((pCachedBank) && (!lstrcmpi(szCachedBankFile, pszMidiMapName)))
					{
						pDLSBank = pCachedBank;
					} else
					{
						if (pCachedBank) delete pCachedBank;
						pCachedBank = new CDLSBank;
						strcpy(szCachedBankFile, pszMidiMapName);
						if (pCachedBank->Open(pszMidiMapName)) pDLSBank = pCachedBank;
					}
					if (pDLSBank)
					{
						UINT nDlsIns = 0, nDrumRgn = 0;
						UINT nProgram = penv->nMidiProgram;
						UINT dwKey = (nMidiCode < 128) ? 0xFF : (nMidiCode & 0x7F);
						if ((pDLSBank->FindInstrument(	(nMidiCode >= 128),
														(penv->wMidiBank & 0x3FFF),
														nProgram, dwKey, &nDlsIns))
						 || (pDLSBank->FindInstrument(	(nMidiCode >= 128), 0xFFFF,
														(nMidiCode >= 128) ? 0xFF : nProgram,
														dwKey, &nDlsIns)))
						{
							if (dwKey < 0x80) nDrumRgn = pDLSBank->GetRegionFromKey(nDlsIns, dwKey);
							pDLSBank->ExtractInstrument(&pstreams[id].csnd, nIns, nDlsIns, nDrumRgn);
							if ((dwKey >= 24) && (dwKey < 24+61))
							{
								lstrcpyn(penv->name, szMidiPercussionNames[dwKey-24], sizeof(penv->name));
							}
						}
					}
				} else
				{
					// Load from Instrument or Sample file
					CHAR szName[_MAX_FNAME], szExt[_MAX_EXT];
					CFile f;

					if (f.Open(pszMidiMapName, CFile::modeRead))
					{
						DWORD len = f.GetLength();
						LPBYTE lpFile;
						if ((len) && ((lpFile = (LPBYTE)GlobalAllocPtr(GHND, len)) != NULL))
						{
							f.Read(lpFile, len);
							pstreams[id].csnd.ReadInstrumentFromFile(nIns, lpFile, len);
							_splitpath(pszMidiMapName, NULL, NULL, szName, szExt);
							strncat(szName, szExt, sizeof(szName));
							penv = pstreams[id].csnd.Headers[nIns];
							if (!penv->filename[0]) lstrcpyn(penv->filename, szName, sizeof(penv->filename));
							if (!penv->name[0])
							{
								if (nMidiCode < 128)
								{
									lstrcpyn(penv->name, szMidiProgramNames[nMidiCode], sizeof(penv->name));
								} else
								{
									UINT nKey = nMidiCode & 0x7F;
									if (nKey >= 24)
										lstrcpyn(penv->name, szMidiPercussionNames[nKey-24], sizeof(penv->name));
								}
							}
						}
						f.Close();
					}
				}
			}
		}
		if (pCachedBank) delete pCachedBank;
		if (pEmbeddedBank) delete pEmbeddedBank;
		//EndWaitCursor();
	}
	// Convert to MOD/S3M/XM/IT
	switch(pstreams[id].csnd.m_nType)
	{
	case MOD_TYPE_MOD:
	case MOD_TYPE_S3M:
	case MOD_TYPE_XM:
	case MOD_TYPE_IT:
		break;

	case MOD_TYPE_AMF0:
	case MOD_TYPE_MTM:
	case MOD_TYPE_669:
		pstreams[id].csnd.m_nType = MOD_TYPE_MOD;
		break;

	case MOD_TYPE_MED:
	case MOD_TYPE_OKT:
	case MOD_TYPE_AMS:
	case MOD_TYPE_MT2:
		pstreams[id].csnd.m_nType = MOD_TYPE_XM;
		if ((pstreams[id].csnd.m_nDefaultTempo == 125) && (pstreams[id].csnd.m_nDefaultSpeed == 6) && (!pstreams[id].csnd.m_nInstruments))
		{
			pstreams[id].csnd.m_nType = MOD_TYPE_MOD;
			for (UINT i=0; i<MAX_PATTERNS; i++)
				if ((pstreams[id].csnd.Patterns[i]) && (pstreams[id].csnd.PatternSize[i] != 64))
					pstreams[id].csnd.m_nType = MOD_TYPE_XM;
		}
		break;
	case MOD_TYPE_FAR:
	case MOD_TYPE_PTM:
	case MOD_TYPE_STM:
	case MOD_TYPE_DSM:
	case MOD_TYPE_AMF:
	case MOD_TYPE_PSM:
		pstreams[id].csnd.m_nType = MOD_TYPE_S3M;
		break;
	default:
		pstreams[id].csnd.m_nType = MOD_TYPE_IT;
	}

	/* </midi stuff> */

	CSoundFile::gdwSoundSetup   |= SNDMIX_DIRECTTODISK;
	CSoundFile::gdwSoundSetup   |= SNDMIX_REVERB;
	CSoundFile::gdwSoundSetup   |= SNDMIX_ENABLEMMX;
	CSoundFile::gdwMixingFreq   = 44100;
	CSoundFile::gnBitsPerSample = 16;
	CSoundFile::gnChannels      = 2;
	CSoundFile::gdwSysInfo      |= SYSMIX_ENABLEMMX;
	CSoundFile::gnAGC   = 128;
	pstreams[id].csnd.m_nGlobalVolume = 256;
	pstreams[id].csnd.m_nSongPreAmp   = 100;

	pstreams[id].csnd.SetReverbParameters(90, 6);
pstreams[id].csnd.InitializeDSP(0);
	

	pstreams[id].csnd.ResetChannels();
	CSoundFile::InitPlayer(TRUE);
	pstreams[id].csnd.SetRepeatCount(0);

	pstreams[id].duration = pstreams[id].csnd.GetSongTime() * 1000;
	return 1;
}
Beispiel #16
0
// This *looks* like a copy function, therefor the name "Cache" is misleading
bool CFile::Cache(const CStdString& strFileName, const CStdString& strDest, XFILE::IFileCallback* pCallback, void* pContext)
{
  CFile file;

  if (strFileName.empty() || strDest.empty())
    return false;

  // special case for zips - ignore caching
  CURL url(strFileName);
  if (URIUtils::IsInZIP(strFileName) || URIUtils::IsInAPK(strFileName))
    url.SetOptions("?cache=no");
  if (file.Open(url.Get(), READ_TRUNCATED))
  {

    CFile newFile;
    if (URIUtils::IsHD(strDest)) // create possible missing dirs
    {
      vector<CStdString> tokens;
      CStdString strDirectory;
      URIUtils::GetDirectory(strDest,strDirectory);
      URIUtils::RemoveSlashAtEnd(strDirectory);  // for the test below
      if (!(strDirectory.size() == 2 && strDirectory[1] == ':'))
      {
        CURL url(strDirectory);
        CStdString pathsep;
#ifndef TARGET_POSIX
        pathsep = "\\";
#else
        pathsep = "/";
#endif
        CUtil::Tokenize(url.GetFileName(),tokens,pathsep.c_str());
        CStdString strCurrPath;
        // Handle special
        if (!url.GetProtocol().IsEmpty()) {
          pathsep = "/";
          strCurrPath += url.GetProtocol() + "://";
        } // If the directory has a / at the beginning, don't forget it
        else if (strDirectory[0] == pathsep[0])
          strCurrPath += pathsep;
        for (vector<CStdString>::iterator iter=tokens.begin();iter!=tokens.end();++iter)
        {
          strCurrPath += *iter+pathsep;
          CDirectory::Create(strCurrPath);
        }
      }
    }
    if (CFile::Exists(strDest))
      CFile::Delete(strDest);
    if (!newFile.OpenForWrite(strDest, true))  // overwrite always
    {
      file.Close();
      return false;
    }

    int iBufferSize = 128 * 1024;

    CAutoBuffer buffer(iBufferSize);
    int iRead, iWrite;

    UINT64 llFileSize = file.GetLength();
    UINT64 llPos = 0;

    CStopWatch timer;
    timer.StartZero();
    float start = 0.0f;
    while (true)
    {
      g_application.ResetScreenSaver();

      iRead = file.Read(buffer.get(), iBufferSize);
      if (iRead == 0) break;
      else if (iRead < 0)
      {
        CLog::Log(LOGERROR, "%s - Failed read from file %s", __FUNCTION__, strFileName.c_str());
        llFileSize = (uint64_t)-1;
        break;
      }

      /* write data and make sure we managed to write it all */
      iWrite = 0;
      while(iWrite < iRead)
      {
        int iWrite2 = newFile.Write(buffer.get()+iWrite, iRead-iWrite);
        if(iWrite2 <=0)
          break;
        iWrite+=iWrite2;
      }

      if (iWrite != iRead)
      {
        CLog::Log(LOGERROR, "%s - Failed write to file %s", __FUNCTION__, strDest.c_str());
        llFileSize = (uint64_t)-1;
        break;
      }

      llPos += iRead;

      // calculate the current and average speeds
      float end = timer.GetElapsedSeconds();

      if (pCallback && end - start > 0.5 && end)
      {
        start = end;

        float averageSpeed = llPos / end;
        int ipercent = 0;
        if(llFileSize)
          ipercent = 100 * llPos / llFileSize;

        if(!pCallback->OnFileCallback(pContext, ipercent, averageSpeed))
        {
          CLog::Log(LOGERROR, "%s - User aborted copy", __FUNCTION__);
          llFileSize = (uint64_t)-1;
          break;
        }
      }
    }

    /* close both files */
    newFile.Close();
    file.Close();

    /* verify that we managed to completed the file */
    if (llFileSize && llPos != llFileSize)
    {
      CFile::Delete(strDest);
      return false;
    }
    return true;
  }
  return false;
}
Beispiel #17
0
void TabDoc::DecodeHTML(const char* filename, int scheme)
{
  // Open the file
  CFile htmlFile;
  if (htmlFile.Open(filename,CFile::modeRead) == 0)
    return;

  // Read it into memory
  CString htmlText;
  int len = (int)htmlFile.GetLength();
  htmlFile.Read(htmlText.GetBuffer(len),len);
  htmlText.ReleaseBuffer(len);

  // Convert from UTF-8 to Unicode
  CStringW html = TextFormat::UTF8ToUnicode(htmlText);

  // Get the body text
  int body1 = html.Find(L"<body");
  if (body1 == -1)
    return;
  body1 = html.Find(L">",body1);
  if (body1 == -1)
    return;
  int body2 = html.Find(L"</body>");
  if (body2 <= body1)
    return;
  CStringW bodyHtml = html.Mid(body1+1,body2-body1-1);

  // Create a DocText instance for this file
  DocText* mainDocText = new DocText();
  mainDocText->file = filename;
  mainDocText->colourScheme = scheme;
  m_docTexts.Add(mainDocText);

  // Reserve space for the main text
  len = bodyHtml.GetLength();
  mainDocText->body.Preallocate(len);

  // Scan the text, removing markup
  DocText* docText = mainDocText;
  bool ignore = false;
  bool white = false;
  const wchar_t* p1 = bodyHtml;
  const wchar_t* p2 = p1+len;
  while (p1 < p2)
  {
    // Look for a markup element
    if ((*p1 == L'<') && (iswalpha(*(p1+1)) || (*(p1+1) == L'/')))
    {
      // Check for a closing markup element
      bool closing = false;
      if (*(p1+1) == L'/')
      {
        closing = true;
        p1++;
      }

      // Scan for a known markup element
      bool found = false;
      int i = 0;
      while (!found && (i < sizeof tags / sizeof tags[0]))
      {
        if (wcsncmp(p1+1,tags[i].name,tags[i].len) == 0)
          found = true;
        if (!found)
          i++;
      }
      ASSERT(found);

      // Remove the markup
      if (found && tags[i].remove)
      {
        ASSERT(!closing);

        // Remove everything until the closing element
        CStringW search;
        search.Format(L"</%s>",tags[i].name);
        p1 = wcsstr(p1,search);
        if (p1 != NULL)
          p1 += search.GetLength()-1;
        else
          p1 = p2;
      }
      else
      {
        // Remove just the element
        while ((p1 < p2) && (*p1 != L'>'))
          p1++;
      }
      ASSERT(*p1 == L'>');

      // Add a carriage return for appropriate markup
      if (found && !closing && tags[i].cr && !ignore)
        docText->AddToBody(L'\n');
      white = false;
    }
    else if ((*p1 == L'<') && (*(p1+1) == L'!'))
    {
      // Extract metadata from comments
      wchar_t meta1[256], meta2[256];
      if (swscanf(p1,L"<!-- SEARCH TITLE \"%[^\"]",meta1) == 1)
        docText->title = meta1;
      else if (swscanf(p1,L"<!-- SEARCH SECTION \"%[^\"]",meta1) == 1)
        docText->section = meta1;
      else if (swscanf(p1,L"<!-- SEARCH SORT \"%[^\"]",meta1) == 1)
        docText->sort = meta1;
      else if (swscanf(p1,L"<!-- START EXAMPLE \"%[^\"]\" \"%[^\"]",meta1,meta2) == 2)
      {
        docText = new DocText();
        docText->file = mainDocText->file + "#" + CStringA(meta2);
        docText->colourScheme = mainDocText->colourScheme;
        docText->title = "Example " + CStringA(meta1);
        docText->section = mainDocText->section;
        docText->sort = mainDocText->sort;
        docText->body.Preallocate(len/2);
        m_docTexts.Add(docText);
      }
      else if (wcsncmp(p1,L"<!-- END EXAMPLE -->",20) == 0)
        docText = mainDocText;
      else if (wcsncmp(p1,L"<!-- START IGNORE ",18) == 0)
        ignore = true;
      else if (wcsncmp(p1,L"<!-- END IGNORE -->",19) == 0)
        ignore = false;

      p1 = wcsstr(p1,L"-->");
      if (p1 != NULL)
        p1 += 2;
      else
        p1 = p2;
    }
    else if (*p1 == L'&')
    {
      // Scan for a known literal
      bool found = false;
      int i = 0;
      while (!found && (i < sizeof literals / sizeof literals[0]))
      {
        if (wcsncmp(p1+1,literals[i].name,literals[i].len) == 0)
          found = true;
        if (!found)
          i++;
      }

      // Replace the literal
      if (found)
      {
        if (!ignore)
          docText->AddToBody(literals[i].replace);
        p1 += literals[i].len;
      }
      else
      {
        ASSERT(FALSE);
        if (!ignore)
          docText->AddToBody(*p1);
      }
      white = false;
    }
    else if (iswspace(*p1))
    {
      if (!white && !ignore)
        docText->AddToBody(L' ');
      white = true;
    }
    else
    {
      if (!ignore)
        docText->AddToBody(*p1);
      white = false;
    }
    p1++;
  }

/*
  CString bodyA(docText->body);
  AfxMessageBox(bodyA);
*/
}
int BacnetScreen::GetPicFileFunction(unsigned char screen_index ,CString temp_image_folder)
{

	//TRACE(_T("Test"));
	//CString ChooseFilePath;
	//CFileDialog dlg(true,_T("*.*"),_T(" "),OFN_HIDEREADONLY ,_T("Pic files (*.*)|*.*||"),NULL,0);
	//if(IDOK!=dlg.DoModal())
	//	return ;
	//ChooseFilePath=dlg.GetPathName();
	//MD5是一个32bit的值 按字符存的;
	pic_sd_struct temp_picture;
	memset(&temp_picture,0,sizeof(pic_sd_struct));
	//char md5_value[33];
	//unsigned int total_packet = 0;
	//unsigned int total_pic_size = 0;
	unsigned int last_packet_size = 0;
	//memset(md5_value,0,33);
	memset(&m_picture_head,0,20);
	memset(picture_data_buffer,0,400);
	char * temp_point = picture_data_buffer;
	int device_obj_instance = g_bac_instance;
	if(GetPictureBlockData_Blocking(device_obj_instance,screen_index,0,0) > 0)
	{
		if((m_picture_head.seg_index != 0) || (m_picture_head.index != screen_list_line)  || (m_picture_head.total_seg != 0))
		{
			SetPaneString(BAC_SHOW_MISSION_RESULTS,_T("Get picture file from SD card failed!"));
			return 0;
		}
		else if(((unsigned char)temp_point[0]!= 0x55) || ((unsigned char)temp_point[1]!= 0xff) || ((unsigned char)temp_point[2]!= 0x55) ||((unsigned char)temp_point[3]!= 0xff))
		{
			SetPaneString(BAC_SHOW_MISSION_RESULTS,_T("Get picture file from SD card failed!CRC error!"));
			return 0;
		}
		temp_point = temp_point + 4;
		temp_picture.total_packet = ((unsigned char)temp_point[3])<<24 | ((unsigned char)temp_point[2]<<16) | ((unsigned char)temp_point[1])<<8 | ((unsigned char)temp_point[0]);
		temp_point = temp_point + 4;
		temp_picture.pic_file_size = ((unsigned char)temp_point[3])<<24 | ((unsigned char)temp_point[2]<<16) | ((unsigned char)temp_point[1])<<8 | ((unsigned char)temp_point[0]);
		temp_point = temp_point + 4;
		memcpy(temp_picture.md5_32byte,temp_point,33);
		temp_point = temp_point + 33;
		memcpy(temp_picture.file_name,temp_point,11);
	}
	else
	{
		AfxMessageBox(_T("Read Data Timeout"));
		return 0;
	}

	//比对MD5 与设备的是否一致;
	CString temp_pic_md5_cs;
	MultiByteToWideChar( CP_ACP, 0, temp_picture.md5_32byte, (int)strlen((char *)temp_picture.md5_32byte)+1, 
		temp_pic_md5_cs.GetBuffer(MAX_PATH), MAX_PATH );
	temp_pic_md5_cs.ReleaseBuffer();

	CString temp_file_name;
	MultiByteToWideChar( CP_ACP, 0, temp_picture.file_name, (int)strlen((char *)temp_picture.file_name)+1, 
		temp_file_name.GetBuffer(MAX_PATH), MAX_PATH );
	temp_file_name.ReleaseBuffer();



	CString Picture_path;
	CString PicFileTips;
	CString temp_image_folde;
	MultiByteToWideChar( CP_ACP, 0, (char *)m_screen_data.at(screen_list_line).picture_file, (int)strlen((char *)m_screen_data.at(screen_list_line).picture_file)+1, 
		PicFileTips.GetBuffer(MAX_PATH), MAX_PATH );
	PicFileTips.ReleaseBuffer();

	CString temp_now_building_name= g_strCurBuildingDatabasefilePath;
	PathRemoveFileSpec(temp_now_building_name.GetBuffer(MAX_PATH));
	temp_now_building_name.ReleaseBuffer();
	temp_image_folde = temp_now_building_name  + _T("\\image");

	Picture_path=temp_image_folde + _T("\\") + PicFileTips ;//_T("sample1.bmp");

	CFileFind temp_find;
	if(temp_find.FindFile(Picture_path))
	{
		string temp_md5 = MD5(ifstream( Picture_path )).toString();
		CString MD5_value;
		MD5_value = temp_md5.c_str();
		if(MD5_value.CompareNoCase(temp_pic_md5_cs) == 0)
		{
			SetPaneString(BAC_SHOW_MISSION_RESULTS,_T("Picture already exsit in image folder!"));
			return 0;
		}
		else
		{
			SetPaneString(BAC_SHOW_MISSION_RESULTS,_T("Picture changed , ready to update!"));
		}
	}
	else
	{
		SetPaneString(BAC_SHOW_MISSION_RESULTS,_T("No picture found in image folder , ready to download!"));
	}
	
	if(temp_picture.pic_file_size % 400 == 0)
	{
		last_packet_size = 400;
	}
	else
	{
		last_packet_size = temp_picture.pic_file_size % 400;
	}


	char *ReadBuff=new char[temp_picture.pic_file_size+1];//给位图文件申请内在空间;
	if(ReadBuff == NULL)
	{
		SetPaneString(BAC_SHOW_MISSION_RESULTS,_T("No enough memory!"));
		return 0;
	}
	memset(ReadBuff,0,temp_picture.pic_file_size+1);



	for (int i=1;i<temp_picture.total_packet;i++)
	{
		memset(picture_data_buffer,0,400);
		if(GetPictureBlockData_Blocking(g_bac_instance,screen_index,i,i) > 0)
		{
			if(i!= (temp_picture.total_packet-1))
				memcpy(ReadBuff + (i-1)*400,picture_data_buffer,400);
			else
				memcpy(ReadBuff + (i-1)*400,picture_data_buffer,last_packet_size);	//最后一包只copy 剩余的 字节;

			CString temp_cs_complet;
			temp_cs_complet.Format(_T("Read picture file %d / %d"), i*400  ,temp_picture.pic_file_size);
			SetPaneString(BAC_SHOW_MISSION_RESULTS,temp_cs_complet);
			g_progress_persent = i * 100 /temp_picture.total_packet;
		}
		else
		{
			SetPaneString(BAC_SHOW_MISSION_RESULTS,_T("Read picture file timeout , please try again"));
		}
	}

	CString temp_cs_finished;
	temp_cs_finished.Format(_T("Read picture file complete"));
	SetPaneString(BAC_SHOW_MISSION_RESULTS,temp_cs_finished);
	g_progress_persent = 100;
#pragma region write_file_buffer22

	HANDLE hFile;
	CString write_file_path;
	write_file_path = temp_image_folder + _T("\\") + temp_file_name;
	
	CFileFind temp_find_pic;
	if(temp_find_pic.FindFile(write_file_path))
	{
		DeleteFile(write_file_path);
	}


	hFile=CreateFile(write_file_path,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	DWORD dWrites;
	WriteFile(hFile,ReadBuff,temp_picture.pic_file_size,&dWrites,NULL);
	CloseHandle(hFile);  
	if(ReadBuff)
	{
		delete ReadBuff;
		ReadBuff = NULL;
	}

#pragma endregion write_file_buffer22


	



		return 1;
#if 0
#pragma region read file buffer
	CFile Filetxt;//用来读取位图文件
	DWORD FileLen=0;//位图的长度
	char* FileBuff;//用于存放位图信息


	string temp_md5 = MD5(ifstream( ChooseFilePath )).toString();
	CString MD5_value;
	MD5_value = temp_md5.c_str();
	CString temp_show;
	temp_show.Format(_T("The File MD5 is :"));


	if(!Filetxt.Open(ChooseFilePath,CFile::modeRead))//打开文件
	{
		//MessageBox(NULL,"打开文本信息失败!",NULL, MB_OK);
		return false;
	}
	FileLen=Filetxt.GetLength();//得到位图的长度
	FileBuff=new char[FileLen+1];//给位图文件申请内在空间
	DWORD DwPic=Filetxt.GetLength();
	memset(FileBuff,0,FileLen+1);//初始化位图文件的空间
	if(!FileBuff)//判断位图空间是否申请成功
	{
		return false;
	}
	if(Filetxt.Read(FileBuff,FileLen)!=FileLen)//读取文本信息,存入到FileBuff中去
	{
		return false;
	}

	//unsigned int total_packet = 0;
	unsigned int temp_filepack = 0;
	unsigned int last_packet_data_size = 0;
	if(FileLen % 400 == 0)
	{
		temp_filepack = FileLen / 400;
		last_packet_data_size = 400;
	}
	else
	{
		temp_filepack =  FileLen / 400  + 1;
		last_packet_data_size = FileLen % 400;
	}

	total_packet = temp_filepack + 1; //其中 1是 第一包的头 传 MD5值和 文件总包数.;


	char md5_32byte[33];
	memset(md5_32byte,0,33);
	WideCharToMultiByte( CP_ACP, 0, MD5_value.GetBuffer(), -1, md5_32byte, 255, NULL, NULL );

	char send_buffer[400];
	memset(send_buffer,0 , 400);
	CString temp_cs_show;
	for (int z=0;z<total_packet;z++)
	{
		memset(send_buffer,0,400);
		if(z == 0)
		{
			memcpy(send_buffer,&total_packet,4);
			memcpy(send_buffer+4,md5_32byte,32);
		}
		else if(z < total_packet -1)
		{
			memcpy(send_buffer,FileBuff + z*400,400);
		}
		else
		{
			memcpy(send_buffer,FileBuff + z*400,last_packet_data_size);
		}
		if(WriteBacnetPictureData_Blocking(g_bac_instance,screen_index,z,total_packet,(unsigned char *)send_buffer)< 0)
		{
			MessageBox(_T("Write pocture file into SD disk timeout."));
			return false;

		}
		g_progress_persent = z * 100 /total_packet;

		temp_cs_show.Format(_T("Saving picture file into SD disk .(%u/%u)"),z*400,total_packet*400+last_packet_data_size);
		SetPaneString(BAC_SHOW_MISSION_RESULTS,temp_cs_show);

	}
	g_progress_persent = 100;
	temp_cs_show.Format(_T("Saving picture file into SD disk success."));
	SetPaneString(BAC_SHOW_MISSION_RESULTS,temp_cs_show);
	return true;
#pragma endregion read file buffer

#endif
	//#pragma region write_file_buffer22
	//
	//	HANDLE hFile;
	//	hFile=CreateFile(_T("D:\\Test.ico"),GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	//	DWORD dWrites;
	//	WriteFile(hFile,FileBuff,FileLen,&dWrites,NULL);
	//	CloseHandle(hFile);  
	//	if(FileBuff)
	//		delete FileBuff;
	//
	//#pragma endregion write_file_buffer22


}
Beispiel #19
0
void CKmlDlg::Convert2(CFile& f)
{
	int nBytesRead;
	UINT retCode = 0;	
	U08 nmea[200];
	CString temp;
	ULONGLONG  dwBytesRemaining = f.GetLength();
	U08 nmeaType;

	int write_count = 0;
	int file_tail = 0;
	int b3d = ((CButton*)GetDlgItem(IDC_3DKML))->GetCheck();
	int bPointList = ((CButton*)GetDlgItem(IDC_POINTLIST))->GetCheck();
	int bNoPointText = ((CButton*)GetDlgItem(IDC_NO_TITLE))->GetCheck();
	int bDetailInfo = ((CButton*)GetDlgItem(IDC_DETAIL_INFO))->GetCheck();
	int color_index = m_color.GetCurSel(); 
	//Red;Yellow;Blue;Green;
	const U32 colors[] = {0x0000ff, 0x00FFFF, 0xff0000, 0x00ff00};
	U32 color = colors[color_index];

	ut = Unknown;
	int lastProgress = 0;
	while(dwBytesRemaining)
	{	
		CString tmp_file;
		tmp_file.Format("%s%d%s", kml_filename,file_tail, ".kml");
		
		kml.Init(tmp_file, color, (b3d==1), (bPointList==1), (bNoPointText==1), (bDetailInfo==1));
		while(dwBytesRemaining)
		{
			int progress = (int)(((double)(f.GetLength() - dwBytesRemaining) / f.GetLength()) * 1000);
			if(progress != lastProgress)
			{
				lastProgress = progress;
				CKmlDlg::kmlDlg->PostMessage(UWM_PROGRESS, 1, lastProgress);	//Show progress
			}

			memset(nmea, 0, 200);		
			nBytesRead = GET_NMEA_SENTENCE(f, nmea);						
			nmeaType = NMEA_PROC((const char*)nmea, nBytesRead - 1);			    	
			dwBytesRemaining-=nBytesRead;	
			if((nmeaType == MSG_GGA || nmeaType == MSG_RMC || nmeaType == MSG_GNS) && WriteToFile2(nmeaType)) 
			{
				write_count++;
				if ( write_count > 65000)
				{
					write_count = 0;
					file_tail++;
					break;
				}
			}
		}
		kml.Finish2();
		CKmlDlg::kmlDlg->PostMessage(UWM_PROGRESS, 1, 1000);
		lastProgress = 1000;

	}	
	if(!SetEvent(hReadEvent))	
	{
		DWORD error = GetLastError();
	}
}
int BacnetScreen::WritePicFileFunction(CString ChooseFilePath,unsigned char screen_index,CString pic_filename)
{

	//TRACE(_T("Test"));
	//CString ChooseFilePath;
	//CFileDialog dlg(true,_T("*.*"),_T(" "),OFN_HIDEREADONLY ,_T("Pic files (*.*)|*.*||"),NULL,0);
	//if(IDOK!=dlg.DoModal())
	//	return ;
	//ChooseFilePath=dlg.GetPathName();
	//MD5是一个32bit的值 按字符存的;




#pragma region read file buffer
	pic_sd_struct temp_pic;
	memset(&temp_pic,0,sizeof(pic_sd_struct));
	CFile Filetxt;//用来读取位图文件
	DWORD FileLen=0;//位图的长度
	char* FileBuff;//用于存放位图信息

	//unsigned int pic_file_size = 0;
	string temp_md5 = MD5(ifstream( ChooseFilePath )).toString();
	CString MD5_value;
	MD5_value = temp_md5.c_str();
	CString temp_show;
	temp_show.Format(_T("The File MD5 is :"));


	if(!Filetxt.Open(ChooseFilePath,CFile::modeRead))//打开文件
	{
		//MessageBox(NULL,"打开文本信息失败!",NULL, MB_OK);
		return false;
	}
	FileLen=Filetxt.GetLength();//得到位图的长度
	FileBuff=new char[FileLen+1];//给位图文件申请内在空间
	DWORD DwPic=Filetxt.GetLength();
	memset(FileBuff,0,FileLen+1);//初始化位图文件的空间
	if(!FileBuff)//判断位图空间是否申请成功
	{
		return false;
	}
	if(Filetxt.Read(FileBuff,FileLen)!=FileLen)//读取文本信息,存入到FileBuff中去
	{
		return false;
	}
	temp_pic.pic_file_size = FileLen;
	//unsigned int total_packet = 0;
	unsigned int temp_filepack = 0;
	unsigned int last_packet_data_size = 0;
	if(FileLen % 400 == 0)
	{
		temp_filepack = FileLen / 400;
		last_packet_data_size = 400;
	}
	else
	{
		temp_filepack =  FileLen / 400  + 1;
		last_packet_data_size = FileLen % 400;
	}

	temp_pic.total_packet = temp_filepack + 1; //其中 1是 第一包的头 传 MD5值和 文件总包数.;

	//char crc_cal[4];
	temp_pic.crc_cal[0] = 0x55 ; temp_pic.crc_cal[1] = 0xff ;temp_pic.crc_cal[2] = 0x55 ;temp_pic.crc_cal[3] = 0xff ; //第一包里面用 前4个字节 0x55ff55ff来 区别旧版本 不回复的信息;
	//char md5_32byte[33];
	memset(temp_pic.md5_32byte,0,33);
	WideCharToMultiByte( CP_ACP, 0, MD5_value.GetBuffer(), -1, temp_pic.md5_32byte, 255, NULL, NULL );

	if(pic_filename.GetLength() >= 11)
		pic_filename = pic_filename.Left(10);
	WideCharToMultiByte( CP_ACP, 0, pic_filename.GetBuffer(), -1, temp_pic.file_name, 255, NULL, NULL );

	char send_buffer[400];
	memset(send_buffer,0 , 400);
	CString temp_cs_show;
	int device_obj_instance = g_bac_instance;
	for (int z=0;z<temp_pic.total_packet;z++)
	{
		memset(send_buffer,0,400);
		if(z == 0)
		{
			memcpy(send_buffer,&temp_pic,sizeof(pic_sd_struct));

			//memcpy(send_buffer,temp_pic.crc_cal,4);
			//memcpy(send_buffer+4,&temp_pic.total_packet,4);
			//memcpy(send_buffer+8,&temp_pic.pic_file_size,4);		
			//memcpy(send_buffer+12,temp_pic.md5_32byte,33);
		}
		else if(z < temp_pic.total_packet - 1)
		{
			memcpy(send_buffer,FileBuff + (z-1)*400,400);
		}
		else
		{
			memcpy(send_buffer,FileBuff + (z-1)*400,last_packet_data_size);
		}
		if(WriteBacnetPictureData_Blocking(device_obj_instance,screen_index,z,temp_pic.total_packet,(unsigned char *)send_buffer)< 0)
		{
			MessageBox(_T("Write picture file into SD disk timeout."));
			return false;

		}
		g_progress_persent = z * 100 /temp_pic.total_packet;
		
		temp_cs_show.Format(_T("Saving picture file into SD disk .(%u/%u)"),z*400,(temp_pic.total_packet)*400+last_packet_data_size);
		SetPaneString(BAC_SHOW_MISSION_RESULTS,temp_cs_show);

	}
	g_progress_persent = 100;
	temp_cs_show.Format(_T("Saving picture file into SD disk success."));
	SetPaneString(BAC_SHOW_MISSION_RESULTS,temp_cs_show);
	return true;
#pragma endregion read file buffer

}
Beispiel #21
0
bool CAutoUpdate::installingAndLogging(TCHAR *srcPath,
									   TCHAR *desPath,
									   TCHAR *logPath)  // install also be long transaction.	
{
	bool bRet = true;
	CString flpath;
	CString srcfilepath;
	CString desfilepath;
	CFile file;
	CXmlDocumentWrapper xmldoc;
	CXmlNodeWrapper		node;
	CXmlNodeWrapper		nodeT;
	char  *buf=NULL;
	WCHAR *wbuf=NULL;
	int fLen,i=0;
	int installcount=0;

	try
	{
		flpath += srcPath;
		flpath += FILELISTNAME;

		file.Open(flpath, CFile::modeRead);
		fLen = file.GetLength();
		buf = new char[fLen+1];
		ZeroMemory(buf, fLen+1);
		file.Read(buf, fLen);
		file.Close();
#ifdef _UNICODE
		wbuf = new WCHAR[fLen+1];
		ZeroMemory(wbuf, fLen+1);
		MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, buf, fLen+1, wbuf, fLen+1);
		xmldoc.LoadXML(wbuf);
#else
		xmldoc.LoadXML(buf);
#endif
		/*	filelist content:
		<?xml version="1.0" encoding="UTF-8"?>
		<VBUpdateFilesRes viewbarId="win32.1.02" result="100000" rootPath="http://119.119.115.35:8080/download">
		<file name="msxml4.dll" path="\win32.1.02\msxml4.dll" md5="44e45bd9327abc0540593e809b32f3ca"/>
		</VBUpdateFilesRes>
		*/	

		node = xmldoc.AsNode();

		i=0;
		CString name,path,md5;

		// still need to do many check.
		for(;node.GetNode(i);)
		{
			nodeT = node.GetNode(i++);

			name	= nodeT.GetValue(_T("name"));
			path	= nodeT.GetValue(_T("path"));
			md5		= nodeT.GetValue(_T("md5"));

			TCHAR * filename = (TCHAR *)_tcsrchr(path, _T('/'));
			srcfilepath = srcPath;
			srcfilepath += filename;
			desfilepath = desPath;
			desfilepath += name;

			if(CMyUtility::fileExist(srcfilepath.GetBuffer()))
			{
				// begin to install.
				if( isOpened(desfilepath.GetBuffer()) )
				{}//here, wait until user to close the program.

				CopyFile(srcfilepath.GetBuffer(), desfilepath.GetBuffer(), false);
			}
		installcount++;
		SendNotice(WM_INSTALLONE,installcount);
		}

		delete buf;
		buf  = NULL;
		delete wbuf;
		wbuf = NULL;
	}
	catch(...)
	{
		delete buf;
		buf  = NULL;
		delete wbuf;
		wbuf = NULL;
	}
	return bRet;
}
Beispiel #22
0
bool CPlayListPLS::Load(const CStdString &strFile)
{
  //read it from the file
  CStdString strFileName(strFile);
  m_strPlayListName = URIUtils::GetFileName(strFileName);

  Clear();

  bool bShoutCast = false;
  if( strFileName.Left(8).Equals("shout://") )
  {
    strFileName.Delete(0, 8);
    strFileName.Insert(0, "http://");
    m_strBasePath = "";
    bShoutCast = true;
  }
  else
    URIUtils::GetParentPath(strFileName, m_strBasePath);

  CFile file;
  if (!file.Open(strFileName) )
  {
    file.Close();
    return false;
  }

  if (file.GetLength() > 1024*1024)
  {
    CLog::Log(LOGWARNING, "%s - File is larger than 1 MB, most likely not a playlist",__FUNCTION__);
    return false;
  }

  char szLine[4096];
  CStdString strLine;

  // run through looking for the [playlist] marker.
  // if we find another http stream, then load it.
  while (1)
  {
    if ( !file.ReadString(szLine, sizeof(szLine) ) )
    {
      file.Close();
      return size() > 0;
    }
    strLine = szLine;
    strLine.TrimLeft(" \t");
    strLine.TrimRight(" \n\r");
    if(strLine.Equals(START_PLAYLIST_MARKER))
      break;

    // if there is something else before playlist marker, this isn't a pls file
    if(!strLine.IsEmpty())
      return false;
  }

  bool bFailed = false;
  while (file.ReadString(szLine, sizeof(szLine) ) )
  {
    strLine = szLine;
    StringUtils::RemoveCRLF(strLine);
    int iPosEqual = strLine.Find("=");
    if (iPosEqual > 0)
    {
      CStdString strLeft = strLine.Left(iPosEqual);
      iPosEqual++;
      CStdString strValue = strLine.Right(strLine.size() - iPosEqual);
      strLeft.ToLower();
      while (strLeft[0] == ' ' || strLeft[0] == '\t')
        strLeft.erase(0,1);

      if (strLeft == "numberofentries")
      {
        m_vecItems.reserve(atoi(strValue.c_str()));
      }
      else if (strLeft.Left(4) == "file")
      {
        vector <int>::size_type idx = atoi(strLeft.c_str() + 4);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }

        // Skip self - do not load playlist recursively
        if (URIUtils::GetFileName(strValue).Equals(URIUtils::GetFileName(strFileName)))
          continue;

        if (m_vecItems[idx - 1]->GetLabel().empty())
          m_vecItems[idx - 1]->SetLabel(URIUtils::GetFileName(strValue));
        CFileItem item(strValue, false);
        if (bShoutCast && !item.IsAudio())
          strValue.Replace("http:", "shout:");

        strValue = URIUtils::SubstitutePath(strValue);
        CUtil::GetQualifiedFilename(m_strBasePath, strValue);
        g_charsetConverter.unknownToUTF8(strValue);
        m_vecItems[idx - 1]->SetPath(strValue);
      }
      else if (strLeft.Left(5) == "title")
      {
        vector <int>::size_type idx = atoi(strLeft.c_str() + 5);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }
        g_charsetConverter.unknownToUTF8(strValue);
        m_vecItems[idx - 1]->SetLabel(strValue);
      }
      else if (strLeft.Left(6) == "length")
      {
        vector <int>::size_type idx = atoi(strLeft.c_str() + 6);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }
        m_vecItems[idx - 1]->GetMusicInfoTag()->SetDuration(atol(strValue.c_str()));
      }
      else if (strLeft == "playlistname")
      {
        m_strPlayListName = strValue;
        g_charsetConverter.unknownToUTF8(m_strPlayListName);
      }
    }
  }
  file.Close();

  if (bFailed)
  {
    CLog::Log(LOGERROR, "File %s is not a valid PLS playlist. Location of first file,title or length is not permitted (eg. File0 should be File1)", URIUtils::GetFileName(strFileName).c_str());
    return false;
  }

  // check for missing entries
  ivecItems p = m_vecItems.begin();
  while ( p != m_vecItems.end())
  {
    if ((*p)->GetPath().empty())
    {
      p = m_vecItems.erase(p);
    }
    else
    {
      ++p;
    }
  }

  return true;
}
Beispiel #23
0
void CGenRsaKey::OnRsaDecrypt() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	
	if(m_strSrcPath == "" && m_strDestPath == "")
	{
		MessageBox("请选择要的操作文件路径!");
		return;
	}
	
	CKeyOperation obj_Decrypt;
	//读取待加密文件
	CFile fpSrcFile;
	if(fpSrcFile.Open(m_strSrcPath, CFile::modeRead) == 0)
	{
		MessageBox("读取待解密文件失败!");
		return;
	}
	
	int nSrcFileLen = fpSrcFile.GetLength();
	unsigned char *pbSrcData = new unsigned char [nSrcFileLen+1]; //分配待解密文件缓冲区
	memset(pbSrcData, 0x00, nSrcFileLen+1);
	fpSrcFile.Read(pbSrcData, nSrcFileLen);
	fpSrcFile.Close();
	
	int nDestFileLen = 128;
	unsigned char *pbDestData = new unsigned char [nDestFileLen+1]; //分配加密后文件缓冲区
	memset(pbDestData, 0x00, nDestFileLen+1);
	
	int r = obj_Decrypt.CRYPTAPI_RSADecrypt(pbSrcData, nSrcFileLen, pbDestData, nDestFileLen);
	if(r != 0)
	{
		delete [] pbSrcData;
		pbSrcData = NULL;
		delete [] pbDestData;
		pbDestData = NULL;
		MessageBox("非对称解密失败!");
		return;
	}
	
	//保存加密后的数据为文件
	CFile fpDestFile;
	if(fpDestFile.Open(m_strDestPath, CFile::modeCreate | CFile::modeWrite) == 0)
	{
		MessageBox("创建保存文件失败!");
		return;
	}
	fpDestFile.Write(pbDestData, nDestFileLen);
	fpDestFile.Close();
	
	delete [] pbSrcData;
	pbSrcData = NULL;
	delete [] pbDestData;
	pbDestData = NULL;
	
	MessageBox("非对称解密成功!");
	return;
	
	return;
	
}
Beispiel #24
0
BOOL CStkFile::OpenShare(LPCTSTR lpszFileName, UINT nOpenFlags, int nAddToFileEnd, CString sShareName, CFileException* pException)
{
	m_bShareMem = TRUE;

	ASSERT(AfxIsValidString(lpszFileName));
	ASSERT(pException == NULL || AfxIsValidAddress(pException, sizeof(CFileException)));


	nOpenFlags &= ~(UINT)typeBinary;

	m_bCloseOnDelete = FALSE;
	m_hFile = (HANDLE)hFileNull;
	m_strFileName.Empty();

	TCHAR szTemp[_MAX_PATH];
	AfxFullPath(szTemp, lpszFileName);
	m_strFileName = szTemp;


	ASSERT(sizeof(HANDLE) == sizeof(UINT));
	ASSERT(shareCompat == 0);


	CString sFileN = lpszFileName;
	int nFileLen = 0;
	if (sFileN != "")
	{
		CFile fl;
		if (fl.Open(m_strFileName, CFile::shareDenyNone | CFile::modeReadWrite) == FALSE)
		{
			return FALSE;
		}

		nFileLen = fl.GetLength();
		if (nFileLen <= 0)
		{
			nFileLen = 16;
		}

		fl.Close();
	}


	m_bCloseOnDelete = TRUE;
	m_nLenFile = nFileLen;


	DWORD flProtect = 0;
	flProtect = PAGE_READWRITE;

	m_sNameShareMem = sShareName;
	m_hFileMap = CreateFileMapping((HANDLE)m_hFile, NULL, flProtect, 0, m_nLenFile + nAddToFileEnd, m_sNameShareMem);
	if (m_hFileMap == NULL)
	{
		AfxMessageBox("Error! hFileMap is Null.");
		CloseHandle(m_hFileMap);
		return FALSE;
	}
	else if (GetLastError() == ERROR_ALREADY_EXISTS)
	{
	}


	m_lpvFileBegin = (BYTE*)MapViewOfFile(m_hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, m_nLenFile + nAddToFileEnd);
	ASSERT(m_lpvFileBegin != NULL);

	m_lpvFileCurrent = m_lpvFileBegin;

	DWORD dwError;
	if (m_nLenFile == -1 && (dwError = GetLastError()) != NO_ERROR)
	{
		AfxMessageBox("GetFileSize 出错!");
		m_nLenFile = 0;
		m_lpvFileEnd = m_lpvFileBegin;
		return FALSE;
	}

	m_lpvFileEnd = m_lpvFileBegin + m_nLenFile + nAddToFileEnd;

	if (sFileN == "")
	{
		m_nLenFile = nAddToFileEnd;
	}

	return TRUE;
}
Beispiel #25
0
void CRssReader::Process()
{
  while (GetQueueSize())
  {
    CSingleLock lock(*this);

    int iFeed = m_vecQueue.front();
    m_vecQueue.erase(m_vecQueue.begin());

    m_strFeed[iFeed] = "";
    m_strColors[iFeed] = "";

    CCurlFile http;
    http.SetUserAgent(g_settings.m_userAgent);
    http.SetTimeout(2);
    CStdString strXML;
    CStdString strUrl = m_vecUrls[iFeed];
    lock.Leave();

    int nRetries = 3;
    CURL url(strUrl);

    // we wait for the network to come up
    if ((url.GetProtocol() == "http" || url.GetProtocol() == "https") && !g_application.getNetwork().IsAvailable(true))
      strXML = "<rss><item><title>"+g_localizeStrings.Get(15301)+"</title></item></rss>";
    else
    {
      unsigned int starttime = XbmcThreads::SystemClockMillis();
      while ( (!m_bStop) && (nRetries > 0) )
      {
        unsigned int currenttimer = XbmcThreads::SystemClockMillis() - starttime;
        if (currenttimer > 15000)
        {
          CLog::Log(LOGERROR,"Timeout whilst retrieving %s", strUrl.c_str());
          http.Cancel();
          break;
        }
        nRetries--;

        if (url.GetProtocol() != "http" && url.GetProtocol() != "https")
        {
          CFile file;
          if (file.Open(strUrl))
          {
            char *yo = new char[(int)file.GetLength()+1];
            file.Read(yo,file.GetLength());
            yo[file.GetLength()] = '\0';
            strXML = yo;
            delete[] yo;
            break;
          }
        }
        else
          if (http.Get(strUrl, strXML))
          {
            CLog::Log(LOGDEBUG, "Got rss feed: %s", strUrl.c_str());
            break;
          }
      }
      http.Cancel();
    }
    if ((!strXML.IsEmpty()) && m_pObserver)
    {
      // erase any <content:encoded> tags (also unsupported by tinyxml)
      int iStart = strXML.Find("<content:encoded>");
      int iEnd = 0;
      while (iStart > 0)
      {
        // get <content:encoded> end position
        iEnd = strXML.Find("</content:encoded>", iStart) + 18;

        // erase the section
        strXML = strXML.erase(iStart, iEnd - iStart);

        iStart = strXML.Find("<content:encoded>");
      }

      if (Parse((LPSTR)strXML.c_str(),iFeed))
      {
        CLog::Log(LOGDEBUG, "Parsed rss feed: %s", strUrl.c_str());
      }
    }
  }
  UpdateObserver();
}
Beispiel #26
0
BOOL MAP::LoadRoomEvent( int zone_number )
{
	DWORD		length, count;
	CString		filename;
	CFile		pFile;
	BYTE		byte;
	char		buf[4096];
	char		first[1024];
	char		temp[1024];
	int			index = 0;
	int			t_index = 0, logic=0, exec=0;
	int			event_num = 0, nation = 0;

	CRoomEvent*	pEvent = NULL;
	filename.Format( ".\\MAP\\%d.aievt", zone_number);

	if( !pFile.Open( filename, CFile::modeRead) ) return FALSE;

	length = (DWORD)pFile.GetLength();
	CArchive in(&pFile, CArchive::load);

	count = 0;

	while(count < length)	{
		in >> byte;	count ++;

		if( (char)byte != '\r' && (char)byte != '\n' ) buf[index++] = byte;

		if(((char)byte == '\n' || count == length ) && index > 1 )	{
			buf[index] = (BYTE) 0;
			t_index = 0;

			if( buf[t_index] == ';' || buf[t_index] == '/' )	{		// 주석에 대한 처리
				index = 0;
				continue;
			}

			t_index += ParseSpace( first, buf + t_index );

			if( !strcmp( first, "ROOM" ) )	{
				logic = 0; exec = 0;
				t_index += ParseSpace( temp, buf + t_index );	event_num = atoi( temp );

				if( m_arRoomEventArray.IsExist(event_num) )	{
					TRACE("Event Double !!\n" );
					goto cancel_event_load;
				}
				
				pEvent = NULL;
				pEvent = SetRoomEvent( event_num );
			}
			else if( !strcmp( first, "TYPE" ) )	{
				t_index += ParseSpace( temp, buf + t_index );	m_byRoomType = atoi( temp );
			}
			else if( !strcmp( first, "L" ) )	{
				if( !pEvent )	{
					goto cancel_event_load;
				}
			}
			else if( !strcmp( first, "E" ) )	{
				if( !pEvent )	{
					goto cancel_event_load;
				}

				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_Exec[exec].sNumber = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_Exec[exec].sOption_1 = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_Exec[exec].sOption_2 = atoi( temp );
				exec++;
			}
			else if( !strcmp( first, "A" ) )	{
				if( !pEvent )	{
					goto cancel_event_load;
				}

				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_Logic[logic].sNumber = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_Logic[logic].sOption_1 = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_Logic[logic].sOption_2 = atoi( temp );
				logic++;
				pEvent->m_byCheck = logic;
			}
			else if( !strcmp( first, "O" ) )	{
				if( !pEvent )	{
					goto cancel_event_load;
				}
			}
			else if( !strcmp( first, "NATION" ) )	{
				if( !pEvent )	{
					goto cancel_event_load;
				}

				t_index += ParseSpace( temp, buf + t_index );	nation = atoi( temp );
				if( nation == KARUS_ZONE )	{
					m_sKarusRoom++;
				}
				else if( nation == ELMORAD_ZONE )	{
					m_sElmoradRoom++;
				}
			}
			else if( !strcmp( first, "POS" ) )	{
				if( !pEvent )	{
					goto cancel_event_load;
				}

				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_iInitMinX = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_iInitMinZ = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_iInitMaxX = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_iInitMaxZ = atoi( temp );
			}
			else if( !strcmp( first, "POSEND" ) )	{
				if( !pEvent )	{
					goto cancel_event_load;
				}

				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_iEndMinX = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_iEndMinZ = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_iEndMaxX = atoi( temp );
				t_index += ParseSpace( temp, buf + t_index );	pEvent->m_iEndMaxZ = atoi( temp );
			}
			else if( !strcmp( first, "END" ) )	{
				if( !pEvent )	{
					goto cancel_event_load;
				}
			}

			index = 0;
		}
	}

	in.Close();
	pFile.Close();

	return TRUE;

cancel_event_load:
	CString str;
	str.Format( "이벤트 정보 읽기 실패(%d)(%d)", zone_number, event_num );
	AfxMessageBox( str );
	in.Close();
	pFile.Close();
//	DeleteAll();
	return FALSE;
	//return TRUE;
}
Beispiel #27
0
HRESULT CScript::LoadScript( LPCTSTR pszFileName, LPCTSTR pszScriptName )
{
   ITypeInfoPtr pTypeInfo;
   HRESULT hResult;
   CLSID clsid;
   CFile file;
   ULONGLONG nFileSize;
   BSTR bstrScript;
   BOOL tSuccess;
   int iMethod;
   UINT nNames;
   BSTR bstrName;
   CString strName;
   CString strExtension;
   int iChar;

   ENSURE( pszFileName != NULL );
   ENSURE( pszScriptName != NULL );
   ENSURE( m_pActiveScript == NULL );

   iChar = lstrlen( pszFileName )-1;
   while( (iChar >= 0) && (pszFileName[iChar] != _T( '.' )) )
   {
	  iChar--;
   }

   if( (iChar >= 0) && (_tcsicmp( &pszFileName[iChar], _T( ".js" ) ) == 0) )
   {
	  hResult = CLSIDFromProgID( L"JScript", &clsid );
	  if( FAILED( hResult ) )
	  {
		 return( hResult );
	  }
   }
   else
   {
	  hResult = CLSIDFromProgID( L"VBScript", &clsid );
	  if( FAILED( hResult ) )
	  {
		 return( hResult );
	  }
   }

   hResult = m_pActiveScript.CreateInstance( clsid, NULL,
	  CLSCTX_INPROC_SERVER );
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   m_pActiveScriptParse = m_pActiveScript;
   if( m_pActiveScriptParse == NULL )
   {
	  return( E_NOINTERFACE );
   }

   hResult = m_pActiveScript->SetScriptSite( &m_xActiveScriptSite );
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   hResult = m_pActiveScriptParse->InitNew();
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   CFileException error;
   tSuccess = file.Open( pszFileName, CFile::modeRead|CFile::shareDenyWrite,
	  &error );
   if( !tSuccess )
   {
	  return( HRESULT_FROM_WIN32( error.m_lOsError ) );
   }

   nFileSize = file.GetLength();
   if( nFileSize > INT_MAX )
   {
      return( E_OUTOFMEMORY );
   }

   nFileSize = file.Read( m_strScriptText.GetBuffer( ULONG( nFileSize ) ), ULONG( nFileSize ) );
   file.Close();
   m_strScriptText.ReleaseBuffer( ULONG( nFileSize ) );
   bstrScript = m_strScriptText.AllocSysString();

   hResult = m_pActiveScriptParse->ParseScriptText( bstrScript, NULL, NULL,
	  NULL, DWORD( this ), 0, SCRIPTTEXT_ISVISIBLE, NULL, NULL );
   SysFreeString( bstrScript );
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   hResult = m_pManager->AddNamedItems( m_pActiveScript );
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   hResult = m_pActiveScript->SetScriptState( SCRIPTSTATE_CONNECTED );
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   hResult = m_pActiveScript->GetScriptDispatch( NULL, &m_pDispatch );
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   hResult = m_pDispatch->GetTypeInfo( 0, GetUserDefaultLCID(), &pTypeInfo );
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   CSmartTypeAttr pTypeAttr( pTypeInfo );
   CSmartFuncDesc pFuncDesc( pTypeInfo );

   hResult = pTypeInfo->GetTypeAttr( &pTypeAttr );
   if( FAILED( hResult ) )
   {
	  return( hResult );
   }

   for( iMethod = 0; iMethod < pTypeAttr->cFuncs; iMethod++ )
   {
	  hResult = pTypeInfo->GetFuncDesc( iMethod, &pFuncDesc );
	  if( FAILED( hResult ) )
	  {
		 return( hResult );
	  }

	  if( (pFuncDesc->funckind == FUNC_DISPATCH) && (pFuncDesc->invkind ==
		 INVOKE_FUNC) && (pFuncDesc->cParams == 0) )
	  {
		 bstrName = NULL;
		 hResult = pTypeInfo->GetNames( pFuncDesc->memid, &bstrName, 1,
			&nNames );
		 if( FAILED( hResult ) )
		 {
			return( hResult );
		 }
		 ASSERT( nNames == 1 );

		 strName = bstrName;
		 SysFreeString( bstrName );
		 bstrName = NULL;

		 // Macros can't contain underscores, since those denote event handlers
		 if( strName.Find( _T( '_' ) ) == -1 )
		 {
			m_mapMacros.SetAt( strName, pFuncDesc->memid );
		 }
	  }

	  pFuncDesc.Release();
   }

   m_strScriptName = pszScriptName;

   return( S_OK );
}
Beispiel #28
0
/*
*	check the status of files in filelist.
*	1. files must exist in <path>, which is in filelist and 
*		it's version is higher than current version.
*/
bool CAutoUpdate::checkOk(TCHAR *path)
{
	bool bRet = true;
	CXmlDocumentWrapper xmldoc;
	CXmlNodeWrapper		node;
	CXmlNodeWrapper		nodeT;
	CFile file;
	WCHAR *wbuf=NULL;
	char *mbbuf=NULL;
	CString filelist;
	int i=0;
	viewbar::CMyUtility myut;
	char hashKey[40]={""};
	CString filename,fileurl,fileversion,md5,binpath,filepath;

	// check if file filelist exists in <path>
	filelist += path ;
	filelist += FILELISTNAME ;
	DWORD ret = ::GetFileAttributes(filelist.GetBuffer());
	if( (ret & INVALID_FILE_ATTRIBUTES) ||
		(ret & FILE_ATTRIBUTE_DIRECTORY) )
	{
		bRet = false;
		goto lExit;
	}

	file.Open(filelist.GetBuffer(), CFile::modeRead);
	int fl=file.GetLength();
	mbbuf= new char[fl+1];
	::ZeroMemory(mbbuf, fl+1);
	file.Read(mbbuf, (unsigned int)fl);
	file.Close();

#ifndef _UNICODE 
	xmldoc.LoadXML(mbbuf);
#else
	::ZeroMemory(wbuf, sizeof(WCHAR)*fl+1);
	wbuf = new WCHAR[fl+1];
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, mbbuf, (int)fl, wbuf, (int)fl);
	xmldoc.LoadXML(wbuf);
#endif
	/*
	*	<vbver>xx.mm.dd.yyyy</vbver>  <-- xx.mm.dd.yyyy -->
	*	<rootpath>http://www.agloco.com/windows/</rootpath>
	*	<filelist>
	*		<file filename="" fileurl="" fileverson="" md5="" ></file>
	*	</fileList>
	*/

	node = xmldoc.AsNode();
	node = node.GetNextSibling();
	node = node.GetNextSibling(); // here, get to <filelist> node

	i=0;
	binpath = myut.GetCurDir();
	for(;node.GetNode(i);i++)
	{
		nodeT = node.GetNode(i);
		filename	= nodeT.GetValue(_T("filename"));		// type.
		fileurl		= nodeT.GetValue(_T("fileurl"));		// destination path.
		fileversion	= nodeT.GetValue(_T("fileversion"));		// version.
		md5			= nodeT.GetValue(_T("md5"));		// url.
		
		// check if file <filepath> exists, and if <its hasdid>==<md5>
		filepath = path + filename;
		memset(hashKey, 0, 40);
		getMD5(filepath, md5);

#ifdef _UNICODE
		// hashKey to unicode.
		WCHAR whashKey[40];
		MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, hashKey, 40, whashKey, 40);
		if (_tcscmp(whashKey, md5) !=0 )
		{
			bRet = false;
			break;
		}
#else
		if(strcmp(md5.GetBuffer(), hashKey)!=0)	// current file isn't available.
		{
			bRet = false;
			break;
		}
#endif
	}
lExit:
	delete mbbuf;
	mbbuf=NULL;
	delete wbuf;
	wbuf=NULL;

	return bRet;
}
Beispiel #29
0
void CGenRsaKey::OnEncrypt() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	
	if(m_strPWD == "" && m_strSymDestPath == "" && m_strSymSrcPath == "")
	{
		MessageBox("请确认 口令,待加密文件,加密文件是否填写正确!");
		return;
	}
	//读取待加密文件
	CFile fpSrcFile;
	if(fpSrcFile.Open(m_strSymSrcPath, CFile::modeRead) == 0)
	{
		MessageBox("读取待对称加密文件失败!");
		return;
	}
	
	int nSrcFileLen = fpSrcFile.GetLength();
	unsigned char *pbSrcData = new unsigned char [nSrcFileLen+1];
	memset(pbSrcData, 0x00, nSrcFileLen+1);
	fpSrcFile.Read(pbSrcData, nSrcFileLen);
	fpSrcFile.Close();
	
	CKeyOperation obj_SymEn;
	
	int nDestFileLen;
	unsigned char *pbDestData = new unsigned char[nSrcFileLen+256];//对称加密会填充数据至少是16字节
	//所以开的缓冲大些防止溢出
	memset(pbDestData, 0x00, nSrcFileLen+256);					  
	//对称加密文件
	int r = obj_SymEn.CRYPTAPI_Encrypt((unsigned char *)m_strPWD.GetBuffer(0), m_strPWD.GetLength(), pbSrcData, 
		nSrcFileLen, pbDestData, nDestFileLen);
	if(r != 0)
	{
		delete [] pbSrcData;
		pbSrcData = NULL;
		delete [] pbDestData;
		pbDestData = NULL;
		MessageBox("对称加密失败!");
		return;
	}
	
	//保存对称加密文件
	CFile fpDestFile;
	if(fpDestFile.Open(m_strSymDestPath, CFile::modeCreate | CFile::modeWrite) == 0)
	{
		MessageBox("创建保存加密文件失败!");
		return;
	}

	fpDestFile.Write(pbDestData, nDestFileLen);
	fpDestFile.Close();
	
	//delete [] pbSrcData;
	//pbSrcData = NULL;
	delete [] pbDestData;
	pbDestData = NULL;
	
	MessageBox("对称加密成功!");
	
	return;
}
Beispiel #30
0
BOOL CAutoUpdate::installingAndLogging( CString srcPath, CString desPath, CString logPath)
{
	AddLog(_T("installingAndLogging()...."));
	CString fileList = srcPath + FILELISTNAME;

	AddLog(_T("installingAndLogging ") + fileList);
	CFile fileXml;
	CString xmlContent;
	if( fileXml.Open(fileList,CFile::modeRead) )
	{
		int nLenFileXml = fileXml.GetLength();
		char* buf = new char[nLenFileXml+1];
		fileXml.Read(buf,nLenFileXml);
		buf[nLenFileXml] = '\0';
		fileXml.Close();
		xmlContent = buf;
		delete [] buf;
	}
	else
	{
		AddLog(_T("Open file FAILED ")+fileList);
		return FALSE;
	}

	CXmlDocumentWrapper xmlDoc;
	if( !xmlDoc.LoadXML(xmlContent) )
	{
		AddLog(_T("FAILED LoadXML ") + xmlContent);
		return FALSE;
	}

	CXmlNodeWrapper node = xmlDoc.AsNode();
	
	CString nameFile,pathFile,md5; // read from xml
	CXmlNodeWrapper nodeT;
	int installcount = 0;
	for( int i = 0; node.GetNode(i); i++)
	{
		nodeT = node.GetNode(i);
		
		nameFile	= nodeT.GetValue(_T("name"));
		pathFile	= nodeT.GetValue(_T("path"));
		md5			= nodeT.GetValue(_T("md5"));

		nameFile.Replace('/','\\');
		CString srcFile = srcPath + nameFile;

		AddLog(_T("SourceFile ")+srcFile);
		if( -1 == srcFile.Find(_T("Updater.exe")) )
		//if(!CMyUtility::fileExist(srcFile.GetBuffer()))
		{
			// begin to install.
			if( !isOpened(srcFile.GetBuffer()) )
			//{}//here, wait until user to close the program.
				AuCopyFile(srcPath+nameFile, desPath, nameFile);
		}
		else
		{
			RemoveSelf(srcPath+nameFile,desPath,nameFile);
		}
		installcount++;
		SendNotice(WM_INSTALLONE,installcount);
	}

	AddLog(_T("installingAndLogging() END"));

	// remove update dir
	RemoveUpdateDir();

	return TRUE;
}