BOOL CNetRssProtocol::Start()
{
	bStarted=1;
	CString sFile=GetUserFolder()+"RssLatest.txt";
	if(isFileExist(sFile)){
		CFile file(sFile, CFile::modeRead);	// создать файл
		CArchive ar(&file, CArchive::load);
		aLoadedRss.Serialize(ar);
    }
	return TRUE;
}
Example #2
0
PRGINTERFACE_API void  DataIntegrateForCheck(CMapStringToString &mstr, int indexmax, bool colormark)
{
	g_jherr.Empty();
	
	for(int cnt = 31; cnt <= 40; cnt++){
		CString err;
		if(CHECK_REC_FAIL == sjCheckOneRecord(g_Cfg,sizeof(g_Cfg)/sizeof(PRECBASE2),mstr,cnt,colormark,false,err,false))
			g_jherr += err;
	}
	mstr.SetAt("jdjg",g_jherr);//检定结果
}
Example #3
0
PRGINTERFACE_API void DataIntegrateForCompensate(CMapStringToString &mstr,int indexmax)
{
	g_jherr.Empty();
	
	for(int cnt = 1; cnt <= 400; cnt++){
		CString err;
		if(CHECK_REC_FAIL == sjCheckOneRecordFull(g_Cfg,sizeof(g_Cfg)/sizeof(PRECBASE2),mstr,cnt,true,true,err,false,true))
			g_jherr += err;
	}
	mstr.SetAt("jdjg",g_jherr);//检定结果
}
Example #4
0
CString CDownloadManager::GetDownloadDirectory(const CMapStringToString& mapSharedPaths)
{
	CString csDirectory;
	if (!mapSharedPaths.Lookup("online", csDirectory))
	{
		CString csProgramFilesDir;
		Util::GetProgramFilesDir(csProgramFilesDir);
		Util::ConstructPath(csDirectory, csProgramFilesDir, "Mindscape\\Online");
	}
	return csDirectory;
}
Example #5
0
PRGINTERFACE_API void DataIntegrateForCompensate(CMapStringToString &mstr,int indexmax)
{
	CString perrecord;
	int ipos = indexmax;
	zero = 0.0;
	if(mstr.Lookup(_T("Z19"),perrecord) && (perrecord.FindOneOf("0123456789") >= 0)){
		zero = atof(perrecord);
	}
	z14 = 0;
	if(mstr.Lookup(_T("Z14"),perrecord) && (perrecord.FindOneOf("0123456789") >= 0)){
		z14 = atoi(perrecord);
	}
	
	while(ipos-- > 0)
	{
		CString sid;
		double accuracy;
		sid.Format("Z%d",ipos);
		if(mstr.Lookup(sid,perrecord) && (perrecord.FindOneOf("0123456789") >= 0))
		{
			if(perrecord.Find("--") >= 0)
				continue;
			sid.Format("jhsel%d",INDEX2GROUP(ipos));
			if(!mstr.Lookup(sid,sid) || sid.FindOneOf("0123456789") < 0)		continue;//retrieve the jhsel
			
			accuracy = atof(sid)/100.0;
			
			int iid = CheckPrecious(sid);
			if(iid < 0)		continue;//translate the jhsel
			perrecord = DataIntergrate(ipos,atof(perrecord),g_PrecBase[iid].iDigipos-2,g_PrecBase[iid].iMantissa);
			sid=SJD2SByPosition(GetDiffData(ipos,atof(perrecord),accuracy),INDEX2GROUP(ipos)+g_PrecBase[iid].iDigipos-3);
			if(!CheckData(ipos,atof(perrecord),accuracy))
			{
				sid = "<font color='red'>"+sid+"</font>";
			}
			perrecord = sid;
			sid.Format("Z%d",ipos);
			mstr.SetAt(sid,perrecord);
		}
	}
}
Example #6
0
DWORD CHttpClient::WGet( LPCTSTR lpszRegCode, LPCTSTR lpszUserName,
						LPCTSTR lpszPasswd, LPCTSTR lpszVersion,
						CString &strResult, int nWantLen )
{
	CMapStringToString	map;
	map.SetAt( szRegCodeKey, lpszRegCode );
	map.SetAt( szUserNameKey, m_strUserName );
	map.SetAt( szPasswdKey, m_strPasswd );
	map.SetAt( szVersionKey, lpszVersion );
	
	CString	strDiskSerial	=	GetDiskSerial( );
	map.SetAt( szDiskSerialKey, strDiskSerial );
	
	CString	strURL;
	strURL.Format( szHttpURLFormat, m_strServer, m_nPort, szWebpathWGet );

	CString	strResultLocal, strValue;
	DWORD dwRet = RequestPost( strURL, &map, &strResultLocal, NULL, NULL );
	if( HTTP_STATUS_OK == dwRet )
	{
		int	nIndex	=	strResultLocal.Find( szWGetResultKey );
		if( -1 != nIndex )
			strValue	=	strResultLocal.Mid( nIndex+strlen(szWGetResultKey), nWantLen );
	}
	if( strValue.GetLength() == nWantLen )
	{
		strResult	=	strValue;
		return dwRet;
	}
	return dwRet;
}
Example #7
0
BOOL CConfigLoader::SaveConfig( CString szSection, CString szFileName )
{
	if( szFileName.GetLength() > 0 )
		m_szFileName = szFileName;

	CString szKey;
	CString szValue;
	POSITION posKey = NULL;

	CMapStringToString *lpKeyMap = NULL;
	if( m_SectionMap.Lookup( szSection, lpKeyMap ) )
	{
		posKey = lpKeyMap->GetStartPosition();
		while(posKey)
		{
			lpKeyMap->GetNextAssoc( posKey, szKey, szValue );
			WritePrivateProfileString( szSection, szKey, szValue, m_szFileName );
		}
	}

	return TRUE;
}
Example #8
0
CString ExtractTag(CString tag, CMapStringToString& attribs, bool& fClosing)
{
    tag.Trim();
    attribs.RemoveAll();

    fClosing = !tag.IsEmpty() ? tag[0] == '/' : false;
    tag.TrimLeft('/');

    int i = tag.Find(' ');
    if (i < 0) {
        i = tag.GetLength();
    }
    CString type = tag.Left(i).MakeLower();
    tag = tag.Mid(i).Trim();

    while ((i = tag.Find('=')) > 0) {
        CString attrib = tag.Left(i).Trim().MakeLower();
        tag = tag.Mid(i + 1);
        for (i = 0; i < tag.GetLength() && _istspace(tag[i]); i++) {
            ;
        }
        tag = i < tag.GetLength() ? tag.Mid(i) : _T("");
        if (!tag.IsEmpty() && tag[0] == '\"') {
            tag = tag.Mid(1);
            i = tag.Find('\"');
        } else {
            i = tag.Find(' ');
        }
        if (i < 0) {
            i = tag.GetLength();
        }
        CString param = tag.Left(i).Trim();
        if (!param.IsEmpty()) {
            attribs[attrib] = param;
        }
        tag = i + 1 < tag.GetLength() ? tag.Mid(i + 1) : _T("");
    }

    return type;
}
Example #9
0
PRGINTERFACE_API void  DataIntegrateForCheck(CMapStringToString &mstr, int indexmax, bool colormark)
{
	CString perrecord;
	CString jherr("");
	int ipos = indexmax;

	zero = 0.0;
	if(mstr.Lookup(_T("Z19"),perrecord) && (perrecord.FindOneOf("0123456789") >= 0)){
		zero = atof(perrecord);
	}
	z14 = 0;
	if(mstr.Lookup(_T("Z14"),perrecord) && (perrecord.FindOneOf("0123456789") >= 0)){
		z14 = atoi(perrecord);
	}
	while(ipos-- > 0)
	{
		CString sid;
		double accuracy;
		sid.Format("Z%d",ipos);
		if(mstr.Lookup(sid,perrecord) && (perrecord.FindOneOf("0123456789") >= 0))
		{
			if(perrecord.Find("--") >= 0)
				continue;
			sid.Format("jhsel%d",INDEX2GROUP(ipos));
			if(!mstr.Lookup(sid,sid) || (sid.FindOneOf("0123456789") < 0) )		continue;//retrieve the jhsel
						
			accuracy = atof(sid)/100.0;
			
			int iid = CheckPrecious(sid);
			if(iid < 0)		continue;//translate the jhsel//translate the jhsel
			perrecord = DataIntergrate(ipos,atof(perrecord),g_PrecBase[iid].iDigipos-2,g_PrecBase[iid].iMantissa);
			if((!CheckData(ipos,atof(perrecord),accuracy)))
			{
				//add the a message to the error
				CString stmp;
				stmp.Format("%s盘第%d点不合格;\n",Panhao[INDEX2GROUP(ipos)],INDEX2REST(ipos));
				jherr += stmp;
				if(colormark)
					perrecord = "<font color='red'>"+perrecord+"</font>";
			}
			sid.Format("Z%d",ipos);
			mstr.SetAt(sid,perrecord);
		}

	}
	mstr.SetAt("jdjg",jherr);//检定结果
}
Example #10
0
BOOL MR_ReadPredefinedConstants(const char *pFileName)
{
	BOOL lReturnValue = TRUE;
	FILE *lFile = fopen(pFileName, "r");

	if(lFile == NULL) {
		lReturnValue = FALSE;

		fprintf(stderr, "ERROR: Unable to open %s(defines file)\n", pFileName);
	}
	else {
		char lBuffer[250];
		while(lReturnValue && fgets(lBuffer, sizeof(lBuffer), lFile)) {
			CString lLine = MR_PreProcLine(lBuffer);

			if(MR_BeginByKeyword(lLine, "#define")) {
				char lKey[100];
				char lValue[100];

				if(sscanf(lLine, " #define %s %s ", lKey, &lValue) != 2) {
					lReturnValue = FALSE;

					fprintf(stderr, "ERROR: syntax error in defines file\n");

				}
				else {
					// add the define to the list
					gDefineMap.SetAt(lKey, lValue);
				}
			}
		}

		fclose(lFile);
	}

	return lReturnValue;
}
Example #11
0
HRESULT GetRibbonText(BSTR * RibbonXml)
{
	LPBYTE content = NULL;
	DWORD content_length = 0;

	ASSERT_RETURN_VALUE(LoadResourceFromModule(
		AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_RESOURCE_H), L"TEXT", &content, &content_length), S_FALSE);

	CMemFile mf(content, content_length);
	CTextFileRead rdr(&mf);

	CMapStringToString replacements;

	CString line;
	while (rdr.ReadLine(line))
	{
		CSimpleArray<CString> tokens;

		CString token;
		token.Preallocate(30);

		for (LPCWSTR pos = line; *pos; ++pos)
		{
			if (*pos == ' ' || *pos == '\t')
			{
				if (!token.IsEmpty())
				{
					tokens.Add(token);
					token = CString();
				}
			}
			else
			{
				token += *pos;
			}
		}

		if (!token.IsEmpty())
			tokens.Add(token);

		if (tokens.GetSize() != 3)
			continue;

		if (tokens[0] != "#define")
			continue;

		replacements[tokens[1]] = tokens[2];
	}

	CString ribbon = LoadTextFromModule(AfxGetInstanceHandle(), IDR_RIBBON);

	for (int pos = 0; pos < ribbon.GetLength(); ++pos)
	{
		if (ribbon[pos] != '{')
			continue;

		int endpos = ribbon.Find('}', pos);
		ASSERT_CONTINUE(endpos != -1);

		CString token = ribbon.Mid(pos+1, endpos-pos-1);
		CString token_found;

		ASSERT_CONTINUE(replacements.Lookup(token, token_found));	

		ribbon.Delete(pos, endpos-pos+1);
		ribbon.Insert(pos, token_found);

		pos += (token_found.GetLength()-1);
	}

	*RibbonXml = ribbon.AllocSysString();
	return S_OK;
}
CString GetNDCRulFile(CString& sNDC,CString& sMobnum,DWORD& dwMaxLen)
{
	dwMaxLen=0;
	static CFileInfoArray dir;
	static BOOL bAdded=0;
	static CMapStringToString aNDCIndex;
	if(bAdded==0){
		bAdded=1;
		dir.AddDir(GetAppFolder()+"Sms/","*.rul",TRUE,0,FALSE);
		for(int i=0;i<dir.GetSize();i++){
			CString sItemPath=dir[i].GetFilePath();
			CString sContent;
			ReadFile(sItemPath,sContent);
			sContent.Replace("\r","");
			sContent+="\n";
			CString sLen=CDataXMLSaver::GetInstringPart("SmsMaxLength=","\n",sContent);
			CString sNDCs=CDataXMLSaver::GetInstringPart("SmsNdcList=","\n",sContent);
			CString sName=CDataXMLSaver::GetInstringPart("WndTitle=","\n",sContent);
			if(sNDCs!=""){
				CStringArray aNDCs;
				ConvertToArray(sNDCs,aNDCs,',');
				for(int j=0;j<aNDCs.GetSize();j++){
					CString sOld=aNDCIndex[aNDCs[j]];
					if(sOld!=""){
						sOld+="|";
					}
					sOld+=sItemPath+"\t"+sLen+"\t"+sName;
					aNDCIndex.SetAt(aNDCs[j],sOld);
				}
			}
		}
	}
	CString sNDCData=aNDCIndex[sNDC];
	if(sNDCData.Find("|")!=-1){
		// Выбор :(
		CStringArray aOperators;
		ConvertToArray(sNDCData,aOperators,'|');
		CStringArray aOperatorsNames;
		int i=0;
		for(i=0;i<aOperators.GetSize();i++){
			CStringArray aDats;
			ConvertToArray(aOperators[i],aDats,'\t');
			if(aDats.GetSize()>=3){
				aOperatorsNames.Add(aDats[2]);
			}
		}
		i=SelectFromMenu(aOperatorsNames,0);
		if(i>=0){
			sNDCData=aOperators[i];
		}else{
			return "000";
		}
	}
	if(sNDCData!=""){
		CStringArray aDats;
		ConvertToArray(sNDCData,aDats,'\t');
		if(aDats.GetSize()>=2){
			dwMaxLen=atol(aDats[1]);
			return aDats[0];
		}
	}
	// Доверяем гуглу?
	CString sRetFile=GetAppFolder()+"Sms/default.rul";
	if(isFileExist(sRetFile)){
		CString sContent;
		ReadFile(sRetFile,sContent);
		CString sCList=CDataXMLSaver::GetInstringPart("SmsCarriersList=","\n",sContent);
		CStringArray aCarriers;
		ConvertToArray(sCList,aCarriers,',');
		int i=SelectFromMenu(aCarriers,0);
		if(i>0){
			dwMaxLen=1000;
			sMobnum=sNDC+sMobnum;
			sNDC=Format("%i",i);
			return sRetFile;
		}
		if(i<0){
			return "000";
		}
	}
	return "";
}
BOOL CNetRssProtocol::SendNet_StatusExch(const char* szRec,const char* szProtocol)
{
	if(CString(szProtocol)=="sms"){
		return 1;
	}
	if(objSettings.lRSSLocUser){
		if(isScreenSaverActiveOrCLocked()){
			return -1;
		}
	}
	CString szRecipient=GetCompNameNoProtocol(szRec);
	int iPerson=objSettings.AddrBook.FindPersonByIP(szRecipient,TRUE);
	if(iPerson!=-1){
		if(objSettings.AddrBook.aPersons[iPerson]->IsGroup()){
			// Групповой-заблокирован
			return -1;
		};
	}
	CWebWorld url;
	CString sRSS=url.GetWebPage(szRecipient);
	if(sRSS==""){
		// Не доступен
		return -1;
	}
	#ifdef _DEBUG
	CString sFile=CString("lastblog")+szRecipient+".xml";//http://davydov.blogspot.com/atom.xml
	MakeSafeFileName(sFile);
	SaveFile(CString("c://")+sFile,sRSS);
	#endif
	int iStatus=1;
	XDoc* feedDoc=parseXML(sRSS);
	XNode* feed=0;
	if(feedDoc){
		feed=feedDoc->GetRoot();
		if(!feed){
			delete feedDoc;
			return -1;
		}
		CString sLnewsBuildDate=aLoadedRss[szRecipient];
		int iMaxNews=objSettings.dwProtocolRSSMAxNews;
		if(sLnewsBuildDate==""){
			iMaxNews=5;
		}
		CString sLnewsBuildDateToSet="";
		BOOL bAtom=0;
		CString sGlobalTitle;
		if(feed->GetChild("channel",1)==GetEmptyNode() && feed->GetChild("title",1)!=GetEmptyNode()){
			// Atom!!!
			bAtom=1;
			sGlobalTitle=feed->GetChild("title",1)->value;
		}else{
			sGlobalTitle=feed->GetChild("channel",1)->GetChild("title",1)->value;
		}
		CString sFrom="";
		if(iPerson!=-1){
			sFrom=objSettings.AddrBook.aPersons[iPerson]->GetTitle();
		}else{
			sFrom=sGlobalTitle+"/rss";
		}
		CXMLNodes feedItems;
		if(bAtom){
			feed->FindByTagName("entry",FALSE,feedItems);
		}else{
			feed->GetChild("channel",1)->FindByTagName("item",FALSE,feedItems);
		}
		int iCount=0;
		int iLenCount=feedItems.GetSize();
		if(iLenCount==0){
			// Может rdf???
			feed->FindByTagName("item",FALSE,feedItems);
			iLenCount=feedItems.GetSize();
		}
		CString sSummary;
		while(iCount<iLenCount && iCount<iMaxNews){
			XNode* item=feedItems[iCount];
			CString sPubDate;
			if(bAtom){
				sPubDate=item->GetChild("issued",1)->value;
			}else{
				sPubDate=item->GetChild("pubDate",1)->value;
				if(sPubDate==""){
					//rdf???
					sPubDate=item->GetChild("dc:date",1)->value;
				}
			}
			//sPubDate=UnescapeString(sPubDate);
			StripTags(sPubDate);
			DeEntitize(sPubDate);

			CString sTitle;
			sTitle=item->GetChild("title",1)->value;
			//sTitle=UnescapeString(sTitle);
			StripTags(sTitle);
			DeEntitize(sTitle);
			if(sTitle==""){
				sTitle=sGlobalTitle;
			}
			
			CString sAuthor;
			if(bAtom){
				LPXNode pAut;
				pAut=item->GetChild("author",1);
				if(pAut->iBeginPos!=-1 && pAut->iEndPos!=-1){
					sAuthor=sRSS.Mid(pAut->iBeginPos,pAut->iEndPos-pAut->iBeginPos);
				}
			}else{
				sAuthor=item->GetChild("author",1)->value;
				if(sAuthor==""){
					//rdf???
					sAuthor=item->GetChild("dc:creator",1)->value;
				}
			}
			//sAuthor=UnescapeString(sAuthor);
			StripTags(sAuthor);
			DeEntitize(sAuthor);
			if(sAuthor!=""){
				sTitle+=" (";
				sTitle+=sAuthor;
				sTitle+=")";
			}
			
			LPXNode pDesk;
			if(bAtom){
				pDesk=item->GetChild("content",1);
			}else{
				pDesk=item->GetChild("description",1);
			}
			CString sDesk;
			if(pDesk->iBeginPos!=-1 && pDesk->iEndPos!=-1){
				sDesk=sRSS.Mid(pDesk->iBeginPos,pDesk->iEndPos-pDesk->iBeginPos);
			}
			/*
			if(sDesk.Find("%20")!=-1){
				sDesk=UnescapeString(sDesk);
			}
			*/
			CString sDeskL=sDesk;
			sDeskL.MakeLower();
			if(sDeskL.Find(";div")!=-1 || sDeskL.Find(";span")!=-1){
				// Для извращенных...
				DeEntitize(sDesk);
				StripTags(sDesk);
			}else{
				// Это по правильному
				StripTags(sDesk);
				DeEntitize(sDesk);
			}
			sDesk.TrimLeft();
			sDesk.TrimRight();

			CString sLink;
			if(bAtom){
				CXMLNodes feedLinks;
				item->FindByTagName("link",FALSE,feedLinks);
				for(int j=0;j<feedLinks.GetSize();j++){
					XNode* itemLnk=feedLinks[j];
					sLink=itemLnk->GetAttr("href")->value;
					CString sType=itemLnk->GetAttr("type")->value;
					sType.MakeLower();
					if(sType.Find("text")!=-1){
						break;// Наша линка!
					}
				}
			}else{
				sLink=item->GetChild("link",1)->value;
			}
			sLink=UnescapeString(sLink);
			StripTags(sLink);
			DeEntitize(sLink);
			sLink.TrimLeft();
			sLink.TrimRight();
			
			{
				CSmartLock SL(&csRssFeeds,TRUE);
				CString sRnewsBuildDate=sLink+"\t"+sPubDate+" "+sTitle+" "+sDesk;
				if(sLnewsBuildDate==sRnewsBuildDate){
					if(iCount==0){
						iStatus=1;
					}
					break;
				}
				if(sLnewsBuildDateToSet==""){// Запомнили самую первую новость
					sLnewsBuildDateToSet=sRnewsBuildDate;
				}
				/*
				#ifdef _DEBUG
				else{
					sDesk+="\nOld id-text:"+sLnewsBuildDate;
					sDesk+="\nNew id-text:"+sRnewsBuildDate;
				}
				#endif
				*/
			}

			if(sPubDate!=""){
				COleDateTime dt;
				dt.ParseDateTime(sPubDate);
				if(dt.GetStatus()==COleDateTimeSpan::valid){
					sTitle=dt.Format("%x %X. ")+sTitle;
				}
			}
			CString sNews=sTitle;
			sNews+="\n";
			if(sDesk!=""){
				sNews+="\n";
				sNews+=sDesk;
			}
			if(sLink!=""){
				sNews+="\n\n";
				sNews+=_l("Read more")+": ";
				sNews+=sLink;
			}
			CDataXMLSaver::Xml2Str(sNews);
			if(objSettings.lRSSSummar){
				sSummary+="\n";
				sSummary+="\n";
				sSummary+=sTitle;
				sSummary+="\n";
				sSummary+=_l("Read more")+": ";
				sSummary+=sLink;
			}else{
				CString sAttach="";
				if(objSettings.dwProtocolRSSOType){
					sAttach+=Format("["DEF_OPENTYPE"%i]",objSettings.dwProtocolRSSOType);
				}
				OpenMessage(sFrom,"",sNews,"",sAttach,sGlobalTitle);
			}
			iCount++;
		}
		if(sSummary!=""){
			CString sAttach="";
			if(objSettings.dwProtocolRSSOType){
				sAttach+=Format("["DEF_OPENTYPE"%i]",objSettings.dwProtocolRSSOType);
			}
			sSummary.TrimLeft();
			OpenMessage(sFrom,"",sSummary,"",sAttach,sGlobalTitle);
		}
		if(feedDoc){
			delete feedDoc;
		}
		if(sLnewsBuildDateToSet!=""){
			aLoadedRss.SetAt(szRecipient,sLnewsBuildDateToSet);
		}
	}
	if(iPerson!=-1){
		objSettings.AddrBook.aPersons[iPerson]->iOnlineStatus=iStatus;
		RefreshUserStatusIcon(iPerson);
	}
	return 0;
}
Example #14
0
PRGINTERFACE_API void  PrepareArrayForReport(CMapStringToString &mstr)
{
	//check the start position of the resister group
	int grpoffset=0;
	CString skey,sval,perrecord;
	zero = 0.0;
	if(mstr.Lookup(_T("Z19"),perrecord) && (perrecord.FindOneOf("0123456789") >= 0)){
		zero = atof(perrecord);
	}
	z14 = 0;
	if(mstr.Lookup(_T("Z14"),perrecord) && (perrecord.FindOneOf("0123456789") >= 0)){
		z14 = atoi(perrecord);
	}

	do{
		skey.Format("Z%d",31+grpoffset++*20);
		if(mstr.Lookup(skey,sval) && sval.FindOneOf("0123456789") >= 0)
			break;
	}while(grpoffset<9);
	
	--grpoffset;
	
				
	for (int grpindex = 0;grpindex < 8;grpindex++){
		skey.Format("Z%d",31+grpindex*20);
		if (mstr.Lookup(skey,sval) && (sval.FindOneOf("0123456789") >= 0) )
		{
			if(sval.FindOneOf("0123456789") != -1)
			{
				skey.Format("Z%d",31+grpindex*20+12);
				mstr.SetAt(skey,CString(Panhao[grpindex]));
				skey.Format("jhsel%d",grpindex);
				if(mstr.Lookup(skey,sval) && (sval.FindOneOf("0123456789") >= 0))
				{
					sval = _T("±")+sval;
					skey.Format("Z%d",31+grpindex*20+13);
					mstr.SetAt(skey,sval);
				}
			}
		}
	}
	return;
	//move the table and insert "/" at corresponding place
	for ( grpindex = 0;grpindex < 8;grpindex++)
		for (int subindex = 0;subindex< 14;subindex++){
			skey.Format("Z%d",31+grpindex*20+subindex);
			if (!mstr.Lookup(skey,sval) || sval.FindOneOf("0123456789") < 0)
				mstr.SetAt(skey,_T("/"));
			else	if(sval.FindOneOf("0123456789") == -1)
				mstr.SetAt(skey,_T("/"));
			else {
				mstr.RemoveKey(skey);
				skey.Format("Z%d",31+(grpindex-grpoffset)*20+subindex);
				mstr.SetAt(skey,sval);
			}
			
		}
}
Example #15
0
// Inserts a video object in MMS message
// Input:	csObjPath=String with file path
void CMMSSender::InsertVideo(CString csObjPath)
{
	CMapStringToString mssContentType;
	mssContentType.SetAt("avi","video/avi");
	mssContentType.SetAt("asf","video/x-ms-asf");
	mssContentType.SetAt("mpg","video/mpeg");
	mssContentType.SetAt("mpeg","video/mpeg");
	mssContentType.SetAt("wmv","video/x-ms-wmv");

	CString csContentType;
	int nPosPunto=csObjPath.ReverseFind('.');
	if(nPosPunto!=-1)
	{
		CString csExtension=csObjPath.Mid(nPosPunto+1);
		mssContentType.Lookup(csExtension,csContentType);

		if(csContentType.IsEmpty())
			return;
	}

	CString csData;
	CString csURL;

	CString csCookie;

	CString csHeaders;
	CString csRetHeaders;
	CString csRetData;

	BYTE* pbtFile=(BYTE*)malloc(OBJ_BUFFER_SIZE);
	memset(pbtFile,0,OBJ_BUFFER_SIZE);

	BYTE* pbtContents=(BYTE*)malloc(OBJ_BUFFER_SIZE);
	memset(pbtContents,0,OBJ_BUFFER_SIZE);
	int nPosicionDatos=0;

	CString csSeparator="---------------------------7d77df567a4b9";

	// Object data generation
	CString csFilenamePart;
	csFilenamePart.Format("--%s\r\nContent-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n",csSeparator,csObjPath,csContentType);
	memcpy(&pbtContents[nPosicionDatos],csFilenamePart.GetBuffer(0),csFilenamePart.GetLength());
	nPosicionDatos+=csFilenamePart.GetLength();

	CFile fl;
	BOOL bRes=fl.Open(csObjPath,CFile::modeRead);
	if(bRes)
	{
		int nLeidos=fl.Read(pbtFile,OBJ_BUFFER_SIZE);
		fl.Close();

		memcpy(&pbtContents[nPosicionDatos],pbtFile,nLeidos);
		nPosicionDatos+=nLeidos;
	}

	CString csFinal;
	csFinal.Format("\r\n--%s--\r\n",csSeparator);
	memcpy(&pbtContents[nPosicionDatos],csFinal.GetBuffer(0),csFinal.GetLength());
	nPosicionDatos+=csFinal.GetLength();

    CString csContentType2;
	csContentType2.Format("multipart/form-data; boundary=%s",csSeparator);
	csHeaders = "Accept-Encoding: gzip, deflate\r\n"
				"Accept-Language: es\r\n"
				"Accept: */*\r\n"
				"Connection: Keep-Alive\r\n";
	csHeaders += "Content-type: "+csContentType2+"\r\n";
	csHeaders += "Cookie: "+m_csCookie+"\r\n";
	csURL.Format("http://%s/do/multimedia/uploadEnd",m_csServer);
	UINT nCode=PostHTTP(csURL,pbtContents,nPosicionDatos,csHeaders,csRetHeaders,csRetData);

	free(pbtFile);
	free(pbtContents);
}
BOOL CCapDownload::retrievePackages()
{
	CString					csCertFile,
		csId,
		csValue;
	COptDownloadPackage		*pOptDownloadPackage;
	CMapStringToStringArray	*pMapArray = NULL;
	CMapStringToString		*pMap = NULL;
	INT_PTR					nPack = 0;

	/***
	*
	* Environnement checking
	*
	***/

	// Working directory
	if (directoryCreate(getDownloadFolder()) == FALSE)
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot create working directory (%s)"), LookupError(GetLastError()));
		return FALSE;
	}
	// Open package history file, create it if needed
	CFilePackageHistory cFileHistory;
	if (!cFileHistory.Open(getPackageHistoryFilename(), FALSE, TRUE))
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot create history file <%>"), getPackageHistoryFilename());
		return FALSE;
	}
	if (!m_pPrologResp->isDownloadRequired())
	{
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => No package available for download"));
		return FALSE;
	}
	// Trying to create suspend Download tool
	if (!suspendDownload())
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot suspend Download and Setup Tool using <%s> file"), OCS_DOWNLOAD_SUSPEND);
		return FALSE;
	}
	// Trying to get exclusive access to download
	if (!lockDownload())
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot lock directory <%s>"), getDownloadFolder());
		resumeDownload();
		return FALSE;
	}
	// Get generic download parameters and write them for using with download tool
	pMapArray = m_pPrologResp->getDownloadParameters();
	if ((pMapArray == NULL) || pMapArray->IsEmpty())
	{
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => No download parameter available"));
		unlockDownload();
		resumeDownload();
		return FALSE;
	}
	// There is only one record for download parameters
	pMap = pMapArray->GetAt(0);
	pMap->Lookup(_T("FRAG_LATENCY"), m_csDownloadFragLatency);
	pMap->Lookup(_T("CYCLE_LATENCY"), m_csDownloadCycleLatency);
	pMap->Lookup(_T("PERIOD_LATENCY"), m_csDownloadPeriodLatency);
	pMap->Lookup(_T("PERIOD_LENGTH"), m_csDownloadPeriodLength);
	pMap->Lookup(_T("TIMEOUT"), m_csDownloadTimeout);
	pMap->Lookup(_T("EXECUTION_TIMEOUT"), m_csCommandTimeout);
	if (m_csCommandTimeout.IsEmpty())
		m_csCommandTimeout = COMMAND_TIMEOUT_DEFAULT;
	pMap->Lookup(_T("ON"), m_csDownloadOn);
	writeConfig();
	delete pMapArray;
	pMapArray = NULL;

	// Now get each package information
	pMapArray = m_pPrologResp->getDownloadPackages();
	for (nPack = 0; (pMapArray != NULL) && (nPack<pMapArray->GetCount()); nPack++)
	{
		if (((pMap = pMapArray->GetAt(nPack)) == NULL) || pMap->IsEmpty())
			continue;
		csId.Empty();
		pMap->Lookup(_T("ID"), csId);
		// Try to find if package was not previously downloaded, parsing package history file
		CString csHistBuf;
		BOOL	bAlreadySetup = FALSE;
		cFileHistory.SeekToBegin();
		while (cFileHistory.ReadPackage(csHistBuf))
		{
			if (csHistBuf.Find(csId) != -1)
			{
				// Package ID found in history
				bAlreadySetup = TRUE;
				break;
			}
		}
		pOptDownloadPackage = new COptDownloadPackage(this);
		pOptDownloadPackage->setId(csId);
		// If CERT_PATH or CERT_FILE option is provided
		csValue.Empty();
		pMap->Lookup(_T("CERT_PATH"), csValue);
		pOptDownloadPackage->setCertPath(csValue);
		csValue.Empty();
		pMap->Lookup(_T("CERT_FILE"), csValue);
		pOptDownloadPackage->setCertFile(csValue);
		// Set URL where to download INFO metadata
		csValue.Empty();
		pMap->Lookup(_T("INFO_LOC"), csValue);
		pOptDownloadPackage->setInfoLocation(csValue);
		// Set URL where to download fragment
		csValue.Empty();
		pMap->Lookup(_T("PACK_LOC"), csValue);
		pOptDownloadPackage->setPackLocation(csValue);
		// Set if we have to force package setup, even if already installed
		csValue.Empty();
		pMap->Lookup(_T("FORCE"), csValue);
		pOptDownloadPackage->setForce(csValue);
		// Set if we have to schedule package setup at specified date
		csValue.Empty();
		pMap->Lookup(_T("SCHEDULE"), csValue);
		pOptDownloadPackage->setSchedule(csValue);
		// Set post execution command if package action succeeded
		csValue.Empty();
		pMap->Lookup(_T("POSTCMD"), csValue);
		pOptDownloadPackage->setPostCmd(csValue);
		if (bAlreadySetup && !pOptDownloadPackage->isForced())
		{
			// Package ID found in history, do not download
			m_pLogger->log(LOG_PRIORITY_NOTICE, _T("DOWNLOAD => Will not download package <%s>, already in the package history"), csId);
			sendMessage(csId, SUCCESS_ALREADY_SETUP);
			// Delete already download directory if needed 
			pOptDownloadPackage->clean();
			delete pOptDownloadPackage;
		}
		else
		{
			// Package not already downloaded, or setup forced, put it in the download queue
			if (pOptDownloadPackage->isForced())
				m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Package <%s> forced, ignoring package history check"), csId);
			m_tPackages.Add(pOptDownloadPackage);
		}
	}
	cFileHistory.Close();
	delete pMapArray;
	// Cleaning file history for duplicates
	switch (CFilePackageHistory::CleanDuplicates(getPackageHistoryFilename()))
	{
	case 1:
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Package history file successfully cleaned for duplicate IDs"));
		break;
	case 2:
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Package history file cleaning not required"));
		break;
	default:
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Failed to clean Package history file for duplicate IDs"));
		break;
	}

	// Now, prepare directories and download instructions for download tool
	for (nPack = 0; nPack<m_tPackages.GetSize(); nPack++)
	{
		pOptDownloadPackage = (COptDownloadPackage*)(m_tPackages[nPack]);
		// Check if package is not expired
		if (pOptDownloadPackage->isExpired(m_csDownloadTimeout))
		{
			ULONG ulNow = time(NULL);
			m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Package <%s> timed out (now:%lu, since:%lu, Timeout:%s)"), pOptDownloadPackage->getId(), ulNow, (ULONG)pOptDownloadPackage->getTimeStamp(), m_csDownloadTimeout);
			if (sendMessage(pOptDownloadPackage->getId(), ERR_TIMEOUT))
				// Server successfully notified => remove package
				if (!pOptDownloadPackage->clean())
					m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Failed to remove timed out package <%s>"), pOptDownloadPackage->getId());
		}
		else
		{
			// Check if package not already added to download queue
			if (pOptDownloadPackage->makeDirectory() && !fileExists(pOptDownloadPackage->getLocalMetadataFilename()))
			{
				// Download metadata from deployment server
				if (pOptDownloadPackage->downloadInfoFile())
					m_pLogger->log(LOG_PRIORITY_NOTICE, _T("DOWNLOAD => Package <%s> added to download queue"), pOptDownloadPackage->getId());
				else
					// Error dowloading metadata => remove package directory to avoid error message into download tool
					pOptDownloadPackage->clean();
			}
			else
				m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Package <%s> already in download queue, keeping on package"), pOptDownloadPackage->getId());
		}
	}
	// Now, allow Download tool
	unlockDownload();
	resumeDownload();
	return TRUE;
}
Example #17
0
DWORD CHttpClient::Request(LPCTSTR lpszURL, CString &strPostData,
						 CFile *pFileSave, CString *pstrResult,
						 PROGRESS_CALLBACK fnCallback, void *cookie )
{
	DWORD	dwRet	=	HTTP_STATUS_BAD_REQUEST;

	if( NULL == lpszURL || strlen(lpszURL) == 0 )
		return dwRet;

	int	nContentLength = 0;
	int nContentLengthLocal = 0;
	int nContentLengthFinished = 0;
	int nContentLengthTotal = 0;

	// prepare header
	CString	strHeader;
	CMapStringToString	mapHeader;
	if( pFileSave && pFileSave->GetPosition() > 0 )
	{
		nContentLengthFinished = (int)pFileSave->GetPosition();
		CString strRange;
		strRange.Format( "bytes=%u-", nContentLengthFinished );
		mapHeader.SetAt( szRange, strRange );
		
	}
	if( pstrResult && pstrResult->GetLength() > 0 )
	{
		nContentLengthFinished = pstrResult->GetLength();
		CString strRange;
		strRange.Format( "bytes=%u-", nContentLengthFinished );
		mapHeader.SetAt( szRange, strRange );
	}
	if( m_strCookie.GetLength() > 0 )
		mapHeader.SetAt( szCookieKey, m_strCookie );
	MakeHttpHeader( mapHeader, strHeader );

	// default type and flags
	DWORD dwHttpRequestFlags =	INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD
								| INTERNET_FLAG_DONT_CACHE
								| INTERNET_FLAG_EXISTING_CONNECT; // | INTERNET_FLAG_KEEP_CONNECTION;
	
	CString	strProxy;
	if( !m_strProxyAddress.IsEmpty() )
		strProxy = FormatProxyString( m_nProxyType, m_strProxyAddress, m_nProxyPort );
	CInternetSession session(	szUserAgentValue, 1, m_nAccessType,
							strProxy, NULL, INTERNET_FLAG_DONT_CACHE );
	// 以下SetOption似乎不起作用
	if( !strProxy.IsEmpty() && !m_strProxyAddress.IsEmpty() )
	{
		session.SetOption( INTERNET_OPTION_PROXY_USERNAME, (LPVOID)(LPCTSTR)m_strProxyUser, m_strProxyUser.GetLength() );
		session.SetOption( INTERNET_OPTION_PROXY_PASSWORD, (LPVOID)(LPCTSTR)m_strProxyPasswd, m_strProxyPasswd.GetLength() );
	}
	session.SetOption( INTERNET_OPTION_RECEIVE_TIMEOUT, 300000 );
	session.SetOption( INTERNET_OPTION_SEND_TIMEOUT, 30000 );
	session.SetOption( INTERNET_OPTION_CONNECT_TIMEOUT, 30000 );

	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	try
	{
		// check to see if this is a reasonable URL
		DoOpenURL( lpszURL, dwHttpRequestFlags, strHeader, strPostData, &session, &pServer, &pFile, fnCallback, cookie );
		if( NULL == pServer || NULL == pFile )
			ThrowTearException( ERR_TEAR_INTERRUPTED );

		pFile->QueryInfoStatusCode(dwRet);

		if (dwRet == HTTP_STATUS_MOVED ||
			dwRet == HTTP_STATUS_REDIRECT ||
			dwRet == HTTP_STATUS_REDIRECT_METHOD)
		{
			CString strNewLocation = GetNewLocation( pFile );

			// close up the redirected site
			pFile->Close();
			delete pFile;
			pFile	=	NULL;
			pServer->Close();
			delete pServer;
			pServer	=	NULL;

			// progress callback
			if( fnCallback )
				fnCallback( PROG_REDIRECTING, 0, NULL, cookie );

			// open new url
			DoOpenURL( strNewLocation, dwHttpRequestFlags,
						strHeader, strPostData,
						&session, &pServer, &pFile, fnCallback, cookie );
			
			pFile->QueryInfoStatusCode(dwRet);
		}

		if (dwRet == HTTP_STATUS_PARTIAL_CONTENT)
			dwRet = HTTP_STATUS_OK;
		if (dwRet != HTTP_STATUS_OK)
			ThrowTearException( ERR_TEAR_INTERRUPTED );

		CString	strInfo;
		pFile->QueryInfo( HTTP_QUERY_SET_COOKIE, strInfo );
		pFile->QueryInfo( HTTP_QUERY_COOKIE, strInfo );
		if( strInfo.GetLength() )
			m_strCookie	=	strInfo;
		pFile->QueryInfo( HTTP_QUERY_CONTENT_LENGTH, strInfo );
		nContentLength	=	atol( strInfo );
		nContentLengthTotal = nContentLength + nContentLengthFinished;
		if( pstrResult && nContentLengthTotal > 0 )
			pstrResult->GetBuffer( nContentLengthTotal+5 );

		DWORD	dwCheckSum	=	0;
		BOOL	bHasCheckSum	=	FALSE;
		CString	strCheckSum;
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strCheckSum);
		int nPlace = strCheckSum.Find( szCheckSumKeySuffix );
		if ( -1 != nPlace )
		{
			strCheckSum = strCheckSum.Mid( nPlace+strlen(szCheckSumKeySuffix) );
			nPlace = strCheckSum.Find( '\n' );
			if( nPlace > 0 )
			{
				dwCheckSum = atol( strCheckSum.Left( nPlace ) );
				bHasCheckSum	=	TRUE;
			}
		}

		if( fnCallback )
			fnCallback( PROG_TRANSFERRING, 0, NULL, cookie );

		DWORD	dwCheckSumLocal	=	0;
		TCHAR sz[1028];
		int nRead = pFile->Read(sz+4, 1023);
		while (nRead > 0)
		{
			sz[4+nRead] = '\0';
			if( NULL != pFileSave )
				pFileSave->Write( sz+4, nRead );
			if( NULL != pstrResult )
				*pstrResult	+=	(TCHAR *)(sz+4);
			nContentLengthLocal	+=	nRead;

			if( fnCallback && nContentLengthTotal > 0 )
				fnCallback( PROG_PROGRESS, DWORD(STKLIB_MAXF_PROGRESS*(nContentLengthFinished+nContentLengthLocal)/nContentLengthTotal), NULL, cookie );

			if( bHasCheckSum )
			{
				*((DWORD *)sz)	=	dwCheckSumLocal;
				dwCheckSumLocal = CRC32( sz, nRead );
			}

			nRead = pFile->Read(sz+4, 1023);
		}

		if( pstrResult && nContentLengthTotal > 0 )
			pstrResult->ReleaseBuffer();

		if( (nContentLength > 0 && nContentLengthLocal != nContentLength)
				|| (bHasCheckSum && dwCheckSum != dwCheckSumLocal) )
			ThrowTearException( ERR_TEAR_DATATRANSFER );

		if( fnCallback )
			fnCallback( PROG_PROGRESS, STKLIB_MAX_PROGRESS, NULL, cookie );
	}
	catch (CInternetException* pEx)
	{
		// catch errors from WinINet
		if (HTTP_STATUS_OK == dwRet)
			dwRet	=	HTTP_STATUS_PARTIAL;
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}
	catch (CTearException* pEx)
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}
	catch( CException * pEx )
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}

	if (pFile != NULL)
	{
		pFile->Close();
		delete pFile;
	}
	if (pServer != NULL)
	{
		pServer->Close();
		delete pServer;
	}
	session.Close();

	if(nContentLength > 0 && nContentLengthLocal != nContentLength)
		return Request( lpszURL, strPostData, pFileSave, pstrResult, fnCallback, cookie );

	return dwRet;
}
Example #18
0
void CDz3Handler::DataIntegrateForCompensate(CMapStringToString& mstr,int indexmax)
{
	mstr.SetAt("0.005","0");	mstr.SetAt("0.01","1");	mstr.SetAt("0.02","2");
	mstr.SetAt("0.05","3");		mstr.SetAt("0.1","4");	mstr.SetAt("0.2","5");
	mstr.SetAt("0.5","6");		mstr.SetAt("1","7");	mstr.SetAt("2","8");
	mstr.SetAt("5","9");		mstr.SetAt("5","10");
	static int g_Digipos[] = {-7,-6,-6,-6,-5,-5,-5,-4,-4,-4,-3};
	static int g_Mantissa[]= { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
	CString perrecord;
	int ipos = indexmax;
	
	while(ipos-- > 0)
	{
		CString sid;
		double accuracy;
		sid.Format("Z%d",ipos);
		if(mstr.Lookup(sid,perrecord))
		{
			if(perrecord.Find("--") >= 0)
				continue;
			sid.Format("jhsel%d",INDEX2GROUP(ipos));
			if(!mstr.Lookup(sid,sid))		continue;//retrieve the jhsel
			
			accuracy = atof(sid)/100.0;
			
			if(!mstr.Lookup(sid,sid))		continue;//translate the jhsel
			perrecord = DataIntergrate(ipos,atof(perrecord),g_Digipos[atoi(sid)]-2,g_Mantissa[atoi(sid)]);
			sid=SJD2SByPosition(GetDiffData(ipos,atof(perrecord),accuracy),INDEX2GROUP(ipos)+g_Digipos[atoi(sid)]-3);
			if(!CheckData(ipos,atof(perrecord),accuracy))
			{
				sid = "<font color='red'>"+sid+"</font>";
			}
			perrecord = sid;
			sid.Format("Z%d",ipos);
			mstr.SetAt(sid,perrecord);
		}
	}
}
Example #19
0
void CDz3Handler::DataIntegrateForCheck(CMapStringToString& mstr,int indexmax,bool colormark)
{
	mstr.SetAt("0.005","0");	mstr.SetAt("0.01","1");	mstr.SetAt("0.02","2");
	mstr.SetAt("0.05","3");		mstr.SetAt("0.1","4");	mstr.SetAt("0.2","5");
	mstr.SetAt("0.5","6");		mstr.SetAt("1","7");	mstr.SetAt("2","8");
	mstr.SetAt("5","9");
	static int g_Digipos[] = {-7,-6,-6,-6,-5,-5,-5,-4,-4,-4,-3};
	static int g_Mantissa[]= { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
	CString perrecord;
	CString jherr("");
	int ipos = indexmax;
	
	while(ipos-- > 0)
	{
		CString sid;
		double accuracy;
		sid.Format("Z%d",ipos);
		if(mstr.Lookup(sid,perrecord))
		{
			if(perrecord.Find("--") >= 0)
				continue;
			sid.Format("jhsel%d",INDEX2GROUP(ipos));
			if(!mstr.Lookup(sid,sid))		continue;//retrieve the jhsel

			accuracy = atof(sid)/100.0;

			if(!mstr.Lookup(sid,sid))		continue;//translate the jhsel
			perrecord = DataIntergrate(ipos,atof(perrecord),g_Digipos[atoi(sid)]-2,g_Mantissa[atoi(sid)]);
			if((!CheckData(ipos,atof(perrecord),accuracy)))
			{
				//add the a message to the error
				CString stmp;
				stmp.Format("%s盘第%d点不合格;\n",Panhao[INDEX2GROUP(ipos)],INDEX2REST(ipos));
				jherr += stmp;
				if(colormark)
					perrecord = "<font color='red'>"+perrecord+"</font>";
			}
			sid.Format("Z%d",ipos);
			mstr.SetAt(sid,perrecord);
		}
	}
	mstr.SetAt("jdjg",jherr);//检定结果
}
Example #20
0
void CDownloadManager::GetSharedPaths(CMapStringToString& mapSharedPaths)
{
   char     chKey[MAX_PATH], szSharedPath[MAX_PATH];
   HKEY     hKey = NULL, hSharedKey = NULL;
   DWORD    retCode;
   DWORD    dwLength = 0;
   CString  csSharedPathKey;

	mapSharedPaths.RemoveAll();

   TRY
   {
      if ( (retCode = RegOpenKeyEx(
               HKEY_LOCAL_MACHINE,
               cbSharedKey,
               0,
               KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
               &hKey)) == ERROR_SUCCESS)
      {
         for(int i=0;retCode == ERROR_SUCCESS;i++)
            {
               retCode = RegEnumKey(hKey, i, chKey, MAX_PATH);
               if(retCode == (DWORD) ERROR_SUCCESS)
                  {
                     hSharedKey = NULL;
                     csSharedPathKey = cbSharedKey;
                     csSharedPathKey += "\\";
                     csSharedPathKey += chKey;
                     if ( (retCode = RegOpenKeyEx(
                              HKEY_LOCAL_MACHINE,
                              (LPCSTR)csSharedPathKey,
                              0,
                              KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
                              &hSharedKey)) == ERROR_SUCCESS)
                     {
                        dwLength = sizeof(szSharedPath);
                        if ((retCode = RegQueryValueEx(
                                 hSharedKey,
                                 NULL,
                                 NULL,
                                 NULL,
                                 (LPBYTE)szSharedPath,
                                 &dwLength)) == ERROR_SUCCESS)
                           {
										CString csKey = chKey;
										csKey.MakeLower();
                              mapSharedPaths.SetAt(csKey, szSharedPath);
                           }
                        RegCloseKey(hSharedKey);
                     }
                  }

            }
         RegCloseKey(hKey);
      }
   }
   CATCH_ALL(e)
   {
      if (hKey != NULL)
      {
         RegCloseKey(hKey);
      }
      if (hSharedKey != NULL)
      {
         RegCloseKey(hSharedKey);
      }
      csSharedPathKey.Empty();
   }
   END_CATCH_ALL
}
Example #21
0
void CObjektPool :: BesondInfo( const short j, const short k, CAtkisSatz* pSatz )
{
	CCfg	*pConfiguration= &((CEDBSExtension*)g_pTE)->Configuration;
	CRule_Layer *pRule_Layer;
	CGeoObj		*pGOBI = NULL;
	CPunktFolge* pBIpoints1 = NULL;
	CPunktFolge* pBIpoints2 = NULL;
	CxString	strTemp;
	CxString	strText, txt;

	CRule_Info	*pRule_Info = NULL;

	CxString strRegeln("ALK-Regeln");
	CxString strRule;

	CxString strObjNum;
	CxString strAktualitaet;
	CxString strObjNumBI;
	CxString strInfoArt;
	CxString strArtBI;
	CxString strFolie, strObjArt, strObjArtBI;
	int iArtGeo;
	bool tText_erzeugt;
	
	try {

		strObjNum = pSatz->OF_Objektnummer( j );
		strAktualitaet = pSatz->OF_Aktuali( j );
	//	strObjNum.TrimAll();
		strFolie = pSatz -> OF_Folie(j);
		strFolie.TrimAll();
		
		pRule_Layer = g_pMetaData->GetRule_Layer( strFolie );
		if( NULL == pRule_Layer )
			return;

		if( 0 == pRule_Layer->ImportMode() ) 
			return;

		strObjArt = pSatz -> OF_Objektart( j );
		strObjArt.TrimAll();
		strObjArtBI = pSatz -> OF_BI_Objektart( j, k );
		strObjArtBI.TrimAll();
		strArtBI = pSatz -> OF_BI_Art( j, k );	
		strArtBI.TrimAll();
		strInfoArt = strArtBI;
		strInfoArt += "/";									//#FJE980805
		strInfoArt += strObjArtBI;
		
	/*
		if ( strArtBI == "44" ) {	// UNIX-Umlaute ausbauen
			strInfoArt = strText.Left( 2 );
			strText = strText.Mid( 2 );
			strText.Transform(2);
		}
	*/
	//	pGO = g_pObjektPool->GetGeoObj( strObjNum + "H" );
	//	pGO->Folie() = strFolie;
	//	pGO->Objektart() = strObjArt;
	//	pGO->Aktualitaet() = m_Aktuali;


//=== Regeln für besondere Informationen suchen ========================================

		strRule = strFolie + strObjArt + strObjArtBI + strArtBI;
		pRule_Info = g_pMetaData->GetRule_Info( strRule );
		if( NULL == pRule_Info )
			return;

		strText = pSatz -> OF_BI_Text( j, k );
		strText.TrimAll();
		if( pConfiguration->m_sCodePage )
			strText.Transform(pConfiguration->m_sCodePage);

		if( pRule_Info->ObjektartBI_bestimmt_Objektklasse_Hauptgeometrie() ) {
			CGeoObj	*pGO;

			pGO = g_pObjektPool->GetGeoObj( strObjNum + "H" );
			if( pConfiguration->m_tCreateAttributeRegeln )
				pGO->AddAttribute( strRegeln, strRule );
			pGO->Folie() = strFolie;
			pGO->Objektart() = strObjArtBI;
			g_pMetaData->ObjectClassesTRiAS().Lookup( pRule_Info->ObjectClassTRiAS_Hauptgeometrie(), (CObject*&)pGO->ObjectClassTRiAS() );
		}

	//=== Regeln für Texte ============================================================
		tText_erzeugt = false;
		if( pConfiguration->m_tCreateBItext) {
			if( 0 != pRule_Info->Importmodus_Attr() ) {
				CxString strTextToCreate;

				strTemp = pRule_Info->Konvertierung_Text().Left(1);
				if( strTemp == "\"" ) {
					strTextToCreate = pRule_Info->Konvertierung_Text().Mid( 1, pRule_Info->Konvertierung_Text().GetLength() - 2 );
				}
				else if( !strText.IsEmpty() ) { 
					if( strTemp == "§" ) {
	//--- Konvertierung für Hausnummern ------------------------------------------------
						if( "§Hausnummer" == pRule_Info->Konvertierung_Text() ) {
							if( strText.Left(2) == "HA" ) {
								CxString strHANR, strHANRZ, strArt, strObjArt;
								int ix1, ix2;
								strHANR = strText;
								strHANR = strHANR.Mid(23,3);
								if( strHANR == "P01" || strHANR == " 01" || strHANR == "001") {
									strHANR = strText;
									strHANR = strHANR.Mid(15,8);
									strHANRZ = strHANR;
									while( isdigit((int)*strHANRZ.Left(1)) )
										strHANRZ = strHANRZ.Mid(1);
									strHANRZ.TrimAll();
									strHANR.Format("%ld", strHANR.Long());
									if( !strHANRZ.IsEmpty() )
										strHANR += strHANRZ;
									for( ix1 = 0,ix2 = pSatz -> OF_AnzahlBesInfo( j );
										ix1 < ix2;
										ix1++ ) {
										strArt = pSatz -> OF_BI_Art( j, ix1 );
										strObjArt = pSatz -> OF_BI_Objektart( j, ix1 );
										if(  strArt == "21" ) {
											if( strObjArt == "  1031" ) {
												strHANR.Empty();
												break;
											}
										}
										else
											continue;
									}	
									strTextToCreate = strHANR;
								}
							}
							else
								strTextToCreate = strText;
						}
	//--- Konvertierung für Flurstückskennzeichen -------------------------------------
						else if( "§Flurstückskennzeichen" == pRule_Info->Konvertierung_Text() ) {
							if( strText.Left(2) == "FS" ) {
								long z, n;
								z = ((CxString)strText.Mid(11,5)).Long();
								n = ((CxString)strText.Mid(16,3)).Long();
								if( 0 == n )							
									strTextToCreate.printf( "%lu", z );
								else							
									strTextToCreate.printf( "%lu/%lu", z, n );
							}
							else
								strTextToCreate = strText;
						}
	//--- Konvertierung für Flurkennzeichen -------------------------------------
						else if( "§Flurkennzeichen" == pRule_Info->Konvertierung_Text() ) {
							if( strText.Left(2) == "FL" ) {
								long f;
								f = ((CxString)strText.Mid(8,3)).Long();
								strTextToCreate.printf( "Fl. %lu", f );
							}
							else
								strTextToCreate = strText;
						}
					}
					else {
						strTextToCreate = strText;
					}
				}

				if( strTextToCreate.IsEmpty() )
					tText_erzeugt = false;
				else {
					tText_erzeugt = true;
					strObjNumBI = strObjNum + "T";
					strObjNumBI += "_";
					txt.Format("%03d", j);
					strObjNumBI += txt;
					strObjNumBI += "_";
					txt.Format("%03d", k);
					strObjNumBI += txt;
	/*
					strObjNumBI = strObjNum;
					strObjNumBI += "_";
			//		txt.Format("%06ld", pSatz->m_lEDBSSatzNummer);
					txt.Format("%08ld", pSatz->m_lNumParserCalls);
					strObjNumBI += txt;
					strObjNumBI += "_";
					txt.Format("%03d", k);
					strObjNumBI += txt;
					strObjNumBI += "_";
					strObjNumBI += key;
					strObjNumBI += "T";
					strObjNumBI += pSatz->OF_BI_ArtGeo(j,k);
					strObjNumBI += "T";
	*/

					pBIpoints1 = pSatz -> OF_BI_Points( j, k );
					if( pBIpoints1 ) {
						pGOBI = g_pObjektPool->GetGeoObj( strObjNumBI );
						if( pConfiguration->m_tCreateAttributeRegeln )
							pGOBI->AddAttribute( strRegeln, strRule );
						pGOBI->tBI = true;
						pGOBI->Folie() = strFolie;
						pGOBI->Objektart() = strObjArtBI;
			//			pGOBI->Aktualitaet() = m_Aktuali;
						g_pMetaData->ObjectClassesTRiAS().Lookup( pRule_Info->Objektklasse_Text(), (CObject*&)pGOBI->ObjectClassTRiAS() );
						if( pBIpoints1->GetSize() > 1 ) {
							pBIpoints2 = new CPunktFolge( 1 );
							if(	pBIpoints1->GetPoint(1).Hoch() == pSatz -> GrundPunktHoch()
								&& pBIpoints1->GetPoint(1).Rechts() == pSatz -> GrundPunktRechts() ) {
								(*pBIpoints2)[0] = new CPunkt( pBIpoints1->GetPoint(0).Hoch(), pBIpoints1->GetPoint(1).Rechts(), pBIpoints1->GetPoint(1).Dreh() );
							}
							else {
								(*pBIpoints2)[0] = new CPunkt( pBIpoints1->GetPoint(0).Hoch(), pBIpoints1->GetPoint(0).Rechts(), pBIpoints1->GetPoint(0).Dreh() );
							}
							AddLineBI( strObjNumBI, pBIpoints2, pGOBI,
								"BI", strFolie, strObjArtBI );
							delete pBIpoints2;
							pBIpoints2 = NULL;
						}
						else
							AddLineBI( strObjNumBI, pBIpoints1, pGOBI,
								"BI", strFolie, strObjArtBI );

						pGOBI->ObjTyp() = 'T';
						pGOBI->ObjLabel() = strTextToCreate;
					}
				}
			}
		}

	//=== Regeln für Attribute ========================================================
		if( pConfiguration->m_tCreateBIattr && !strText.IsEmpty() ) {
			CMapStringToString	mapAttrToCreate;
			CxString	strAttrToCreate;

			if( 0 != pRule_Info->Importmodus_Attr() ) {
				strTemp = pRule_Info->Konvertierung_Attr().Left(1);
				if( strTemp == "\"" ) {
					strAttrToCreate = pRule_Info->Konvertierung_Attr().Mid( 1, pRule_Info->Konvertierung_Attr().GetLength() - 2 );
					mapAttrToCreate.SetAt( pRule_Info->AttributeName(), strAttrToCreate );
				}
				else if( strTemp == "§" ) {
	//--- Konvertierungen -------------------------------------------------------------
					if( "{" == pRule_Info->Konvertierung_Attr().Mid(1,1) ) { // Attributmenge
						CxString strAttrNames(pRule_Info->AttributeName() + ";");
						if( "§{Gebaeudekennzeichen}" == pRule_Info->Konvertierung_Attr() ) {
							if( strText.Left(2) == "HA" ) {
								if( 0 <= strAttrNames.Find("Laenderschluessel;") )
									mapAttrToCreate.SetAt( "Laenderschluessel", strText.Mid( 2, 2 ) );
								if( 0 <= strAttrNames.Find("Regierungsbeziksschluessel;") )
									mapAttrToCreate.SetAt( "Regierungsbeziksschluessel", strText.Mid( 4, 1 ) );
								if( 0 <= strAttrNames.Find("Kreisschluessel;") )
									mapAttrToCreate.SetAt( "Kreisschluessel", strText.Mid( 5, 2 ) );
								if( 0 <= strAttrNames.Find("Gemeindeschluessel;") )
									mapAttrToCreate.SetAt( "Gemeindeschluessel", strText.Mid( 7, 3 ) );
								if( 0 <= strAttrNames.Find("Strassenschluessel;") )
									mapAttrToCreate.SetAt( "Strassenschluessel", strText.Mid( 10, 5 ) );
								if( 0 <= strAttrNames.Find("Hausnummer;") )
									mapAttrToCreate.SetAt( "Hausnummer", strText.Mid( 15, 4 ) );
								if( 0 <= strAttrNames.Find("Hausnummernzusatz;") )
									mapAttrToCreate.SetAt( "Hausnummernzusatz", strText.Mid( 19, 4 ) );
								if( 0 <= strAttrNames.Find("Gebaeudenummer;") )
									mapAttrToCreate.SetAt( "Gebaeudenummer", strText.Mid( 23, 3 ) );
							}
						}	
						if( "§{Flurstueckskennzeichen}" == pRule_Info->Konvertierung_Attr() ) {
							if( strText.Left(2) == "FS" ) {
								if( 0 <= strAttrNames.Find("Bundeslandschluessel;") )
									mapAttrToCreate.SetAt( "Bundeslandschluessel", strText.Mid( 2, 2 ) );
								if( 0 <= strAttrNames.Find("Gemarkungsschluessel;") )
									mapAttrToCreate.SetAt( "Gemarkungsschluessel", strText.Mid( 4, 4 ) );
								if( 0 <= strAttrNames.Find("Flur;") )
									mapAttrToCreate.SetAt( "Flur", strText.Mid( 8, 3 ) );
								if( 0 <= strAttrNames.Find("Flurstueckszaehler;") )
									mapAttrToCreate.SetAt( "Flurstueckszaehler", strText.Mid( 11, 5 ) );
								if( 0 <= strAttrNames.Find("Flurstuecksnenner;") )
									mapAttrToCreate.SetAt( "Flurstuecksnenner", strText.Mid( 16, 3 ) );
								if( 0 <= strAttrNames.Find("Flurstuecksfolgenummer;") )
									mapAttrToCreate.SetAt( "Flurstuecksfolgenummer", strText.Mid( 19, 2 ) );
							}
						}	
					}
					else {										// Einzelattribut
						if( "§WLDGE-Flurstueckskennzeichen" == pRule_Info->Konvertierung_Attr() ) {
							strAttrToCreate = strText.Mid( 2, 6 )
								+ "-" + strText.Mid( 8, 3 ) + "-"
								+ strText.Mid( 11, 5 ) + "/" + strText.Mid( 16, 3 )
								+ "." + strText.Mid( 19, 2 );
							mapAttrToCreate.SetAt( pRule_Info->AttributeName(), strAttrToCreate );
						}	
					}
				}
				else
					mapAttrToCreate.SetAt( pRule_Info->AttributeName(), strText );

				if( !mapAttrToCreate.IsEmpty() ) {
					CGeoObj	*pGO;

					pGO = g_pObjektPool->GetGeoObj( strObjNum + "H" );
					if( pConfiguration->m_tCreateAttributeRegeln )
						pGO->AddAttribute( strRegeln, strRule );
					if( 0 == pGO->AnzahlLinien() && !tText_erzeugt ) {
						double dblH;
						double dblR; 

						if( pGO->Folie().IsEmpty() )
							pGO->Folie() = strFolie;
						if( pGO->Objektart().IsEmpty() )
							pGO->Objektart() = strObjArt;
	//					pGO->Aktualitaet() = m_Aktuali;
						dblH = pSatz -> GrundPunktHoch();
						dblR = pSatz -> GrundPunktRechts();
						if (( dblH != 0.0 ) && ( dblR != 0.0 ))
							pGO -> SetzPunkt( dblH, dblR );
					}

					POSITION pos;
					CString strAttrName;
					CString strAttrValue;
					for ( pos = mapAttrToCreate.GetStartPosition();
						pos != NULL; ) {
						mapAttrToCreate.GetNextAssoc( pos, strAttrName, strAttrValue  );
						pGO -> AddAttribute( strAttrName, strAttrValue );
						g_pTriasInterface -> NeuesMerkmal( strAttrName );
					}
					mapAttrToCreate.RemoveAll();
				}
			}
		}

	//=== Regeln für Geometrien =======================================================
		if( pConfiguration->m_tCreateBIgeom && strText.IsEmpty() && !tText_erzeugt ) {
			if( 0 != pRule_Info->Importmodus_Detailgeometrie() ) {
				strObjNumBI = strObjNum + "D";
				strObjNumBI += "_";
				txt.Format("%03d", j);
				strObjNumBI += txt;
				txt.Format("%03d", k);
				strObjNumBI += txt;
				strObjNumBI += strObjArtBI;
				txt.Format("%08ld", pSatz->m_lNumParserCalls);
				strObjNumBI += txt;
	/*
					strObjNumBI = strObjNum;
					strObjNumBI += "_";
			//		txt.Format("%06ld", pSatz->m_lEDBSSatzNummer);
					txt.Format("%08ld", pSatz->m_lNumParserCalls);
					strObjNumBI += txt;
					strObjNumBI += "_";
					txt.Format("%03d", k);
					strObjNumBI += txt;
					strObjNumBI += "_";
					strObjNumBI += strObjArt + strInfoArt;
					strObjNumBI += "T";
					strObjNumBI += pSatz->OF_BI_ArtGeo(j,k);
	*/
				pBIpoints1 = pSatz -> OF_BI_Points( j, k );
				if( pBIpoints1 ) {
					int iAnzahlPunkte = 0;

					iArtGeo = atoi(pSatz->OF_BI_ArtGeo(j,k));
					switch( iArtGeo ) {
					case _EinzelpunktInBesondererAusrichtung:
			#pragma message( "Einzelpunkte verarbeiten" )
						pBIpoints2 = new CPunktFolge( *pBIpoints1, false );
						break;
					case _Gerade:
						pBIpoints2 = new CPunktFolge( *pBIpoints1, false );
						break;
					case _Polygonzug:
						pBIpoints2 = new CPunktFolge( *pBIpoints1, false );
						break;
					case _Kreisbogen_rechts:
						{
							if( pBIpoints1->GetSize() == 3 ) {
								SAFEARRAY *psa = NULL;
								ConvertArc1(
										(pBIpoints1->GetPoint(1)).Hoch(), (pBIpoints1->GetPoint(1)).Rechts(),
										(pBIpoints1->GetPoint(2)).Hoch(), (pBIpoints1->GetPoint(2)).Rechts(),
										(pBIpoints1->GetPoint(0)).Hoch(), (pBIpoints1->GetPoint(0)).Rechts(),
										&psa );
								if( psa ) {
									iAnzahlPunkte = psa->rgsabound[0].cElements / 2;
									if( iAnzahlPunkte > 0 ) {
										pBIpoints2 = new CPunktFolge( iAnzahlPunkte );
										do {
											--iAnzahlPunkte;
											(*pBIpoints2)[iAnzahlPunkte] = new CPunkt( *(((double*)psa->pvData) + iAnzahlPunkte*2), *(((double*)psa->pvData) + iAnzahlPunkte*2 + 1) );
										} while( iAnzahlPunkte > 0);
									}
									SafeArrayDestroy( psa );
									psa = NULL;
								}
							}
							else {	//Korrektur für Kreise aus zwei Punkten
								pBIpoints2 = new CPunktFolge( *pBIpoints1, false );
							}
						}
						break;
					case _Kreisbogen_links:
						{
							if( pBIpoints1->GetSize() == 3 ) {
								SAFEARRAY *psa = NULL;
								ConvertArc1(
										(pBIpoints1->GetPoint(0)).Hoch(), (pBIpoints1->GetPoint(0)).Rechts(),
										(pBIpoints1->GetPoint(2)).Hoch(), (pBIpoints1->GetPoint(2)).Rechts(),
										(pBIpoints1->GetPoint(1)).Hoch(), (pBIpoints1->GetPoint(1)).Rechts(),
										&psa );
								if( psa ) {
									iAnzahlPunkte = psa->rgsabound[0].cElements / 2;
									if( iAnzahlPunkte > 0 ) {
										pBIpoints2 = new CPunktFolge( iAnzahlPunkte );
										do {
											--iAnzahlPunkte;
											(*pBIpoints2)[iAnzahlPunkte] = new CPunkt( *(((double*)psa->pvData) + iAnzahlPunkte*2), *(((double*)psa->pvData) + iAnzahlPunkte*2 + 1) );
										} while( iAnzahlPunkte > 0);
									}
									SafeArrayDestroy( psa );
									psa = NULL;
								}
							}
							else {	//Korrektur für Kreise aus zwei Punkten
								pBIpoints2 = new CPunktFolge( *pBIpoints1, false );
							}
						}
						break;
			/*
					case _Kurve:
						iAnzahlPunkte = 0;

						pPF = new CPunktFolge( iAnzahlPunkte + 2 );
						(*pPF)[0] = new CPunkt( pSatz -> GrundPunktHoch(), pSatz -> GrundPunktRechts());
						(*pPF)[iAnzahlPunkte + 1] = new CPunkt( pSatz -> EndPunktHoch( i ), pSatz -> EndPunktRechts( i ));
						break;
			*/		default:
			//			_ASSERT(0);
						break;
					}
				}
				if( pBIpoints2 ) {
					pGOBI = g_pObjektPool->GetGeoObj( strObjNumBI );
					if( pConfiguration->m_tCreateAttributeRegeln )
						pGOBI->AddAttribute( strRegeln, strRule );
					pGOBI->tBI = true;
					pGOBI->Folie() = strFolie;
					if( pRule_Info->Objektart_bestimmt_Objektklasse_Detailgeometrie() ) {
						pGOBI->Objektart() = strObjArt;
						g_pMetaData->ObjectClassesTRiAS().Lookup( g_pMetaData->m_strObjectClassesTRiAS + strFolie + strObjArt, (CObject*&)pGOBI->ObjectClassTRiAS() );
					}
					else {
						pGOBI->Objektart() = strObjArtBI;
						g_pMetaData->ObjectClassesTRiAS().Lookup( pRule_Info->Objektklasse_Detailgeometrie(), (CObject*&)pGOBI->ObjectClassTRiAS() );
					}
					AddLineBI( strObjNumBI, pBIpoints2, pGOBI,
						"BI", strFolie, strObjArtBI );
					delete pBIpoints2;
					pBIpoints2 = NULL;
				}
			}
		}


	/*		
		if( pConfiguration->m_tDefaultObjectMapping ) {
	//==========================================================================
	/ *		lH = pSatz -> GrundPunktHoch();
			lR = pSatz -> GrundPunktRechts();
			if (( lH != 0.0 ) && ( lR != 0.0 ))
				pGO -> SetzPunkt( lH, lR );

			if ( pGO -> Objektart().IsEmpty())
				pGO -> Objektart() = strObjArt;
			else if ( pGO -> Objektart().Find( strObjArt ) < 0 )	{
				txt = strObjArt;
				txt += ", ";
				txt += pGO -> Objektart();
				pGO -> Objektart() = txt;
			}
	* /
	//=== Standard D-Regeln =============================================================================
		}
		else {
			if ( !strText.IsEmpty() && ( strText != "NNNN" )) {
		//=== C-Regeln =============================================================================
		/ *
				key = strObjArt;
				key += strInfoArt;
				key += ":";
				key += strText;
				if ( g_pTriasInterface -> Get_C_Rule( key, newkey )) {
					if ( !newkey.IsEmpty())	{
						strNewKey = newkey;
						strNewKey.Teilen( newkey, strText, '#' );

						pGO -> AddAttribute( newkey, strText );
						g_pTriasInterface -> NeuesMerkmal( newkey );
					}
				}
		* /
			}
			lH = pSatz -> GrundPunktHoch();
			lR = pSatz -> GrundPunktRechts();
			if (( lH != 0.0 ) && ( lR != 0.0 ))
				pGO -> SetzPunkt( lH, lR );

			if ( pGO -> Objektart().IsEmpty())
				pGO -> Objektart() = strObjArt;
			else if ( pGO -> Objektart().Find( strObjArt ) < 0 )	{
				txt = strObjArt;
				txt += ", ";
				txt += pGO -> Objektart();
				pGO -> Objektart() = txt;
			}

		//=== D-Regeln =============================================================================
		}
	*/
	} 
	catch( ... ) {
		AfxMessageBox( "Unerwarteter Fehler in BesondInfo",0,0);
	}
}	// BesondInfo
Example #22
0
int main()
{
    CMapStringToString map;

    if( !map.IsEmpty() ) _fail;
    if( map.GetCount() != 0 ) _fail;
    if( map.GetSize() != 0 ) _fail;

    map.SetAt( _T("0"), _T(" ") );
    map.SetAt( _T("1"), _T("A") );
    map.SetAt( _T("2"), _T("B") );

    CString value;
    if( !map.Lookup( _T("0"), value ) ) _fail;
    if( value != _T(" ") ) _fail;
    if( !map.Lookup( _T("1"), value ) ) _fail;
    if( value != _T("A") ) _fail;
    if( !map.Lookup( _T("2"), value ) ) _fail;
    if( value != _T("B") ) _fail;
    if( map.Lookup( _T("3"), value ) ) _fail;

    POSITION    position = map.GetStartPosition();
    CString     key;
    BOOL        bFound0 = FALSE;
    BOOL        bFound1 = FALSE;
    BOOL        bFound2 = FALSE;
    while( position != NULL ) {
        map.GetNextAssoc( position, key, value );
        if( key == _T("0") ) {
            if( bFound0 ) _fail;
            if( value != _T(" ") ) _fail;
            bFound0 = TRUE;
        } else if( key == _T("1") ) {
            if( bFound1 ) _fail;
            if( value != _T("A") ) _fail;
            bFound1 = TRUE;
        } else if( key == _T("2") ) {
            if( bFound2 ) _fail;
            if( value != _T("B") ) _fail;
            bFound2 = TRUE;
        } else {
            _fail;
        }
    }
    if( !bFound0 ) _fail;
    if( !bFound1 ) _fail;
    if( !bFound2 ) _fail;

    map.RemoveKey( _T("0") );
    if( map.Lookup( _T("0"), value ) ) _fail;

    CMapStringToString smap1;
    CMapStringToString smap2;
    smap1[_T("0")] = _T(" ");
    smap1[_T("1")] = _T("A");
    smap1[_T("2")] = _T("B");
    
    CMemFile file;
    CArchive ar( &file, CArchive::store );
    smap1.Serialize( ar );
    ar.Close();

    file.Seek( 0, CFile::begin );
    CArchive ar2( &file, CArchive::load );
    smap2.Serialize( ar2 );
    ar2.Close();

    if( smap2[_T("0")] != _T(" ") ) _fail;
    if( smap2[_T("1")] != _T("A") ) _fail;
    if( smap2[_T("2")] != _T("B") ) _fail;

    _PASS;
}
Example #23
0
//
// =======================================================================================================================
//    Map_ImportFile Timo 09/01/99:: called by CXYWnd::Paste & Map_ImportFile if Map_ImportFile ( prefab ), the buffer
//    may contain brushes in old format ( conversion needed )
// =======================================================================================================================
//
void Map_ImportBuffer(char *buf, bool renameEntities) {
	entity_t	*ent;
	brush_t		*b = NULL;
	CPtrArray	ptrs;

	Select_Deselect();

	Undo_Start("import buffer");

	g_qeglobals.d_parsed_brushes = 0;
	if (buf) {
		CMapStringToString	mapStr;
		StartTokenParsing(buf);
		g_qeglobals.d_num_entities = 0;

		//
		// Timo will be used in Entity_Parse to detect if a conversion between brush
		// formats is needed
		//
		g_qeglobals.bNeedConvert = false;
		g_qeglobals.bOldBrushes = false;
		g_qeglobals.bPrimitBrushes = false;
		g_qeglobals.mapVersion = 1.0;

		if (GetToken(true)) {
			if (stricmp(token, "Version") == 0) {
				GetToken(false);
				g_qeglobals.mapVersion = atof(token);
				common->Printf("Map version: %1.2f\n", g_qeglobals.mapVersion);
			} else {
				UngetToken();
			}
		}

		idDict RemappedNames;	// since I can't use "map <string, string>"... sigh. So much for STL...

		while (1) {
			//
			// use the selected brushes list as it's handy ent = Entity_Parse (false,
			// &selected_brushes);
			//
			ent = Entity_Parse(false, &active_brushes);
			if (!ent) {
				break;
			}

			// end entity for undo
			Undo_EndEntity(ent);

			// end brushes for undo
			for (b = ent->brushes.onext; b && b != &ent->brushes; b = b->onext) {
				Undo_EndBrush(b);
			}

			if (!strcmp(ValueForKey(ent, "classname"), "worldspawn")) {
				// world brushes need to be added to the current world entity
				b = ent->brushes.onext;
				while (b && b != &ent->brushes) {
					brush_t *bNext = b->onext;
					Entity_UnlinkBrush(b);
					Entity_LinkBrush(world_entity, b);
					ptrs.Add(b);
					b = bNext;
				}
			}
			else {
				// the following bit remaps conflicting target/targetname key/value pairs
				CString str = ValueForKey(ent, "target");
				CString strKey;
				CString strTarget("");
				if (str.GetLength() > 0) {
					if (FindEntity("target", str.GetBuffer(0))) {
						if (!mapStr.Lookup(str, strKey)) {
							idStr key;
							UniqueTargetName(key);
							strKey = key;
							mapStr.SetAt(str, strKey);
						}

						strTarget = strKey;
						SetKeyValue(ent, "target", strTarget.GetBuffer(0));
					}
				}

				/*
				 * str = ValueForKey(ent, "name"); if (str.GetLength() > 0) { if
				 * (FindEntity("name", str.GetBuffer(0))) { if (!mapStr.Lookup(str, strKey)) {
				 * UniqueTargetName(strKey); mapStr.SetAt(str, strKey); } Entity_SetName(ent,
				 * strKey.GetBuffer(0)); } }
				 */
				CString cstrNameOld = ValueForKey(ent, "name");
				Entity_Name(ent, renameEntities);
				CString cstrNameNew = ValueForKey(ent, "name");
				if (cstrNameOld != cstrNameNew)
				{
					RemappedNames.Set(cstrNameOld, cstrNameNew);
				}
				//
				// if (strTarget.GetLength() > 0) SetKeyValue(ent, "target",
				// strTarget.GetBuffer(0));
				// add the entity to the end of the entity list
				//
				ent->next = &entities;
				ent->prev = entities.prev;
				entities.prev->next = ent;
				entities.prev = ent;
				g_qeglobals.d_num_entities++;

				for (b = ent->brushes.onext; b != &ent->brushes; b = b->onext) {
					ptrs.Add(b);
				}
			}
		}

		// now iterate through the remapped names, and see if there are any target-connections that need remaking...
		//
		// (I could probably write this in half the size with STL, but WTF, work with what we have...)
		//
		int iNumKeyVals = RemappedNames.GetNumKeyVals();
		for (int iKeyVal=0; iKeyVal < iNumKeyVals; iKeyVal++)
		{
			const idKeyValue *pKeyVal = RemappedNames.GetKeyVal( iKeyVal );

			LPCSTR psOldName = pKeyVal->GetKey().c_str();
			LPCSTR psNewName = pKeyVal->GetValue().c_str();

			entity_t *pEntOld = FindEntity("name", psOldName);	// original ent we cloned from
			entity_t *pEntNew = FindEntity("name", psNewName);	// cloned ent

			if (pEntOld && pEntNew)
			{
				CString cstrTargetNameOld = ValueForKey(pEntOld, "target");
				if (!cstrTargetNameOld.IsEmpty())
				{
					// ok, this ent was targeted at another ent, so it's clone needs updating to point to
					//	the clone of that target, so...
					//
					entity_t *pEntOldTarget = FindEntity("name", cstrTargetNameOld);
					if ( pEntOldTarget )
					{
						LPCSTR psNewTargetName = RemappedNames.GetString( cstrTargetNameOld );
						if (psNewTargetName && psNewTargetName[0])
						{
							SetKeyValue(pEntNew, "target", psNewTargetName);
						}
					}
				}
			}
		}
	}

	//
	// ::ShowWindow(g_qeglobals.d_hwndEntity, FALSE);
	// ::LockWindowUpdate(g_qeglobals.d_hwndEntity);
	//
	g_bScreenUpdates = false;
	for (int i = 0; i < ptrs.GetSize(); i++) {
		Brush_Build(reinterpret_cast < brush_t * > (ptrs[i]), true, false);
		Select_Brush(reinterpret_cast < brush_t * > (ptrs[i]), true, false);
	}

	// ::LockWindowUpdate(NULL);
	g_bScreenUpdates = true;

	ptrs.RemoveAll();

	//
	// reset the "need conversion" flag conversion to the good format done in
	// Map_BuildBrushData
	//
	g_qeglobals.bNeedConvert = false;

	Sys_UpdateWindows(W_ALL);

	// Sys_MarkMapModified();
	mapModified = 1;

	Undo_End();
}
         CMapStringToString myMap;
         CString myStr[4]={_T("One"), _T("Two"), _T("Three"), _T("Four")};
         CMapStringToString::CPair* pCurVal;

         myMap.InitHashTable(257);

         // Add 4 elements to the map.
         myMap.SetAt(myStr[0], _T("Odd"));
         myMap.SetAt(myStr[1], _T("Even"));
         myMap.SetAt(myStr[2], _T("Odd"));
         myMap.SetAt(myStr[3], _T("Even"));

         pCurVal = myMap.PGetFirstAssoc();
         while (pCurVal != NULL)
         {
            _tprintf_s(_T("Current key value at %s: %s\n"), 
               pCurVal->key, pCurVal->value);
            pCurVal= myMap.PGetNextAssoc(pCurVal);
         }
Example #25
0
//
//================
//Map_ImportFile
// Timo 09/01/99 : called by CXYWnd::Paste & Map_ImportFile
// if Map_ImportFile ( prefab ), the buffer may contain brushes in old format ( conversion needed )
//================
//
void Map_ImportBuffer (char* buf)
{
	entity_t* ent;
	brush_t* b = NULL;
	CPtrArray ptrs;

	Select_Deselect();

	Undo_Start("import buffer");

	g_qeglobals.d_parsed_brushes = 0;
	if (buf)
	{
		CMapStringToString mapStr;
		StartTokenParsing (buf);
		g_qeglobals.d_num_entities = 0;

		// Timo
		// will be used in Entity_Parse to detect if a conversion between brush formats is needed
		g_qeglobals.bNeedConvert = false;
		g_qeglobals.bOldBrushes = false;
		g_qeglobals.bPrimitBrushes = false;

		while (1)
		{

			// use the selected brushes list as it's handy
			//ent = Entity_Parse (false, &selected_brushes);
			ent = Entity_Parse (false, &active_brushes);
			if (!ent)
				break;
			//end entity for undo
			Undo_EndEntity(ent);
			//end brushes for undo
			for(b = ent->brushes.onext; b && b != &ent->brushes; b = b->onext)
			{
				Undo_EndBrush(b);
			}

			if (!strcmp(ValueForKey (ent, "classname"), "worldspawn"))
			{
				// world brushes need to be added to the current world entity

				b=ent->brushes.onext;
				while (b && b != &ent->brushes)
				{
					brush_t* bNext = b->onext;
					Entity_UnlinkBrush(b);
					Entity_LinkBrush(world_entity, b);
					ptrs.Add(b);
					b = bNext;
				}
			}
			else
			{
				// the following bit remaps conflicting target/targetname key/value pairs
				CString str = ValueForKey(ent, "target");
				CString strKey;
				CString strTarget("");
				if (str.GetLength() > 0)
				{
					if (FindEntity("target", str.GetBuffer(0)))
					{
						if (!mapStr.Lookup(str, strKey))
						{
							UniqueTargetName(strKey);
							mapStr.SetAt(str, strKey);
						}
						strTarget = strKey;
						SetKeyValue(ent, "target", strTarget.GetBuffer(0));
					}
				}
				str = ValueForKey(ent, "targetname");
				if (str.GetLength() > 0)
				{
					if (FindEntity("targetname", str.GetBuffer(0)))
					{
						if (!mapStr.Lookup(str, strKey))
						{
							UniqueTargetName(strKey);
							mapStr.SetAt(str, strKey);
						}
						SetKeyValue(ent, "targetname", strKey.GetBuffer(0));
					}
				}
				//if (strTarget.GetLength() > 0)
				//  SetKeyValue(ent, "target", strTarget.GetBuffer(0));

				// add the entity to the end of the entity list
				ent->next = &entities;
				ent->prev = entities.prev;
				entities.prev->next = ent;
				entities.prev = ent;
				g_qeglobals.d_num_entities++;

				for (b=ent->brushes.onext ; b != &ent->brushes ; b=b->onext)
				{
					ptrs.Add(b);
				}
			}
		}
	}

	//::ShowWindow(g_qeglobals.d_hwndEntity, FALSE);
	//::LockWindowUpdate(g_qeglobals.d_hwndEntity);
	g_bScreenUpdates = false; 
	for (int i = 0; i < ptrs.GetSize(); i++)
	{
		Brush_Build(reinterpret_cast<brush_t*>(ptrs[i]), true, false);
		Select_Brush(reinterpret_cast<brush_t*>(ptrs[i]), true, false);
	}
	//::LockWindowUpdate(NULL);
	g_bScreenUpdates = true; 

	ptrs.RemoveAll();

	// reset the "need conversion" flag
	// conversion to the good format done in Map_BuildBrushData
	g_qeglobals.bNeedConvert=false;

	Sys_UpdateWindows (W_ALL);
  //Sys_MarkMapModified();
	modified = true;

	Undo_End();

}