Exemple #1
0
int CCDDARipJob::RipChunk(CFile& reader, CEncoder* encoder, int& percent)
{
  percent = 0;

  uint8_t stream[1024];

  // get data
  int result = reader.Read(stream, 1024);

  // return if rip is done or on some kind of error
  if (!result)
    return 1;

  // encode data
  int encres=encoder->Encode(result, stream);

  // Get progress indication
  percent = static_cast<int>(reader.GetPosition()*100/reader.GetLength());

  if (reader.GetPosition() == reader.GetLength())
    return 2;

  return -(1-encres);
}
Exemple #2
0
void CSystemTimer::LoadData(CFile & file)
{
    uint32_t TimerDetailsSize, Entries;

    file.Read(&TimerDetailsSize, sizeof(TimerDetailsSize));
    file.Read(&Entries, sizeof(Entries));

    if (TimerDetailsSize != sizeof(TIMER_DETAILS))
    {
        g_Notify->BreakPoint(__FILE__, __LINE__);
        return;
    }
    if (Entries != sizeof(m_TimerDetatils) / sizeof(m_TimerDetatils[0]))
    {
        g_Notify->BreakPoint(__FILE__, __LINE__);
        return;
    }

    file.Read((void *)&m_TimerDetatils, sizeof(m_TimerDetatils));
    file.Read((void *)&m_LastUpdate, sizeof(m_LastUpdate));
    file.Read(&m_NextTimer, sizeof(m_NextTimer));
    file.Read((void *)&m_Current, sizeof(m_Current));
}
Exemple #3
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;
	
}
Exemple #4
0
BOOL CModbusS::LoadFromFile(CString strFile)
{
	CFile f;
	CString strBuf,str;
	try
	{
		if(!f.Open(strFile,CFile::modeRead))
			return FALSE;
		CHAR buffer[4096];
		DWORD dwRead=0;
		// Read in 4096-byte blocks,
		// remember how many bytes were actually read,
		// and try to write that many out. This loop ends
		// when there are no more bytes to read.
		do
		{
			dwRead = f.Read(buffer, 4096);
			if(dwRead > 0)
			{
				int nLen = strBuf.GetLength();
				strBuf+=buffer;
				strBuf.Truncate(nLen+dwRead);
			}
		}
		while (dwRead > 0);
		f.Close();
		//AfxMessageBox(strBuf);
		strBuf.MakeUpper();
		strBuf.Remove(';');
		int nIndex = 0;
		int nProcIndex = -1;
		do
		{
			nIndex = strBuf.Find("\n");
			str = strBuf.Left(nIndex+1);
			if(str.Find("PORT") != -1)
			{
				str.TrimLeft("PORT");
				str.Trim();str.Trim("=");				
				PORT = atoi(str);
			}
			if(str.Find("BAUDRATE") != -1)
			{
				str.TrimLeft("BAUDRATE");
				str.Trim();str.Trim("=");
				BAUDRATE = atoi(str);
			}
			if(str.Find("STOPBITS") != -1)
			{
				str.TrimLeft("STOPBITS");
				str.Trim();str.Trim("=");
				STOPBITS = atoi(str);
			}
			if(str.Find("PARITY") != -1)
			{
				str.TrimLeft("PARITY");
				str.Trim();str.Trim("=");
				PARITY = atoi(str);
			}
			if(str.Find("BYTETIME") != -1)
			{
				str.TrimLeft("BYTETIME");
				str.Trim();str.Trim("=");
				BYTETIME = atoi(str);
			}
			if(str.Find("WAITRESP") != -1)
			{
				str.TrimLeft("WAITRESP");
				str.Trim();str.Trim("=");
				WAITRESP = atoi(str);
			}
			if(str.Find("ADRESS_KP") != -1)
			{
				str.TrimLeft("ADRESS_KP");
				str.Trim();str.Trim("=");
				ADRESS_KP = atoi(str);
			}
			if(str.Find("NEXTMESSAGE") != -1)
			{
				str.TrimLeft("NEXTMESSAGE");
				str.Trim();str.Trim("=");
				NEXTMESSAGE = atoi(str);
			}
			if(str.Find("NUMBER_OF_PRIBOR") != -1)
			{
				str.TrimLeft("NUMBER_OF_PRIBOR");
				str.Trim();str.Trim("=");
				NUMBER_OF_PRIBOR = atoi(str);
			}
			if(str.Find("NUMBER_NO_ANSWER") != -1)
			{
				str.TrimLeft("NUMBER_NO_ANSWER");
				str.Trim();str.Trim("=");
				NUMBER_NO_ANSWER = atoi(str);
			}
			if(str.Find("AMOUNTBYTE") != -1)
			{
				str.TrimLeft("AMOUNTBYTE");
				str.Trim();str.Trim("=");
				AMOUNTBYTE = atoi(str);
			}
			if(str.Find("CONTROLPOTOK") != -1)
			{
				str.TrimLeft("CONTROLPOTOK");
				str.Trim();str.Trim("=");
				CONTROLPOTOK = atoi(str);
			}			
			if(str.Find("MODBUS_TYPE") != -1)
			{
				str.TrimLeft("MODBUS_TYPE");
				str.Trim();str.Trim("=");
				MODBUS_TYPE = atoi(str);
			}		
			if(str.Find("START_ADDRESS_TS") != -1)
			{
				str.TrimLeft("START_ADDRESS_TS");
				str.Trim();str.Trim("=");
				START_ADDRESS_TS = atoi(str);
			}	
			if(str.Find("SIZE_TS") != -1)
			{
				str.TrimLeft("SIZE_TS");
				str.Trim();str.Trim("=");
				SIZE_TS = atoi(str);
			}
			if(str.Find("ADDRESS_ALARM_TS") != -1)
			{
				str.TrimLeft("ADDRESS_ALARM_TS");
				str.Trim();str.Trim("=");
				ADDRESS_ALARM_TS = atoi(str);
			}
			if(str.Find("START_ADDRESS_TI") != -1)
			{
				str.TrimLeft("START_ADDRESS_TI");
				str.Trim();str.Trim("=");
				START_ADDRESS_TI = atoi(str);
			}
			if(str.Find("SIZE_TI") != -1)
			{
				str.TrimLeft("SIZE_TI");
				str.Trim();str.Trim("=");
				SIZE_TI = atoi(str);
			}
			if(str.Find("ADDRESS_ALARM_TI") != -1)
			{
				str.TrimLeft("ADDRESS_ALARM_TI");
				str.Trim();str.Trim("=");
				ADDRESS_ALARM_TI = atoi(str);
			}	
			if(m_nVersion > 10)
			{
				if(str.Find("NUM_CALCULATE") != -1)
				{
					str.TrimLeft("NUM_CALCULATE");
					str.Trim();str.Trim("=");
					m_CalcStructureModbusSArray.SetSize(atoi(str));
				}								
				if(str.Find("NUMBER_CALCULATE") != -1)
				{
					str.TrimLeft("NUMBER_CALCULATE");
					str.Trim();str.Trim("=");
					if((atoi(str) > 0)&&(atoi(str) <= m_CalcStructureModbusSArray.GetSize()))				
						nProcIndex = atoi(str)-1;								
				}
				if((str.Find("TYPE") != -1)&&(str.Find("MODBUS_TYPE") == -1))
				{
					str.TrimLeft("TYPE");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].TYPE = atoi(str);										
				}
				if(str.Find("ADDRESS_FROM") != -1)
				{
					str.TrimLeft("ADDRESS_FROM");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].ADDRESS_FROM = atoi(str);										
				}
				if((str.Find("POSITION_BYTE") != -1)&&(str.Find("POSITION_BYTE_TOO") == -1))
				{
					str.TrimLeft("POSITION_BYTE");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].POSITION_BYTE = atoi(str);										
				}
				if((str.Find("POSITION_BIT") != -1)&&(str.Find("POSITION_BIT_TOO") == -1))
				{
					str.TrimLeft("POSITION_BIT");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].POSITION_BIT = atoi(str);										
				}
				if(str.Find("NUMBER_BYTE") != -1)
				{
					str.TrimLeft("NUMBER_BYTE");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].NUMBER_BYTE = atoi(str);										
				}
				if(str.Find("ADDRESS_TOO") != -1)
				{
					str.TrimLeft("ADDRESS_TOO");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].ADDRESS_TOO = atoi(str);										
				}
				if(str.Find("POSITION_BYTE_TOO") != -1)
				{
					str.TrimLeft("POSITION_BYTE_TOO");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].POSITION_BYTE_TOO = atoi(str);										
				}
				if(str.Find("POSITION_BIT_TOO") != -1)
				{
					str.TrimLeft("POSITION_BIT_TOO");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].POSITION_BIT_TOO = atoi(str);										
				}
				if(str.Find("DOPKODE_YES_NO") != -1)
				{
					str.TrimLeft("DOPKODE_YES_NO");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].DOPKODE_YES_NO = atoi(str);										
				}
				if(str.Find("CENA_SHKALI") != -1)
				{
					str.TrimLeft("CENA_SHKALI");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].CENA_SHKALI = atof(str);										
				}					
				if(str.Find("SMESHENIE") != -1)
				{
					str.TrimLeft("SMESHENIE");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].SMESHENIE = atof(str);										
				}

				if(str.Find("MIN_FIZ") != -1)
				{
					str.TrimLeft("MIN_FIZ");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].MIN_FIZ = atof(str);										
				}
				if(str.Find("MAX_FIZ") != -1)
				{
					str.TrimLeft("MAX_FIZ");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].MAX_FIZ = atof(str);										
				}
				if(str.Find("MAX_SHKALA_FIZ") != -1)
				{
					str.TrimLeft("MAX_SHKALA_FIZ");
					str.Trim();str.Trim("=");
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].MAX_SHKALA_FIZ = atoi(str);										
				}
				if((str.Find("//") != -1)/*&&(str.Find("//_") == -1)&&(str.Find("//MSK_") == -1)&&(str.Find("//KPL_") == -1)
					&&(str.Find("//VER_") == -1)&&(str.Find("//IO_") == -1)*/)
				{
					str.TrimLeft("//");				
					str.Remove('\n');
					str.Remove('\r');
					if((nProcIndex >= 0)&&(nProcIndex < m_CalcStructureModbusSArray.GetSize()))
						m_CalcStructureModbusSArray[nProcIndex].strCOMMENT = str;														
				}	
			}			
			strBuf.Delete(0,nIndex+1);			
		}while(nIndex != -1);
	}
	catch(...)
	{
		return FALSE;
	}

	return TRUE;
}
Exemple #5
0
void CDoc::KannadaConcatenate()
{
	int i,j,temp,Space=0,ind=0;
	BOOL flagpresent,flagnext;
	IIScHeader presenthead,nexthead;
	short int presentsignal[10000],nextsignal[10000],presentpitch[10000],nextpitch[10000];//*EndSignal;
	FILE *presentwave,*nextwave,*target,*missing;
	char present[100],next[100],prescan[100],nextscan[100];
	char Parse[100];
	char c;
	SizeOfSentance = 0;
	int i1=0;
	char p[20] = "parse1.iis";
	do
	{
		c = Path.GetAt(i1);
		if(c == '$')
			break;
		Parse[i1]=c;
		i1++;

	}while(c != '$');
	Parse[i1] = '\0';
	
	strcat(Parse,p);
	
	Parse[strlen(Parse)]= '\0';	
	char Missing[100];
	char M[20] = "missing.txt";
	i1=0;
	do
	{
		c = Path.GetAt(i1);
		if(c == '$')
			break;
		Missing[i1]=c;
		i1++;

	}while(c != '$');
	Missing[i1] = '\0';
	strcat(Missing,M);
	Missing[strlen(Missing)]= '\0';
	char X[100];
	//X=new char [100];
	char x1[20] = "x";
	i1=0;
	do
	{
		c = Path.GetAt(i1);
		if(c == '$')
			break;
		X[i1]=c;
		i1++;

	}while(c != '$');
	X[i1] = '\0';
	strcat(X,x1);
	X[strlen(X)]= '\0';

	CFile file;
	VERIFY(file.Open(Parse,CFile::modeRead));
	//parsed = fopen(Parse,"rt");
	missing = fopen(Missing,"at");
	target = fopen(X,"wb");
	int size=0;
	int duration = 0,Unit=1;
//	int len_present;
//	int pitchmark[300];
	//fscanf(parsed,"%s ",&prescan);
	file.Read(&prescan[0],sizeof(char));
	i=0;
	while(prescan[i] != ' ')
	{
		i++;
		file.Read(&prescan[i],sizeof(char));
	}
	prescan[i] = '\0';

	i1=0;
	do
	{
		c = Path.GetAt(i1);
		if(c == '$')
			break;
		present[i1]=c;
		i1++;

	}while(c != '$');
	present[i1] = '\0';
	strcat(present,prescan);
	int flag_checkdot=0;
	
	
	//TRACE(" \nCunitArray = %d",CUnitArray[ind]);
	while(1)
	{
		//fscanf(parsed,"%s ",&nextscan);
		file.Read(&nextscan[0],sizeof(char));
		i=0;
		while(nextscan[i] != ' ')
		{
			i++;
			file.Read(&nextscan[i],sizeof(char));
		}
		nextscan[i] = '\0';
		i1=0;
		next[i1]='\0';
		do
		{
			c = Path.GetAt(i1);
			if(c == '$')
				break;
			next[i1]=c;
			i1++;
	
		}while(c != '$');
		next[i1] = '\0';
		strcat(next,nextscan);
		Unit++;

		// Last Unit
		if(strcmp(nextscan,"y") == 0 || strcmp(nextscan,"x") == 0 || strcmp(nextscan,"xd") == 0 || strcmp(nextscan,"xq") == 0 || strcmp(nextscan,"xc") == 0 || strcmp(nextscan,"xd") == 0 ||strcmp(nextscan,"xe") == 0)
		{

			presentwave = fopen(present,"rb");
			if(presentwave == NULL)
			{
				TRACE(" \nNot Present - 1 **** %s" ,present);
				
			}
			else
			{
			
				fscanf(presentwave,"%s ",&presenthead.FileID);
				fscanf(presentwave,"%d ",&presenthead.junk);
				fscanf(presentwave,"%d ",&presenthead.junk1);
				fscanf(presentwave,"%u ",&presenthead.LanguageID);
				fscanf(presentwave,"%u ",&presenthead.BasicUnit);
				fscanf(presentwave,"%d ",&presenthead.DataLength);
				fscanf(presentwave,"%d ",&presenthead.AvgPitch);
				fscanf(presentwave,"%d ",&presenthead.LSegment);
				fscanf(presentwave,"%d ",&presenthead.RSegment);
				fscanf(presentwave,"%d\n",&presenthead.LengthofPitchMarks);
				//presentsignal = new short int [presenthead.DataLength];
				for(i=0;i<10000;i++)
					presentsignal[i]=0;
				for(i=0;i<1000;i++)
					presentpitch[i]=0;
				for(i=0;i<presenthead.DataLength;i++)
					fscanf(presentwave,"%d ",&presentsignal[i]);

				for(i=0;i<presenthead.LengthofPitchMarks;i++)
				{
					fscanf(presentwave,"%d ",&temp);
					presentpitch[temp] = 1;
				}
				//TRACE(" Unit = %d, CunitArray[ind] = %d",Unit,CUnitArray[ind]+1);
					for(i=presenthead.LSegment;i<presenthead.DataLength;i++)
						fwrite(&presentsignal[i],sizeof(short int),1,target);
					
					size = size+presenthead.DataLength-presenthead.LSegment;
					TRACE("Size in last = %d",size);
				
			}
			if(strcmp(nextscan,"y") == 0)
			{
				j=0;
				for(i=0;i<4000;i++)
					fwrite(&j,sizeof(short int),1,target);
				size=size+4000;
				break;
			}
			else if(strcmp(nextscan,"xd") == 0 || strcmp(nextscan,"xc") == 0 || strcmp(nextscan,"xq") == 0 || strcmp(nextscan,"xe") == 0)
			{
				strcpy(prescan,"x");
				Unit++;
				if( Unit == CUnitArray[ind]+1)
					ind++;
				
				j=0;
				if(strcmp(nextscan,"xc") == 0 )
				{
					for(i=0;i<4000;i++)
					fwrite(&j,sizeof(short int),1,target);
					size=size+4000;
				}
				else 
				{	
					
					if(flag_checkdot == 1)
					{
						flag_checkdot=0;
					
					}
					else
					{

						for(i=0;i<8000;i++)
							fwrite(&j,sizeof(short int),1,target);
						size=size+8000;
					}
					
				}
				//fscanf(parsed,"%s ",&nextscan);
				file.Read(&nextscan[0],sizeof(char));
				i=0;
				while(nextscan[i] != ' ')
				{
					i++;
					file.Read(&nextscan[i],sizeof(char));
				}
				nextscan[i] = '\0';
				i1=0;
				next[i1]='\0';
				do
				{
					c = Path.GetAt(i1);
					if(c == '$')
						break;
					next[i1]=c;
					i1++;
	
				}while(c != '$');
				next[i1] = '\0';
				strcat(next,nextscan);
				if(strcmp(nextscan,"y") == 0)
					break;
				continue;
			}
			else
			{
				strcpy(present,next);
				strcpy(prescan,nextscan);
				continue;
			}
			if(presentwave != NULL)
				fclose(presentwave);
		}

		// First Unit
		if(strcmp(prescan,"x") == 0)
		{

			j=0;
			
			for(i=0;i<0;i++)
				fwrite(&j,sizeof(short int),1,target);
			size=size+0;
			strcpy(present,next);
			strcpy(prescan,nextscan);
			presentwave = fopen(present,"rb");
			if(presentwave == NULL)
			{
				fprintf(missing,"\n%s",present);
				TRACE("\n Not Present  - 2 ****** %s", present);
					
			
			}
			else
			{
				flag_checkdot=1;
				fscanf(presentwave,"%s ",&presenthead.FileID);
				fscanf(presentwave,"%d ",&presenthead.junk);
				fscanf(presentwave,"%d ",&presenthead.junk1);
				fscanf(presentwave,"%u ",&presenthead.LanguageID);
				fscanf(presentwave,"%u ",&presenthead.BasicUnit);
				fscanf(presentwave,"%d ",&presenthead.DataLength);
				fscanf(presentwave,"%d ",&presenthead.AvgPitch);
				fscanf(presentwave,"%d ",&presenthead.LSegment);
				fscanf(presentwave,"%d ",&presenthead.RSegment);
				fscanf(presentwave,"%d\n",&presenthead.LengthofPitchMarks);
				//presentsignal = new short int [presenthead.DataLength];
				//presentpitch = new short int [presenthead.DataLength];
				for(i=0;i<10000;i++)
					presentsignal[i]=0;
				for(i=0;i<10000;i++)
					presentpitch[i]=0;
				for(i=0;i<presenthead.DataLength;i++)
					fscanf(presentwave,"%d ",&presentsignal[i]);

				if(presenthead.BasicUnit != 1 || presenthead.BasicUnit != 3 || presenthead.BasicUnit != 7)
				{
					//delete [] PM ;
					//PM = new short int [100000];
						for(i=0;i<presenthead.LSegment;i++)
							fwrite(&presentsignal[i],sizeof(short int),1,target);
						size = size+presenthead.LSegment;
						//TRACE("\n Size in first = %d",size);
					
					
				}
			}
			strcpy(present,next);
			strcpy(prescan,nextscan);
			if(presentwave != NULL)
				fclose(presentwave);
			continue;
		}
		
		//Middle Unit

		if(strcmp(prescan,"x") != 0 && strcmp(nextscan,"x") != 0 && strcmp(prescan,"y") != 0 && strcmp(nextscan,"y") != 0)
		{
			
			presentwave = fopen(present,"rb");
			if(presentwave == NULL)
			{
				fprintf(missing,"\n%s",present);
				TRACE("\n Not Present - 3 ******** %s", present);
			
				flagpresent = 0;
			}
			else
			{
			
				flag_checkdot=0;
				flagpresent = 1;				
				fscanf(presentwave,"%s ",&presenthead.FileID);
				fscanf(presentwave,"%d ",&presenthead.junk);
				fscanf(presentwave,"%d ",&presenthead.junk1);
				fscanf(presentwave,"%u ",&presenthead.LanguageID);
				fscanf(presentwave,"%u ",&presenthead.BasicUnit);
				fscanf(presentwave,"%d ",&presenthead.DataLength);
				fscanf(presentwave,"%d ",&presenthead.AvgPitch);
				fscanf(presentwave,"%d ",&presenthead.LSegment);
				fscanf(presentwave,"%d ",&presenthead.RSegment);
				fscanf(presentwave,"%d\n",&presenthead.LengthofPitchMarks);
				//presentsignal = new short int [presenthead.DataLength];
				//presentpitch = new short int [presenthead.DataLength];
				for(i=0;i<10000;i++)
					presentsignal[i]=0;
				for(i=0;i<10000;i++)
					presentpitch[i]=0;
				for(i=0;i<presenthead.DataLength;i++)
					fscanf(presentwave,"%d ",&presentsignal[i]);

				for(i=0;i<presenthead.LengthofPitchMarks;i++)
				{
					fscanf(presentwave,"%d ",&temp);
					presentpitch[temp] = 1;
				}
			}

			nextwave = fopen(next,"rb");
			if(nextwave == NULL)
			{
				fprintf(missing,"\n%s",next);
				TRACE("\n Not Present - 4 ******** %s", next);
			
				flagnext=0;
			}
			else
			{
				flagnext=1;
				fscanf(nextwave,"%s ",&nexthead.FileID);
				fscanf(nextwave,"%d ",&nexthead.junk);
				fscanf(nextwave,"%d ",&nexthead.junk1);
				fscanf(nextwave,"%u ",&nexthead.LanguageID);
				fscanf(nextwave,"%u ",&nexthead.BasicUnit);
				fscanf(nextwave,"%d ",&nexthead.DataLength);
				fscanf(nextwave,"%d ",&nexthead.AvgPitch);
				fscanf(nextwave,"%d ",&nexthead.LSegment);
				fscanf(nextwave,"%d ",&nexthead.RSegment);
				fscanf(nextwave,"%d\n",&nexthead.LengthofPitchMarks);

				//nextsignal = new short int [nexthead.DataLength];
				//nextpitch = new short int [nexthead.DataLength];
				for(i=0;i<10000;i++)
					nextsignal[i]=0;
				for(i=0;i<10000;i++)
					nextpitch[i]=0;
				
				for(i=0;i<nexthead.DataLength;i++)
					fscanf(nextwave,"%d ",&nextsignal[i]);
				
				for(i=0;i<nexthead.LengthofPitchMarks;i++)
				{
					fscanf(nextwave,"%d ",&temp);
					nextpitch[temp] = 1;
				}
			}


			strcpy(ToDuration,present);
			
			int duration = DetectDuration();
			int tempduration=0;
		

			if(flagpresent == 1)
			{
		
				if(presenthead.BasicUnit == 2)
				{
					
					if(duration/2 < presenthead.DataLength-presenthead.LSegment)
						tempduration = duration/2;
					else 
						tempduration = presenthead.DataLength-presenthead.LSegment;
					
					i=0;
					while(1)
					{
						if(presentpitch[i] ==1 && i>presenthead.LSegment+tempduration)
						{
							tempduration=i-presenthead.LSegment;
							break;
						}
						i++;
						//Modified by me
						if(i >= presenthead.DataLength/2)
							break;
					}
					
						for(i=presenthead.LSegment;i<presenthead.LSegment+tempduration;i++)
							fwrite(&presentsignal[i],sizeof(short int),1,target);
						size = size+tempduration;
						TRACE("\n Size in middle = %d",size);
						
				}
				
				if(presenthead.BasicUnit == 4 || presenthead.BasicUnit == 5 || presenthead.BasicUnit == 6)
				{
				
					
						for(i=presenthead.LSegment;i<presenthead.RSegment;i++)
							fwrite(&presentsignal[i],sizeof(short int),1,target);
						size = size+presenthead.RSegment-presenthead.LSegment;
					
					
					if(duration/2 < presenthead.DataLength-presenthead.RSegment)
						tempduration = duration/2;
					else 
						tempduration = presenthead.DataLength-presenthead.RSegment;

					i=0;
					while(1)
					{
						if(presentpitch[i] ==1 && i>presenthead.RSegment+tempduration)
						{
							tempduration=i-presenthead.RSegment;
							break;
						}
						i++;
					}
				
					
						for(i=presenthead.RSegment;i<presenthead.RSegment+tempduration;i++)
							fwrite(&presentsignal[i],sizeof(short int),1,target);
						size = size+tempduration;
						TRACE("\n Size in middle = %d",size);
					
					
				}
				flagpresent=0;
			}
			tempduration=0;
			if(flagnext == 1)
			{
				if(duration/2 < nexthead.LSegment)
					tempduration = duration/2;
				else 
					tempduration = nexthead.LSegment;
						
				i=0;
				while(1)
				{
					if(nextpitch[i] ==1 && i>nexthead.LSegment-tempduration)
					{
						tempduration=nexthead.LSegment-i;
						break;
					}
					i++;
				}
				
					for(i=nexthead.LSegment-tempduration;i<nexthead.LSegment;i++)
						fwrite(&nextsignal[i],sizeof(short int),1,target);
					size = size+tempduration;
					//TRACE("\n Size in middle next  = %d",size);
				
				flagnext=0;
			}
			//TRACE("CSpace = %d, Cunit = %d, Unit = %d\n",CSpace[ind],CUnitArray[ind],Unit);
			strcpy(present,next);
			strcpy(prescan,nextscan);
			if(presentwave != NULL)
				fclose(presentwave);
			if(nextwave != NULL)
				fclose(nextwave);
			
		}
	}
	SizeOfSentance =  size;
	fcloseall();
	//TRACE("\n Space = %d, Unit = %d",Space,Unit);
	TRACE("\nOut of Concatenate %d\n",SizeOfSentance);
	WriteWaveFile();


}
Exemple #6
0
bool CSkeleton::Load(const string& filename)
{
	CFile file;
	if (!file.Open(filename, QIODevice::ReadOnly))
		return false;

	int ver;
	file.Read(ver);
	if (ver < VER_BONE)
	{
		qWarning(("Skeleton version no more supported in '" % filename % "'").toLocal8Bit());
		file.Close();
		return false;
	}

	file.Read(m_ID);
	file.Read(m_boneCount);

	int len;
	Bone* bone;
	m_bones = new Bone[m_boneCount];
	for (int i = 0; i < m_boneCount; i++)
	{
		bone = &m_bones[i];
		file.Read(len);
		file.Read(bone->name, len);
		file.Read(bone->TM);
		file.Read(bone->inverseTM);
		file.Read(bone->localTM);
		file.Read(bone->parentID);
	}

	int temp;
	file.Read(temp);
	m_sendVS = temp != 0;

	file.Read(m_localRH);
	file.Read(m_localShield);
	file.Read(m_localKnuckle);

	if (ver == 5)
	{
		file.Read(m_events, 4);
		file.Read(m_eventParentIDs, 4);
	}
	else if (ver >= 6)
	{
		file.Read(m_events, MAX_MDL_EVENT);
		file.Read(m_eventParentIDs, MAX_MDL_EVENT);
	}

	if (ver == 7)
		file.Read(m_localLH);

	file.Close();
	return true;
}
BOOL CPreviewThread::Run()
{
	ASSERT (m_pPartfile) ;
	CFile destFile;
	CFile srcFile;
	if (!srcFile.Open(m_pPartfile->GetFilePath(), CFile::modeRead | CFile::shareDenyNone))
		return FALSE;
	try{
		uint32 nSize = m_pPartfile->GetFileSize();
		CString strExtension = CString(_tcsrchr(m_pPartfile->GetFileName(), _T('.')));
		CString strPreviewName = m_pPartfile->GetTempPath() + _T("\\") + m_pPartfile->GetFileName().Mid(0, 5) + _T("_preview") + strExtension;
		bool bFullSized = true;
		if (!strExtension.CompareNoCase(_T(".mpg")) || !strExtension.CompareNoCase(_T(".mpeg")))
			bFullSized = false;
		if (!destFile.Open(strPreviewName, CFile::modeWrite | CFile::shareDenyWrite | CFile::modeCreate))
			return FALSE;
		srcFile.SeekToBegin();
		if (bFullSized)
			destFile.SetLength(nSize);
		destFile.SeekToBegin();
		BYTE abyBuffer[4096];
		uint32 nRead;
		while (destFile.GetPosition()+4096 < PARTSIZE*2){
			nRead = srcFile.Read(abyBuffer,4096);
			destFile.Write(abyBuffer,nRead);
		}
		srcFile.Seek(-(PARTSIZE*2),CFile::end);
		uint32 nToGo =PARTSIZE*2;
		if (bFullSized)
			destFile.Seek(-(PARTSIZE*2),CFile::end);
		do{
			nRead = (nToGo - 4096 < 1)? nToGo:4096;
			nToGo -= nRead;
			nRead = srcFile.Read(abyBuffer,4096);
			destFile.Write(abyBuffer,nRead);
		}
		while (nToGo);
		destFile.Close();
		srcFile.Close();
		m_pPartfile->m_bPreviewing = false;

		SHELLEXECUTEINFO SE;
		MEMSET(&SE,0,sizeof(SE));
		SE.fMask = SEE_MASK_NOCLOSEPROCESS ;
		SE.lpVerb = _T("open");
		
		CString path;
		if (!m_player.IsEmpty())
		{
			TCHAR shortPath[512]; //Cax2 short path for vlc
			GetShortPathName(strPreviewName, shortPath, ARRSIZE(shortPath));

			path=thePrefs.GetVideoPlayer();
			int pos = path.ReverseFind(_T('\\'));
			if (pos == -1)
				path.Empty();
			else
				path = path.Left(pos + 1);
			SE.lpFile = m_player.GetBuffer();
			SE.lpParameters=shortPath;
			SE.lpDirectory=path.GetBuffer();
		}
		else
			SE.lpFile = strPreviewName.GetBuffer();
		SE.nShow = SW_SHOW;
		SE.cbSize = sizeof(SE);
		ShellExecuteEx(&SE);
		if (SE.hProcess){
			WaitForSingleObject(SE.hProcess, INFINITE);
			CloseHandle(SE.hProcess);
		}
		CFile::Remove(strPreviewName);
	}	
	catch(CFileException* error){
		m_pPartfile->m_bPreviewing = false;
		error->Delete();
	}
	return TRUE;
}
Exemple #8
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;
}
/*
*	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;
}
Exemple #10
0
int CRaster::LoadBMP(const char* cfileName)
{
    CFile   file;
    BITMAPFILEHEADER    fileHeader;
    BITMAPINFOHEADER    infoHeader;
    DWORD               width, height;

    LOGPALETTE          *logPal;

    DWORD               Index;
    WORD                bitCount;
    BYTE*               tempImage;

    if(flag) {
        DeleteAllData();
    }/* if */

    if(file.Open(cfileName, CFile::modeRead, NULL) == 0)
        return -1;

    fileName    = cfileName; 

    file.Read(&fileHeader, sizeof(BITMAPFILEHEADER));
    if(fileHeader.bfType != 0x4d42) {
        file.Close();
        return -1;
    } /* if... it's not BMP */

// Load bitmap info
    file.Read(&infoHeader, sizeof(BITMAPINFOHEADER));
    bitCount    = infoHeader.biBitCount;
    if(infoHeader.biCompression != BI_RGB ) {
        file.Close();
        return -2;
    }/* if */
    if( bitCount == 1 ||
        bitCount == 4 ||
        bitCount == 8) { // type of bitmap

        DWORD numColor = infoHeader.biClrUsed;
        if(numColor == 0) {
            numColor = 1<<bitCount;
        }

        imgInfo = (BITMAPINFO*)malloc(  sizeof(BITMAPINFO) 
                                        + sizeof(RGBQUAD) * (1<<bitCount));
        file.Read(imgInfo->bmiColors, sizeof(RGBQUAD) * numColor);

    // Create Palette for 1<<bitCount colors
        pal     = new CPalette();
        logPal  = (LOGPALETTE*)
                    calloc( 1,  sizeof(LOGPALETTE) 
                                    + sizeof(PALETTEENTRY) * (1<<bitCount));

        logPal->palVersion      = 0x300;
        logPal->palNumEntries   = BYTE(1<<bitCount);

        for(Index = 0; Index < numColor; Index++) {

            logPal->palPalEntry[Index].peRed    =
                imgInfo->bmiColors[Index].rgbRed;

            logPal->palPalEntry[Index].peGreen	=
                imgInfo->bmiColors[Index].rgbGreen;

            logPal->palPalEntry[Index].peBlue   =
                imgInfo->bmiColors[Index].rgbBlue;
        }/* for */

        pal->CreatePalette(logPal);
        free(logPal);
    } else if(  bitCount == 24 ) {
        imgInfo = (BITMAPINFO*)malloc(  sizeof(BITMAPINFO) 
                                        + sizeof(RGBQUAD));
    } else {
        file.Close();
        return -2;
    } /* if... not support BMP */

    imgInfo->bmiHeader	= infoHeader;

// Load image data
    width   = imgInfo->bmiHeader.biWidth;
    height  = abs(imgInfo->bmiHeader.biHeight);

    switch(bitCount) {
    case 1:
        shiftPixel  = (width + 7) / 8;
        break;
    case 4:
        shiftPixel  = (width + 1) / 2;
        break;
    case 8:
        shiftPixel  = width;
        break;
    case 24:
        shiftPixel  = width * 3;
        break;
    }/* switch */

    DestWidth   = width;
    DestHeight  = height;
    SrcWidth    = width;
    SrcHeight   = height;

    sizeString  = (shiftPixel + 3) / 4 * 4;	// Attention !!! divided 4 !!!;

    tempImage       = new BYTE[sizeString*height];
    imgData         = new BYTE[sizeString*height];
    imgDataSave     = tempImage;

    for(Index = 0; Index < height; Index++) {
        file.Read(tempImage, sizeString);
        tempImage+=sizeString;
    }/* for */

    imgInfo->bmiHeader.biHeight = -abs(imgInfo->bmiHeader.biHeight);

    UpdateImage(0);
    flag    = 1;
    file.Close();
    return 1;
}/* CRaster::LoadBMP */
Exemple #11
0
void CRectangle::openfile(CFile &file)
{
	 file.Read(&tprect, sizeof(TP));
	 CLine::openfile(file);
	 name="CRectangle";
}
Exemple #12
0
BOOL CModbusM::LoadFromTuFile(CString strFile)
{
	CFile f;
	CString strBuf,str;
	try
	{
		if(!f.Open(strFile,CFile::modeRead))
			return FALSE;
		CHAR buffer[4096];
		DWORD dwRead=0;

		// Read in 4096-byte blocks,
		// remember how many bytes were actually read,
		// and try to write that many out. This loop ends
		// when there are no more bytes to read.
		do
		{
			dwRead = f.Read(buffer, 4096);
			if(dwRead > 0)
			{
				int nLen = strBuf.GetLength();
				strBuf+=buffer;
				strBuf.Truncate(nLen+dwRead);
			}
		}
		while (dwRead > 0);
		f.Close();
		//AfxMessageBox(strBuf);
		strBuf.MakeUpper();
		int nIndex = 0;
		int nProcIndex = -1;
		strBuf.Remove(';');
		int nWaitRespTU = 0;
		do
		{
			nIndex = strBuf.Find("\n");
			str = strBuf.Left(nIndex+1);
			
			if(str.Find("NUMBER_OF_TU") != -1)
			{
				str.TrimLeft("NUMBER_OF_TU");
				str.Trim();str.Trim("=");
				m_TuArray.SetSize(atoi(str));
			}
						
			if(str.Find("MAKE_TU") != -1)
			{
				str.TrimLeft("MAKE_TU");
				str.Trim();str.Trim("=");
				if((atoi(str) > 0)&&(atoi(str) <= m_TuArray.GetSize()))				
					nProcIndex = atoi(str)-1;								
			}			
			if(str.Find("WAIT_RESP_TU") != -1)
			{
				str.TrimLeft("WAIT_RESP_TU");
				str.Trim();str.Trim("=");
				//if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					nWaitRespTU = atoi(str);										
			}
			if(str.Find("TU_CLOSER") != -1)
			{
				str.TrimLeft("TU_CLOSER");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].TU_CLOSER = atoi(str);										
			}
			if(str.Find("DATATU_OFF") != -1)
			{
				str.TrimLeft("DATATU_OFF");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].DATATU_OFF = atoi(str);										
			}
			if(str.Find("DATATU_ON") != -1)
			{
				str.TrimLeft("DATATU_ON");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].DATATU_ON = atoi(str);										
			}
			if(str.Find("REGTU_OFF") != -1)
			{
				str.TrimLeft("REGTU_OFF");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].REGTU_OFF = atoi(str);										
			}
			if(str.Find("REGTU_ON") != -1)
			{
				str.TrimLeft("REGTU_ON");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].REGTU_ON = atoi(str);										
			}
			if(str.Find("FUNCTION") != -1)
			{
				str.TrimLeft("FUNCTION");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].FUNCTION = atoi(str);										
			}		
			if((str.Find("ADRESS") != -1)&&(str.Find("ADDRESS_TS") == -1)&&(str.Find("ADDRESS_DAMAGE_TU") == -1))
			{
				str.TrimLeft("ADRESS");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].ADRESS = atoi(str);										
			}
			if(str.Find("TYPE_PRIBOR") != -1)
			{
				str.TrimLeft("TYPE_PRIBOR");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].TYPE_PRIBOR = atoi(str);										
			}
			if(str.Find("IEC_ASDU") != -1)
			{
				str.TrimLeft("IEC_ASDU");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].IEC_ASDU = atoi(str);										
			}
			if(str.Find("TU_ACT_TRM_ENABLE") != -1)
			{
				str.TrimLeft("TU_ACT_TRM_ENABLE");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].TU_ACT_TRM_ENABLE = atoi(str);										
			}
			if(str.Find("TIMER_SEL_EXEC") != -1)
			{
				str.TrimLeft("TIMER_SEL_EXEC");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].TIMER_SEL_EXEC = atoi(str);										
			}
			if(str.Find("TIMER_ACT_TRM") != -1)
			{
				str.TrimLeft("TIMER_ACT_TRM");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].TIMER_ACT_TRM = atoi(str);										
			}	
			if(str.Find("ADDRESS_TS") != -1)
			{
				str.TrimLeft("ADDRESS_TS");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].ADDRESS_TS = atoi(str);										
			}	
			if(str.Find("TS_ON") != -1)
			{
				str.TrimLeft("TS_ON");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].TS_ON = atoi(str);										
			}	
			if(str.Find("TS_OFF") != -1)
			{
				str.TrimLeft("TS_OFF");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].TS_OFF = atoi(str);										
			}	
			if(str.Find("ADDRESS_DAMAGE_TU") != -1)
			{
				str.TrimLeft("ADDRESS_DAMAGE_TU");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].ADDRESS_DAMAGE_TU = atoi(str);										
			}
			if(str.Find("MASKA_DAMAGE_TU") != -1)
			{
				str.TrimLeft("MASKA_DAMAGE_TU");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].MASKA_DAMAGE_TU = atoi(str);										
			}
			if((str.Find("//") != -1)&&(str.Find("//_") == -1))
			{
				str.TrimLeft("//");				
				str.Remove('\n');
				str.Remove('\r');
				if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize()))
					m_TuArray[nProcIndex].strCOMMENT = str;														
			}
			strBuf.Delete(0,nIndex+1);			
		}while(nIndex != -1);

		for(int i = 0; i < m_TuArray.GetSize(); i++)
			m_TuArray[i].WAIT_RESP_TU = nWaitRespTU;
	}
	catch(...)
	{
		return FALSE;
	}

	return TRUE;
}
Exemple #13
0
BOOL CModbusM::LoadFromFile(CString strFile)
{
	CFile f;
	CString strBuf,str;
	try
	{
		if(!f.Open(strFile,CFile::modeRead))
			return FALSE;
		CHAR buffer[4096];
		DWORD dwRead=0;
		// Read in 4096-byte blocks,
		// remember how many bytes were actually read,
		// and try to write that many out. This loop ends
		// when there are no more bytes to read.
		do
		{
			dwRead = f.Read(buffer, 4096);
			if(dwRead > 0)
			{
				int nLen = strBuf.GetLength();
				strBuf+=buffer;
				strBuf.Truncate(nLen+dwRead);
			}
		}
		while (dwRead > 0);
		f.Close();
		//AfxMessageBox(strBuf);
		strBuf.MakeUpper();
		strBuf.Remove(';');
		int nIndex = 0;
		int nProcIndex = -1;
		do
		{
			nIndex = strBuf.Find("\n");
			str = strBuf.Left(nIndex+1);
			if(str.Find("PORT") != -1)
			{
				str.TrimLeft("PORT");
				str.Trim();str.Trim("=");				
				PORT = atoi(str);
			}
			if(str.Find("BAUDRATE") != -1)
			{
				str.TrimLeft("BAUDRATE");
				str.Trim();str.Trim("=");
				BAUDRATE = atoi(str);
			}
			if(str.Find("STOPBITS") != -1)
			{
				str.TrimLeft("STOPBITS");
				str.Trim();str.Trim("=");
				STOPBITS = atoi(str);
			}
			if(str.Find("PARITY") != -1)
			{
				str.TrimLeft("PARITY");
				str.Trim();str.Trim("=");
				PARITY = atoi(str);
			}
			if(str.Find("BYTETIME") != -1)
			{
				str.TrimLeft("BYTETIME");
				str.Trim();str.Trim("=");
				BYTETIME = atoi(str);
			}
			if(str.Find("WAITRESP") != -1)
			{
				str.TrimLeft("WAITRESP");
				str.Trim();str.Trim("=");
				WAITRESP = atoi(str);
			}
			if(str.Find("NEXTMESSAGE") != -1)
			{
				str.TrimLeft("NEXTMESSAGE");
				str.Trim();str.Trim("=");
				NEXTMESSAGE = atoi(str);
			}
			if(str.Find("AMOUNTBYTE") != -1)
			{
				str.TrimLeft("AMOUNTBYTE");
				str.Trim();str.Trim("=");
				AMOUNTBYTE = atoi(str);
			}
			if(str.Find("CONTROLPOTOK") != -1)
			{
				str.TrimLeft("CONTROLPOTOK");
				str.Trim();str.Trim("=");
				CONTROLPOTOK = atoi(str);
			}
			if(str.Find("NUMBER_NO_ANSWER") != -1)
			{
				str.TrimLeft("NUMBER_NO_ANSWER");
				str.Trim();str.Trim("=");
				NUMBER_NO_ANSWER = atoi(str);
			}
			if(str.Find("MODBUS_TYPE") != -1)
			{
				str.TrimLeft("MODBUS_TYPE");
				str.Trim();str.Trim("=");
				MODBUS_TYPE = atoi(str);
			}			
			if(str.Find("NUMBER_OF_PRIBOR") != -1)
			{
				str.TrimLeft("NUMBER_OF_PRIBOR");
				str.Trim();str.Trim("=");
				m_ModbusPriborArray.SetSize(atoi(str));
			}
			
			
			if(str.Find("MAKE_PRIBOR") != -1)
			{
				str.TrimLeft("MAKE_PRIBOR");
				str.Trim();str.Trim("=");
				if((atoi(str) > 0)&&(atoi(str) <= m_ModbusPriborArray.GetSize()))				
					nProcIndex = atoi(str)-1;								
			}
			if((str.Find("//") != -1)&&(str.Find("//_") == -1))
			{
				str.TrimLeft("//");				
				str.Remove('\n');
				str.Remove('\r');
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].strCOMMENT = str;														
			}
			if((str.Find("PRIBOR") != -1)&&(str.Find("MAKE_PRIBOR") == -1)&&(str.Find("NUMBER_OF_PRIBOR") == -1))
			{
				str.TrimLeft("PRIBOR");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].PRIBOR = atoi(str);										
			}			
			if((str.Find("ADRESS") != -1)&&(str.Find("START_ADRESS") == -1)&&(str.Find("ADRESS_PMZ") == -1))
			{
				str.TrimLeft("ADRESS");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].ADRESS = atoi(str);										
			}
			if(str.Find("FUNCTION") != -1)
			{
				str.TrimLeft("FUNCTION");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].FUNCTION = atoi(str);										
			}		
			if(str.Find("START_ADRESS") != -1)
			{
				str.TrimLeft("START_ADRESS");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].START_ADRESS = atoi(str);										
			}
			if(str.Find("ADRESS_PMZ") != -1)
			{
				str.TrimLeft("ADRESS_PMZ");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].ADRESS_PMZ = atoi(str);										
			}
			if((str.Find("NUMBER") != -1)&&(str.Find("NUMBER_NO_ANSWER") == -1)&&(str.Find("NUMBER_OF_PRIBOR") == -1))
			{
				str.TrimLeft("NUMBER");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].NUMBER = atoi(str);										
			}
			if(str.Find("DOP_BYTE1") != -1)
			{
				str.TrimLeft("DOP_BYTE1");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].DOP_BYTE1 = atoi(str);										
			}
			if(str.Find("DOP_BYTE2") != -1)
			{
				str.TrimLeft("DOP_BYTE2");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].DOP_BYTE2 = atoi(str);										
			}
			if(str.Find("DOP_BYTE3") != -1)
			{
				str.TrimLeft("DOP_BYTE3");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].DOP_BYTE3 = atoi(str);										
			}
			if(str.Find("DOP_BYTE4") != -1)
			{
				str.TrimLeft("DOP_BYTE4");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].DOP_BYTE4 = atoi(str);										
			}
			if(str.Find("TYPE_STATUS") != -1)
			{
				str.TrimLeft("TYPE_STATUS");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].TYPE_STATUS= atoi(str);										
			}
			if(str.Find("MASKA_STATUS") != -1)
			{
				str.TrimLeft("MASKA_STATUS");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].MASKA_STATUS= atoi(str);										
			}
			if(str.Find("ADRES_STATUS") != -1)
			{
				str.TrimLeft("ADRES_STATUS");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].ADRES_STATUS= atoi(str);										
			}
			if(str.Find("ADRES_4B") != -1)
			{
				str.TrimLeft("ADRES_4B");
				str.Trim();str.Trim("=");
				if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize()))
					m_ModbusPriborArray[nProcIndex].ADRES_4B= atoi(str);										
			}		
			strBuf.Delete(0,nIndex+1);			
		}while(nIndex != -1);
	}
	catch(...)
	{
		return FALSE;
	}

	return TRUE;
}
Exemple #14
0
size_t CAPEv2Tag::fread_callback(void *ptr, size_t size, size_t nmemb, void *fp)
{
  CFile *file = (CFile *)fp;
  return file->Read(ptr, size * nmemb) / size;
}
Exemple #15
0
bool CEvmFile::Load(const char* sFileName)
{
	CFile oFile;
	if(oFile.Open(sFileName, "r"))
	{
		FocpLog(FOCP_LOG_WARNING, ("Load(%s): open file failure", sFileName));
		return false;
	}

	CEvmFileHead oHead;
	if(sizeof(oHead) != oFile.Read(&oHead, sizeof(oHead)))
	{
		FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
		return false;
	}

	if(!CBinary::MemoryCompare(oHead.magic, "CEXE", 4))
		m_nFileType = EVM_EXE_FILE;
	else if(!CBinary::MemoryCompare(oHead.magic, "CDLL", 4))
		m_nFileType = EVM_DLL_FILE;
	else
	{
		FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
		return false;
	}
	bool bNeedConvert = ((oHead.endian!=0) != IsSmallEndian());
	if(bNeedConvert)
	{
		oHead.version0 = CBinary::U16Code(oHead.version0);
		oHead.version1 = CBinary::U16Code(oHead.version1);
		oHead.version2 = CBinary::U16Code(oHead.version2);
	}
	if(oHead.version0 > EVM_FILE_VERSION_0)
	{
		FocpLog(FOCP_LOG_WARNING, ("Load(%s): version too new", sFileName));
		return false;
	}
	else if(oHead.version0 == EVM_FILE_VERSION_0)
	{
		if(oHead.version1 > EVM_FILE_VERSION_1)
		{
			FocpLog(FOCP_LOG_WARNING, ("Load(%s): version too new", sFileName));
			return false;
		}
		else if(oHead.version1 == EVM_FILE_VERSION_1)
		{
			if(oHead.version2 > EVM_FILE_VERSION_2)
			{
				FocpLog(FOCP_LOG_WARNING, ("Load(%s): version too new", sFileName));
				return false;
			}
		}
	}

	ehc_uint pSection[2], nEntry, nTag = 0;
	bool bReadDone[] = {true,false,false,false,false,false,false,false};

	while(true)
	{
		if(sizeof(pSection) != oFile.Read(pSection, sizeof(pSection)))
		{
			FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
			return false;
		}
		if(bNeedConvert)
		{
			pSection[0] = CBinary::U32Code(pSection[0]);
			pSection[1] = (ehc_int)CBinary::U32Code((ehc_uint)pSection[1]);
		}
		if((pSection[0] >= EVM_INVALID_SECTION) || bReadDone[pSection[0]] || (pSection[0] <= nTag) || (pSection[1] % sizeof(ehc_uint)))
		{
			FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
			return false;
		}
		nTag = pSection[0];
		bReadDone[pSection[0]] = true;
		switch(nTag)
		{
		case EVM_CODESEG_SECTION:
			m_nCodeSize = pSection[1];
			m_pCodeSegment = NULL;
			if(m_nCodeSize)
			{
				m_pCodeSegment = new ehc_char[m_nCodeSize];
				if(m_nCodeSize != oFile.Read(m_pCodeSegment, m_nCodeSize))
				{
					FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
					return false;
				}
			}
			break;
		case EVM_DATASEG_SECTION:
			if(pSection[1] != (ehc_int)sizeof(ehc_uint))
			{
				FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
				return false;
			}
			if(sizeof(ehc_int) != oFile.Read(&m_nDataSize, sizeof(ehc_int)))
			{
				FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
				return false;
			}
			if(bNeedConvert)
				m_nDataSize = CBinary::U32Code(m_nDataSize);
			break;
		case EVM_CONSTSEG_SECTION:
			m_nConstSize = pSection[1];
			m_pConstSegment = NULL;
			if(m_nConstSize)
			{
				m_pConstSegment = new ehc_char[m_nConstSize];
				if(m_nConstSize != oFile.Read(m_pConstSegment, m_nConstSize))
				{
					FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
					return false;
				}
			}
			break;
		case EVM_SYMTAB_SECTION:
			if((pSection[1] % sizeof(CEvmSymbolItem)) || (nFileSize < pSection[1]))
			{
				FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
				return false;
			}
			m_nSymCount = pSection[1] / sizeof(CEvmSymbolItem);
			if(m_nSymCount)
			{
				CEhcSymbolItem* pSymbolTable = new CEhcSymbolItem[m_nSymCount];
				if(pSection[1] != oFile.Read(pSymbolTable, pSection[1]))
				{
					delete[] pSymbolTable;
					FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
					return false;
				}
				if(bNeedConvert)
				{
					for(ehc_int i=0; i<m_nSymCount; ++i)
					{
						pSymbolTable[i].name = CBinary::U32Code(pSymbolTable[i].name);
						pSymbolTable[i].type = CBinary::U32Code(pSymbolTable[i].type);
						pSymbolTable[i].opt = CBinary::U32Code(pSymbolTable[i].opt);
						pSymbolTable[i].arg = CBinary::U32Code(pSymbolTable[i].arg);
					}
				}
				m_pSymbolTable = new CEvmSymbolItem[m_nSymCount];
				for(ehc_int i=0; i<m_nSymCount; ++i)
				{
					if(pSymbolTable[i].name >= (ehc_uint)m_nConstSize)
					{
						delete[] pSymbolTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
						return false;
					}
					m_pSymbolTable[i].name = m_pConstSegment + pSymbolTable[i].name;
					m_pSymbolTable[i].type = pSymbolTable[i].type;
					m_pSymbolTable[i].opt = pSymbolTable[i].opt;
					m_pSymbolTable[i].addr = NULL;
					m_pSymbolTable[i].file = NULL;
					m_pSymbolTable[i].idx = 0xFFFFFFFF;
					ehc_int nMaxLen = m_nConstSize - pSymbolTable[i].name;
					ehc_int nNameLen = (ehc_int)CString::StringLength(m_pSymbolTable[i].name, (ehc_uint)nMaxLen);
					if(nNameLen >= nMaxLen || !nNameLen)
					{//符号名不合法
						delete[] pSymbolTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
						return false;
					}
					if(!(pSymbolTable[i].type&EVM_SHARE_SYM))
					{//可执行文件或动态库符号表中的符号应全是共享符号。
						delete[] pSymbolTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
						return false;
					}
					m_pSymbolTable[i].type &= ~EVM_SHARE_SYM;
					switch(m_pSymbolTable[i].type)
					{
					default:
						delete[] pSymbolTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
						return false;
					case EVM_VARIABLE_SYM:
						switch(m_pSymbolTable[i].opt)
						{
						default:
							delete[] pSymbolTable;
							FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
							return false;
						case EHC_UN: //外部变量符号,需要连接
							++m_nExternCount;
							break;
						case EHC_DS: //输出变量符号,可被连接
							if(pSymbolTable[i].arg >= m_nDataSize)
							{
								delete[] pSymbolTable;
								FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
								return false;
							}
							break;
						}
						break;
					case EVM_FUNCTION_SYM:
						switch(m_pSymbolTable[i].opt)
						{
						default:
							delete[] pSymbolTable;
							FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
							return false;
						case EHC_UN: //外部函数符号,需要连接
							++m_nExternCount;
							break;
						case EHC_CS: //输出函数符号,可被连接
							if(pSymbolTable[i].arg >= m_nCodeSize || (pSymbolTable[i].arg%sizeof(ehc_uint)))
							{//代码越界或无效指令边界
								delete[] pSymbolTable;
								FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
								return false;
							}
							m_pSymbolTable[i].addr = m_pCodeSegment + pSymbolTable[i].arg;
							break;
						case EHC_HS:
							break;
						}
						break;
					}
				}
				delete[] pSymbolTable;
			}
			break;
		case EVM_LIBTAB_SECTION:
			m_nLibCount = pSection[1] / sizeof(m_nLibCount);
			m_pLibTable = NULL;
			if(m_nLibCount)
			{
				ehc_uint* pLibTable = new ehc_uint[m_nLibCount];
				if(pSection[1] != oFile.Read(pLibTable, pSection[1]))
				{
					delete[] pLibTable;
					FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
					return false;
				}
				if(bNeedConvert)
				{
					for(ehc_int i=0; i<m_nLibCount; ++i)
						pLibTable[i] = CBinary::U32Code(pLibTable[i]);
				}
				m_pLibTable = new ehc_char*[m_nLibCount];
				for(ehc_int i=0; i<m_nLibCount; ++i)
				{
					if(pLibTable[i] >= (ehc_uint)m_nConstSize)
					{
						delete[] pLibTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
						return false;
					}
					m_pLibTable[i] = m_pConstSegment + pLibTable[i];
					ehc_int nMaxLen = m_nConstSize - pLibTable[i];
					ehc_int nNameLen = (ehc_int)CString::StringLength(m_pLibTable[i], (ehc_uint)nMaxLen);
					if(nNameLen >= nMaxLen || !nNameLen)
					{//符号名不合法
						delete[] pLibTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
						return false;
					}
				}
				delete[] pLibTable;
			}
			break;
		case EVM_HOSTTAB_SECTION:
			m_nHostCount = pSection[1] / sizeof(m_nHostCount);
			m_pHostTable = NULL;
			if(m_nHostCount)
			{
				ehc_uint* pHostTable = new ehc_uint[m_nHostCount];
				if(pSection[1] != oFile.Read(pHostTable, pSection[1]))
				{
					delete[] pHostTable;
					FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
					return false;
				}
				if(bNeedConvert)
				{
					for(ehc_int i=0; i<m_nHostCount; ++i)
						pHostTable[i] = CBinary::U32Code(pHostTable[i]);
				}
				m_pHostTable = new CDynamicLibrary[m_nHostCount];
				for(ehc_int i=0; i<m_nHostCount; ++i)
				{
					if(pHostTable[i] >= (ehc_uint)m_nConstSize)
					{
						delete[] pHostTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
						return false;
					}
					ehc_har* name = m_pConstSegment + pHostTable[i];
					ehc_int nMaxLen = m_nConstSize - pHostTable[i];
					ehc_int nNameLen = (ehc_int)CString::StringLength(name, (ehc_uint)nMaxLen);
					if(nNameLen >= nMaxLen || !nNameLen)
					{//符号名不合法
						delete[] pHostTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
						return false;
					}
					if(!m_pHostTable[i].Load(name))
					{
						delete[] pHostTable;
						FocpLog(FOCP_LOG_WARNING, ("Load(%s): load host file(%s) failure", sFileName, name));
						return false;
					}
				}
				delete[] pHostTable;
			}
			break;
		case EVM_ENTRY_SECTION:
			if(pSection[1] != (ehc_int)sizeof(ehc_uint))
			{
				FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
				return false;
			}
			if(sizeof(ehc_uint) != oFile.Read(&nEntry, sizeof(ehc_uint)))
			{
				FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
				return false;
			}
			if(bNeedConvert)
				nEntry = CBinary::U32Code(nEntry);
			if((nEntry >= m_nCodeSize) || (nEntry%sizeof(ehc_uint)))
			{
				FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName));
				return false;
			}
			m_pEntry = m_pCodeSegment + nEntry;
			break;
		}
	}

	//扫描符号表,对主机函数进行连接
	for(ehc_int i=0; i<m_nSymCount; ++i)
	{
		if(m_pSymbolTable[i].opt == EHC_HS)
		{
			for(ehc_int j=0; j<m_nHostCount; ++j)
			{
				m_pSymbolTable[i].addr = m_pHostTable[i].FindSymbol(m_pSymbolTable[i].name);
				if(m_pSymbolTable[i].addr)
					break;
			}
			if(m_pSymbolTable[i].addr == NULL)
			{
				FocpLog(FOCP_LOG_WARNING, ("Load(%s): host function(%s) link failure", sFileName, m_pSymbolTable[i].name));
				return false;
			}
		}
	}

	m_oFileName = sFileName;

	return true;
}
DWORD ConnectionLimit::GetOffset(LPCTSTR path)
{
	CFile file;
	DWORD dwOffset = 0;
	bool isWow = IsWow64();
	PVOID oldValue = NULL;
	if(isWow)
	{
		MyWow64DisableWow64FsRedirection(&oldValue);
	}

	if(file.Open(path,CFile::modeRead|CFile::typeBinary))
	{
		if(isWow)
		{
			MyWow64RevertWow64FsRedirection(oldValue);
		}
		unsigned int bytesRead = 0;
		char buffer[1024];
		bytesRead = file.Read(buffer, 1024);
		while(bytesRead != 0)
		{
			for (int i = 0; i<bytesRead; ++i)
			{
				if(!isWow && (CAntiSpySettings::GetSuiteType() != CAntiSpySettings::SUITE_TYPE::WINDOWS_VISTA))
				{

					if(buffer[i] == MAGIC_32[0])
					{
						if(i>= (bytesRead - 5))
						{
							int pos = file.GetPosition();
							file.Seek(-5, CFile::current);
							bytesRead-=5;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 6; ++c)
						{
							if(buffer[i+c] != MAGIC_32[c])
							{
								break;
							}
							else
							{
								if(c == 5)
								{
									dwOffset += i + 10;
									file.Close();
									return dwOffset;
								}
							}
						}
					}
				}
				else if(!isWow && (CAntiSpySettings::GetSuiteType() == CAntiSpySettings::SUITE_TYPE::WINDOWS_VISTA))
				{
					if(buffer[i] == VISTA_MAGIC_32[0])
					{
						if(i>= (bytesRead - 8))
						{
							int pos = file.GetPosition();
							file.Seek(-8, CFile::current);
							bytesRead-=8;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 9; ++c)
						{
							if(buffer[i+c] != VISTA_MAGIC_32[c])
							{
								break;
							}
							else
							{
								if(c == 8)
								{
									dwOffset += i + 9;
									file.Close();
									return dwOffset;
								}
							}
						}
					}
				}
				else if(isWow && (CAntiSpySettings::GetSuiteType() != CAntiSpySettings::SUITE_TYPE::WINDOWS_VISTA))
				{
					if(buffer[i] == MAGIC_64[0])
					{
						if(i>= (bytesRead - 24))
						{
							int pos = file.GetPosition();
							file.Seek(-24, CFile::current);
							bytesRead-=24;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 24; ++c)
						{
							if(buffer[i+c] != MAGIC_64[c])
							{
								break;
							}
							else
							{
								if(c == 23)
								{
									dwOffset += i + 50;
									file.Close();
									return dwOffset;
								}
							}
						}
					}

				}
			}
			dwOffset += bytesRead;
			bytesRead = file.Read(buffer, 1024);
		}
		file.Close();
	}
	return 0;
}
RET_VAL ConnectionLimit::IsVistaPatched(LPCTSTR path)
{
	UnlockFile("c:\\windows\\system32\\drivers\\vga.sys");
	CFile file;
	DWORD dwOffset = 0;
	bool isWow = IsWow64();
	PVOID oldValue = NULL;
	if(isWow)
	{
		MyWow64DisableWow64FsRedirection(&oldValue);
	}

	if(file.Open(path,CFile::modeRead))
	{
		TCHAR patchedChar = 0x90;
		if(isWow)
		{
			MyWow64RevertWow64FsRedirection(oldValue);
		}
		unsigned int bytesRead = 0;
		TCHAR buffer[1024];
		bytesRead = file.Read(buffer, 1024);
		while(bytesRead != 0)
		{
			for (int i = 0; i<bytesRead; ++i)
			{
				if(!isWow)
				{

					if(buffer[i] == VISTA_MAGIC_32[0])
					{
						if(i>= (bytesRead - 8))
						{
							int pos = file.GetPosition();
							file.Seek(-8, CFile::current);
							bytesRead-=8;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 9; ++c)
						{
							if(buffer[i+c] != VISTA_MAGIC_32[c])
							{
								break;
							}
							else
							{
								if(c == 8)
								{
									dwOffset += i + 9;
									bool patched = true;
									for(int p = 0; p < 6; ++p)
									{
										if(buffer[i+9+p] != patchedChar)
											patched = false;
									}
									file.Close();
									if(patched)
										return RET_YES;
									else
										return RET_NO;
									//return dwOffset;
								}
							}
						}
					}
				}
				else
				{
					if(buffer[i] == MAGIC_64[0])
					{
						if(i>= (bytesRead - 24))
						{
							int pos = file.GetPosition();
							file.Seek(-24, CFile::current);
							bytesRead-=24;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 24; ++c)
						{
							if(buffer[i+c] != MAGIC_64[c])
							{
								break;
							}
							else
							{
								if(c == 23)
								{
									dwOffset += i + 50;
									file.Close();
									//return dwOffset;
								}
							}
						}
					}

				}
			}
			dwOffset += bytesRead;
			bytesRead = file.Read(buffer, 1024);
		}
		file.Close();
	}
	return RET_ERROR;

}
Exemple #18
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;
}
Exemple #19
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;
}
Exemple #20
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;
}
Exemple #21
0
BOOL CWindowsMetaFile::GetMetaFile(LPCSTR pszFileName, ALDUS_WMF_HEADER* pAldusHeader, METAHEADER* pHeader, HMETAFILE* phMetaFile)
{
	BOOL fSuccess = FALSE;
	
	ASSERT(pszFileName != NULL);
	
	// Create the file we will be using.

	CFile File;

	// Attempt to open the file.

	if (File.Open(pszFileName, CFile::modeRead | CFile::shareDenyWrite))
	{
		ALDUS_WMF_HEADER AldusHeader;

		// Read the Aldus header.

		if (File.Read(&AldusHeader, sizeof(AldusHeader)) == sizeof(AldusHeader))
		{
			// Save the Aldus header if the user has requested it.
					
			if (pAldusHeader != NULL)
			{
				*pAldusHeader = AldusHeader;
			}
						
			// Validate the header.

			if (AldusHeader.key == ALDUS_WMF_KEY)
			{
				// If the user has only requested the Aldus header, stop and return TRUE.
				
				fSuccess = (pHeader == NULL) && (phMetaFile == NULL);
				
				if (!fSuccess)
				{
					// Read the metafile header.
	
					METAHEADER Header;
	
					DWORD dwPosition = File.GetPosition();
	
					if (File.Read(&Header, sizeof(Header)) == sizeof(Header))
					{
						// Save the metafile header if the user has requested it.
							
						if (pHeader != NULL)
						{
							*pHeader = Header;
						}
						
						// If the user does not want a metafile handle, stop and return TRUE.
						
						fSuccess = phMetaFile == NULL;
								
						if (!fSuccess)
						{
							*phMetaFile = NULL;
								
							// Get the size from the metafile header.
							
							DWORD dwSize = Header.mtSize*2;
							
							if (dwSize != 0)
							{
								// Allocate the memory to hold the metafile data.
									
								HGLOBAL hMetaFileData;
									
								hMetaFileData = GlobalAlloc(GMEM_MOVEABLE|GMEM_SHARE, dwSize);
									
								if (hMetaFileData != NULL)
								{
									LPVOID pMetaFileData;
										
									pMetaFileData = GlobalLock(hMetaFileData);
										
									if (pMetaFileData != NULL)
									{
										// Seek back to the start of the metafile header.
										
										File.Seek(dwPosition, CFile::begin);

										// Read the metafile data.
										
										if (File.ReadHuge(pMetaFileData, dwSize) == dwSize)
										{
											// We have now read the data, make a metafile from it.
	
#ifdef WIN32
											*phMetaFile = ::SetMetaFileBitsEx(dwSize, (LPBYTE)pMetaFileData);
#else
											*phMetaFile = ::SetMetaFileBits(hMetaFileData);
#endif
											fSuccess = *phMetaFile != NULL;
										}

#ifdef WIN32
										GlobalUnlock(hMetaFileData);
										pMetaFileData = NULL;
#else
										if (*phMetaFile == NULL)
										{
											GlobalUnlock(hMetaFileData);
											pMetaFileData = NULL;
										}
#endif
									}
#ifdef WIN32
									GlobalFree(hMetaFileData);
									hMetaFileData = NULL;
#else
									if (*phMetaFile == NULL)
									{
										GlobalFree(hMetaFileData);
										hMetaFileData = NULL;
									}
#endif
								}
							}
						}
					}
				}
			}
		}
	}

	return fSuccess;
}
Exemple #22
0
//上传头像
bool CDataBaseSink::OnRequestUploadFace(WORD wRequestID, DWORD dwContextID, VOID * pData, WORD wDataSize)
{
	//数据验证
	ASSERT(wDataSize==sizeof(DBR_GP_UploadCustomFace));
	if (wDataSize!=sizeof(DBR_GP_UploadCustomFace)) return false;

	//数据转换
	DBR_GP_UploadCustomFace *pUploadCustomFace = (DBR_GP_UploadCustomFace*)pData;

	//文件定义
	CFile fileCustomFace;
	TCHAR szFileName[128];
	_snprintf(szFileName, CountArray(szFileName), TEXT("%s\\UploadFile_%ld.zip"), theApp.m_szDirWork, pUploadCustomFace->dwUserID);

	try
	{
		if ( fileCustomFace.Open( szFileName, CFile::modeRead|CFile::typeBinary) )
		{
			BYTE cbCustomFaceData[1024*30];

			//读取文件
			UINT uReadSize = fileCustomFace.Read(cbCustomFaceData, CountArray(cbCustomFaceData));

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

			LONG lRet=-1;
			try
			{
				lRet = SPUploadFace(pUploadCustomFace->dwUserID, cbCustomFaceData, uReadSize);
			}
			catch (IDataBaseException * pIException)
			{
				//错误信息
				LPCTSTR pszDescribe=pIException->GetExceptionDescribe();
				CTraceService::TraceString(pszDescribe,TraceLevel_Exception);
			}

			//成功判断
			if ( lRet != -1 )
			{
				DBR_GP_UploadFaceResult UploadFaceResult;
				ZeroMemory(&UploadFaceResult, sizeof(UploadFaceResult));
				lstrcpyn(UploadFaceResult.szDescribeMsg, TEXT("头像上传成功!"), CountArray(UploadFaceResult.szDescribeMsg));
				UploadFaceResult.dwFaceVer=lRet;
				UploadFaceResult.bOperateSuccess=true;

				m_pIDataBaseEngineEvent->OnEventDataBaseResult(DBR_GP_UPLOAD_FACE_RESULT,dwContextID,
					&UploadFaceResult,sizeof(UploadFaceResult));
			}
			else
			{
				//操作失败
				DBR_GP_UploadFaceResult UploadFaceResult;
				ZeroMemory(&UploadFaceResult, sizeof(UploadFaceResult));
				lstrcpyn(UploadFaceResult.szDescribeMsg, TEXT("由于数据库操作异常,请重新上传!"), CountArray(UploadFaceResult.szDescribeMsg));
				UploadFaceResult.bOperateSuccess=false;

				m_pIDataBaseEngineEvent->OnEventDataBaseResult(DBR_GP_UPLOAD_FACE_RESULT,dwContextID,
					&UploadFaceResult,sizeof(UploadFaceResult));
			}

			//删除文件
			CFile::Remove(szFileName);
		}
	}catch(...){}	

	return true;
}
Exemple #23
0
//from emule
void DonkeyFile::CreateHashFromInput(FILE* file,CFile* file2, int Length, byte* Output, byte* in_string)
{
    // time critial
    md4clr(Output);
    bool PaddingStarted = false;
    UINT Hash[4];
    Hash[0] = 0x67452301;
    Hash[1] = 0xEFCDAB89;
    Hash[2] = 0x98BADCFE;
    Hash[3] = 0x10325476;
    CFile* data = 0;
    if (in_string)
        data = new CMemFile(in_string,Length);
    UINT Required = Length;
    byte   X[64*128];
    while (Required >= 64) {
        UINT len = Required / 64;
        if (len > sizeof(X)/(64 * sizeof(X[0])))
            len = sizeof(X)/(64 * sizeof(X[0]));
        if (in_string)
            data->Read(&X,len*64);
        else if (file)
            fread(&X,len*64,1,file);
        else if (file2)
            file2->Read(&X,len*64);
        for (UINT i = 0; i < len; i++)
        {
            MD4Transform(Hash, (UINT*)(X + i*64));
        }
        Required -= len*64;
    }
    // bytes to read
    Required = Length % 64;
    if (Required != 0) {
        if (in_string)
            data->Read(&X,Required);
        else if (file)
            fread(&X,Required,1,file);
        else if (file2)
            file2->Read(&X,Required);
    }
    // in byte scale 512 = 64, 448 = 56
    if (Required >= 56) {
        X[Required] = 0x80;
        PaddingStarted = TRUE;
        memset(&X[Required + 1], 0, 63 - Required);
        MD4Transform(Hash, (UINT*)X);
        Required = 0;
    }
    if (!PaddingStarted)
        X[Required++] = 0x80;
    memset(&X[Required], 0, 64 - Required);
    // add size (convert to bits)
    UINT Length2 = Length >> 29;
    Length <<= 3;
    memcpy(&X[56], &Length, 4);
    memcpy(&X[60], &Length2, 4);
    MD4Transform(Hash, (UINT*)X);
    md4cpy(Output, Hash);
    if(data!=NULL) {
        delete data;
    }
    //safe_delete(data);
}
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

}
Exemple #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();
}
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


}
Exemple #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 );
}
Exemple #28
0
/*
 * reads n tRobotInfo structs from a CFile
 */
int ReadRobotInfos (CArray<tRobotInfo>& botInfo, int n, CFile& cf, int o)
{
	int h, i, j;

for (i = 0; i < n; i++) {
	h = i + o;
	botInfo [h].nModel = cf.ReadInt ();
	for (j = 0; j < MAX_GUNS; j++)
		cf.ReadVector (botInfo [h].gunPoints [j]);
	cf.Read (botInfo [h].gunSubModels, MAX_GUNS, 1);

	botInfo [h].nExp1VClip = cf.ReadShort ();
	botInfo [h].nExp1Sound = cf.ReadShort ();
	botInfo [h].nExp2VClip = cf.ReadShort ();
	botInfo [h].nExp2Sound = cf.ReadShort ();
	botInfo [h].nWeaponType = cf.ReadByte ();
	botInfo [h].nSecWeaponType = cf.ReadByte ();
	botInfo [h].nGuns = cf.ReadByte ();
	botInfo [h].containsId = cf.ReadByte ();
	botInfo [h].containsCount = cf.ReadByte ();
	botInfo [h].containsProb = cf.ReadByte ();
	botInfo [h].containsType = cf.ReadByte ();
	botInfo [h].kamikaze = cf.ReadByte ();
	botInfo [h].scoreValue = cf.ReadShort ();
	botInfo [h].badass = cf.ReadByte ();
	botInfo [h].energyDrain = cf.ReadByte ();
	botInfo [h].lighting = cf.ReadFix ();
	botInfo [h].strength = cf.ReadFix ();
	botInfo [h].mass = cf.ReadFix ();
	botInfo [h].drag = cf.ReadFix ();

	for (j = 0; j < NDL; j++)
		botInfo [h].fieldOfView [j] = cf.ReadFix ();
	for (j = 0; j < NDL; j++)
		botInfo [h].primaryFiringWait [j] = cf.ReadFix ();
	for (j = 0; j < NDL; j++)
		botInfo [h].secondaryFiringWait [j] = cf.ReadFix ();
	for (j = 0; j < NDL; j++)
		botInfo [h].turnTime [j] = cf.ReadFix ();
	for (j = 0; j < NDL; j++)
		botInfo [h].xMaxSpeed [j] = cf.ReadFix ();
	for (j = 0; j < NDL; j++)
		botInfo [h].circleDistance [j] = cf.ReadFix ();
	cf.Read (botInfo [h].nRapidFireCount, NDL, 1);
	cf.Read (botInfo [h].evadeSpeed, NDL, 1);
	botInfo [h].cloakType = cf.ReadByte ();
	botInfo [h].attackType = cf.ReadByte ();
	botInfo [h].seeSound = cf.ReadByte ();
	botInfo [h].attackSound = cf.ReadByte ();
	botInfo [h].clawSound = cf.ReadByte ();
	botInfo [h].tauntSound = cf.ReadByte ();
	botInfo [h].bossFlag = cf.ReadByte ();
	botInfo [h].companion = cf.ReadByte ();
	botInfo [h].smartBlobs = cf.ReadByte ();
	botInfo [h].energyBlobs = cf.ReadByte ();
	botInfo [h].thief = cf.ReadByte ();
	botInfo [h].pursuit = cf.ReadByte ();
	botInfo [h].lightcast = cf.ReadByte ();
	botInfo [h].bDeathRoll = cf.ReadByte ();
	botInfo [h].flags = cf.ReadByte ();
	cf.Read(botInfo [h].pad, 3, 1);
	botInfo [h].deathrollSound = cf.ReadByte ();
	botInfo [h].glow = cf.ReadByte ();
	botInfo [h].behavior = cf.ReadByte ();
	botInfo [h].aim = cf.ReadByte ();
	for (j = 0; j < MAX_GUNS + 1; j++)
		ReadJointLists (botInfo [h].animStates [j], N_ANIM_STATES, cf);
	botInfo [h].always_0xabcd = cf.ReadInt ();
	}
return i;
}
Exemple #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;
}
Exemple #30
0
void CObject::LoadState (CFile& cf)
{
info.nSignature = cf.ReadInt ();      
info.nType = (ubyte) cf.ReadByte (); 
info.nId = (ubyte) cf.ReadByte ();
info.nNextInSeg = cf.ReadShort ();
info.nPrevInSeg = cf.ReadShort ();
info.controlType = (ubyte) cf.ReadByte ();
info.movementType = (ubyte) cf.ReadByte ();
info.renderType = (ubyte) cf.ReadByte ();
info.nFlags = (ubyte) cf.ReadByte ();
info.nSegment = cf.ReadShort ();
info.nAttachedObj = cf.ReadShort ();
cf.ReadVector (info.position.vPos);     
cf.ReadMatrix (info.position.mOrient);  
info.xSize = cf.ReadFix (); 
info.xShields = cf.ReadFix ();
cf.ReadVector (info.vLastPos);  
info.contains.nType = cf.ReadByte (); 
info.contains.nId = cf.ReadByte ();   
info.contains.nCount = cf.ReadByte ();
info.nCreator = cf.ReadByte ();
info.xLifeLeft = cf.ReadFix ();   
if (info.movementType == MT_PHYSICS) {
	cf.ReadVector (mType.physInfo.velocity);   
	cf.ReadVector (mType.physInfo.thrust);     
	mType.physInfo.mass = cf.ReadFix ();       
	mType.physInfo.drag = cf.ReadFix ();       
	mType.physInfo.brakes = cf.ReadFix ();     
	cf.ReadVector (mType.physInfo.rotVel);     
	cf.ReadVector (mType.physInfo.rotThrust);  
	mType.physInfo.turnRoll = cf.ReadFixAng ();   
	mType.physInfo.flags = (ushort) cf.ReadShort ();      
	}
else if (info.movementType == MT_SPINNING) {
	cf.ReadVector (mType.spinRate);  
	}
switch (info.controlType) {
	case CT_WEAPON:
		cType.laserInfo.parent.nType = cf.ReadShort ();
		cType.laserInfo.parent.nObject = cf.ReadShort ();
		cType.laserInfo.parent.nSignature = cf.ReadInt ();
		cType.laserInfo.xCreationTime = cf.ReadFix ();
		cType.laserInfo.nLastHitObj = cf.ReadShort ();
		if (cType.laserInfo.nLastHitObj < 0)
			cType.laserInfo.nLastHitObj = 0;
		else {
			gameData.objs.nHitObjects [Index () * MAX_HIT_OBJECTS] = cType.laserInfo.nLastHitObj;
			cType.laserInfo.nLastHitObj = 1;
			}
		cType.laserInfo.nHomingTarget = cf.ReadShort ();
		cType.laserInfo.xScale = cf.ReadFix ();
		break;

	case CT_EXPLOSION:
		cType.explInfo.nSpawnTime = cf.ReadFix ();
		cType.explInfo.nDeleteTime = cf.ReadFix ();
		cType.explInfo.nDeleteObj = cf.ReadShort ();
		cType.explInfo.attached.nParent = cf.ReadShort ();
		cType.explInfo.attached.nPrev = cf.ReadShort ();
		cType.explInfo.attached.nNext = cf.ReadShort ();
		break;

	case CT_AI:
		cType.aiInfo.behavior = (ubyte) cf.ReadByte ();
		cf.Read (cType.aiInfo.flags, 1, MAX_AI_FLAGS);
		cType.aiInfo.nHideSegment = cf.ReadShort ();
		cType.aiInfo.nHideIndex = cf.ReadShort ();
		cType.aiInfo.nPathLength = cf.ReadShort ();
		cType.aiInfo.nCurPathIndex = cf.ReadByte ();
		cType.aiInfo.bDyingSoundPlaying = cf.ReadByte ();
		cType.aiInfo.nDangerLaser = cf.ReadShort ();
		cType.aiInfo.nDangerLaserSig = cf.ReadInt ();
		cType.aiInfo.xDyingStartTime = cf.ReadFix ();
		break;

	case CT_LIGHT:
		cType.lightInfo.intensity = cf.ReadFix ();
		break;

	case CT_POWERUP:
		cType.powerupInfo.nCount = cf.ReadInt ();
		cType.powerupInfo.xCreationTime = cf.ReadFix ();
		cType.powerupInfo.nFlags = cf.ReadInt ();
		break;
	}
switch (info.renderType) {
	case RT_MORPH:
	case RT_POLYOBJ: {
		int i;
		rType.polyObjInfo.nModel = cf.ReadInt ();
		for (i = 0; i < MAX_SUBMODELS; i++)
			cf.ReadAngVec (rType.polyObjInfo.animAngles [i]);
		rType.polyObjInfo.nSubObjFlags = cf.ReadInt ();
		rType.polyObjInfo.nTexOverride = cf.ReadInt ();
		rType.polyObjInfo.nAltTextures = cf.ReadInt ();
		break;
		}
	case RT_WEAPON_VCLIP:
	case RT_HOSTAGE:
	case RT_POWERUP:
	case RT_FIREBALL:
	case RT_THRUSTER:
		rType.vClipInfo.nClipIndex = cf.ReadInt ();
		rType.vClipInfo.xFrameTime = cf.ReadFix ();
		rType.vClipInfo.nCurFrame = cf.ReadByte ();
		break;

	case RT_LASER:
		break;
	}
}