void CConnectRemoteMachineWindow::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here
	CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd);
	byte ips[4];

	if (0 == m_ip.GetAddress(ips[0],ips[1],ips[2],ips[3]))
	{
		AfxMessageBox(L"address is error!");
		return;
	}
	
	char strip[256];
	sprintf_s(strip, 256, "%d.%d.%d.%d", ips[0],ips[1],ips[2],ips[3]);
	
	KBEngine::u_int16_t port = 0;
	CString sport;
	m_port.GetWindowTextW(sport);
	char* csport = KBEngine::strutil::wchar2char(sport.GetBuffer(0));
	port = atoi(csport);
	std::string command = strip;
	command += ":";
	command += csport;
	free(csport);

	KBEngine::Network::EndPoint* endpoint = KBEngine::Network::EndPoint::ObjPool().createObject();

	KBEngine::u_int32_t address;
	Network::Address::string2ip(strip, address);
	KBEngine::Network::Address addr(address, htons(port));

	if(addr.ip == 0)
	{
		::AfxMessageBox(L"address is error!");
		KBEngine::Network::EndPoint::ObjPool().reclaimObject(endpoint);
		return;
	}

	endpoint->socket(SOCK_STREAM);
	if (!endpoint->good())
	{
		AfxMessageBox(L"couldn't create a socket\n");
		KBEngine::Network::EndPoint::ObjPool().reclaimObject(endpoint);
		return;
	}

	endpoint->addr(addr);
	if(endpoint->connect(addr.port, addr.ip) == -1)
	{
		CString err;
		err.Format(L"connect server is error! %d", ::WSAGetLastError());
		AfxMessageBox(err);
		KBEngine::Network::EndPoint::ObjPool().reclaimObject(endpoint);
		return;
	}

	endpoint->setnonblocking(false);
	int8 findComponentTypes[] = {LOGGER_TYPE, BASEAPP_TYPE, CELLAPP_TYPE, BASEAPPMGR_TYPE, CELLAPPMGR_TYPE, LOGINAPP_TYPE, DBMGR_TYPE, BOTS_TYPE, UNKNOWN_COMPONENT_TYPE};
	int ifind = 0;

	while(true)
	{
		int8 findComponentType = findComponentTypes[ifind++];
		if(findComponentType == UNKNOWN_COMPONENT_TYPE)
		{
			//INFO_MSG("Componentbridge::process: not found %s, try again...\n",
			//	COMPONENT_NAME_EX(findComponentType));
			break;
		}

		KBEngine::Network::Bundle bhandler;
		bhandler.newMessage(KBEngine::MachineInterface::onFindInterfaceAddr);

		KBEngine::MachineInterface::onFindInterfaceAddrArgs7::staticAddToBundle(bhandler, KBEngine::getUserUID(), KBEngine::getUsername(), 
			CONSOLE_TYPE, g_componentID, (COMPONENT_TYPE)findComponentType, 0, 0);

		endpoint->send(&bhandler);

		KBEngine::Network::TCPPacket packet;
		packet.resize(65535);

		endpoint->setnonblocking(true);
		KBEngine::sleep(300);
		packet.wpos(endpoint->recv(packet.data(), 65535));

		while(packet.length() > 0)
		{
			MachineInterface::onBroadcastInterfaceArgs24 args;
			
			try
			{
				args.createFromStream(packet);
			}catch(MemoryStreamException &)
			{
				goto END;
			}

			INFO_MSG(fmt::format("CConnectRemoteMachineWindow::OnBnClickedOk: found {}, addr:{}:{}\n",
				COMPONENT_NAME_EX((COMPONENT_TYPE)args.componentType), inet_ntoa((struct in_addr&)args.intaddr), ntohs(args.intport)));

			Components::getSingleton().addComponent(args.uid, args.username.c_str(), 
				(KBEngine::COMPONENT_TYPE)args.componentType, args.componentID, args.globalorderid, args.grouporderid, 
				args.intaddr, args.intport, args.extaddr, args.extport, args.extaddrEx, args.pid, args.cpu, args.mem, args.usedmem, 
				args.extradata, args.extradata1, args.extradata2, args.extradata3);

		}
	}
END:
	dlg->updateTree();

	KBEngine::Network::EndPoint::ObjPool().reclaimObject(endpoint);
	wchar_t* wcommand = KBEngine::strutil::char2wchar(command.c_str());
	bool found = false;
	std::deque<CString>::iterator iter = m_historyCommand.begin();
	for(; iter != m_historyCommand.end(); iter++)
	{
		if((*iter) == wcommand)
		{
			found = true;
			break;
		}
	}
	
	if(!found)
	{
		m_historyCommand.push_front(wcommand);
		if(m_historyCommand.size() > 10)
			m_historyCommand.pop_back();

		saveHistory();
	}

	free(wcommand);

	OnOK(); 
}
Ejemplo n.º 2
0
void RunBsp (char *command)
{
	char	sys[2048];
	char	batpath[2048];
	char	outputpath[2048];
	char	temppath[1024];
	char	name[2048];
	char	cWork[2048];
	FILE	*hFile;
	BOOL	ret;
	PROCESS_INFORMATION ProcessInformation;
	STARTUPINFO	startupinfo;
  HWND hwndPClient = NULL;

  g_hWnd = g_pParentWnd->GetSafeHwnd();
	SetInspectorMode(W_CONSOLE);
  g_tBegin = CTime::GetCurrentTime();

	
	DWORD	dwExitcode;
  ret = GetExitCodeProcess (g_hToolThread, &dwExitcode);
  if (dwExitcode != STILL_ACTIVE)
    g_hToolThread = NULL;

	if (bsp_process || g_hToolThread)
	{
		Sys_Printf ("BSP is still going...\n");
		return;
	}

  outputpath[0] = '\0';
	GetTempPath(512, temppath);

  CString strOutFile = temppath;
  AddSlash(strOutFile);
  strOutFile += "junk.txt";

	sprintf (outputpath, " >>%s\r\n", strOutFile);

  strcpy (name, currentmap);
	if (region_active)
	{
		Map_SaveFile (name, false);
		StripExtension (name);
		strcat (name, ".reg");
	}

	Map_SaveFile (name, region_active);

  // FIXME: this code just gets worse and worse
  CString strPath, strFile;

  char *rsh = ValueForKey(g_qeglobals.d_project_entity, "rshcmd");
  if (rsh == NULL)
  {
    ExtractPath_and_Filename(name, strPath, strFile);
    AddSlash(strPath);
    BuildShortPathName(strPath, cWork, 1024);
    strcat(cWork, strFile);
  }
  else
  {
    strcpy(cWork, name);
  }

  hwndPClient = FindWindow(NULL, "Q3Map Process Client");
  if ( hwndPClient == NULL ) {
    hwndPClient = FindAnyWindow("Q3Map Process Client");
  }

  Sys_Printf("Window info for Process Client %i\n", reinterpret_cast<int>(hwndPClient));

  bool processServer = (rsh && strlen(rsh) > 0 && hwndPClient);

  QE_ExpandBspString (command, sys, cWork, processServer);

  // if we can find the q3map process server running 
  // we will submit maps to it instead of via createprocess
  //
  if (processServer)
  {
    CString str;
    char cBuff[2048];
    char *pStart = sys;
    char *pEnd = strstr(pStart, "&&");
    while (pEnd)
    {
      int nLen = pEnd-pStart-1;
      strncpy(cBuff, pStart, nLen);
      cBuff[nLen] = 0;
      str = cBuff;
      FindReplace(str, rsh, "");
      str.TrimLeft(' ');
      str.TrimRight(' ');
      ATOM a = GlobalAddAtom(str);
      PostMessage(hwndPClient, wm_AddCommand, 0, (LPARAM)a);
      pStart = pEnd+2;
      pEnd = strstr(pStart, "&&");
    }
    str = pStart;
    FindReplace(str, rsh, "");
    str.TrimLeft(' ');
    str.TrimRight(' ');
    ATOM a = GlobalAddAtom(str);
    PostMessage(hwndPClient, wm_AddCommand, 0, (LPARAM)a);
    Sys_Printf("Commands sent to Q3Map Process Client\n");
    return;
  }

  CString strSys = sys;

  FindReplace(strSys, "&&", outputpath);
  strcpy(sys, strSys);
  strcat(sys, outputpath);

  if (g_PrefsDlg.m_bInternalBSP)
  {
    g_tBegin = CTime::GetCurrentTime();
    strSys.MakeLower();
    char* p = new char[strSys.GetLength()+1];
    strcpy(p, strSys.GetBuffer(0));
    ThreadTools(p);
  }
  else
  {
	  Sys_ClearPrintf ();
	  Sys_Printf ("==================\nRunning bsp command...\n");
	  Sys_Printf ("\n%s\n", sys);

	  //++timo removed the old way BSP commands .. dumping to junk.txt doesn't work on my win98 box
	  // FIXME : will most likely break Quake2 BSP commands, is fitted to a one-lined sys command
	  //
	  // write qe3bsp.bat
	  //

	  sprintf (batpath, "%sqe3bsp.bat", temppath);
	  hFile = fopen(batpath, "w");
	  if (!hFile)
		  Error ("Can't write to %s", batpath);
	  fprintf (hFile, sys);
	  fclose (hFile);

	  Pointfile_Delete ();

	  // delete junk.txt file
	  remove(strOutFile);

	  GetStartupInfo (&startupinfo);

	  ret = CreateProcess(
		  batpath,
		  NULL,
		  NULL,
		  NULL,
		  FALSE,
		  0,
		  NULL,
		  NULL,
		  &startupinfo,
		  &ProcessInformation
		  );

	  if (!ret)
		  Error ("CreateProcess failed");

	  bsp_process = ProcessInformation.hProcess;

	  Sleep (100);	// give the new process a chance to open it's window

	  BringWindowToTop( g_qeglobals.d_hwndMain );	// pop us back on top
#if 0
	  //
	  // write qe3bsp.bat
	  //
	  sprintf (batpath, "%sqe3bsp.bat", temppath);
	  hFile = fopen(batpath, "w");
	  if (!hFile)
		  Error ("Can't write to %s", batpath);
	  fprintf (hFile, sys);
	  fclose (hFile);

	  //
	  // write qe3bsp2.bat
	  //
	  sprintf (batpath, "%sqe3bsp2.bat", temppath);
	  hFile = fopen(batpath, "w");
	  if (!hFile)
		  Error ("Can't write to %s", batpath);
	  fprintf (hFile, "%sqe3bsp.bat > %s", temppath, outputpath);
	  fclose (hFile);

	  Pointfile_Delete ();

	  GetStartupInfo (&startupinfo);

	  ret = CreateProcess(
      batpath,		// pointer to name of executable module 
      NULL,			// pointer to command line string
      NULL,			// pointer to process security attributes 
      NULL,			// pointer to thread security attributes 
      FALSE,			// handle inheritance flag 
      0 /*DETACHED_PROCESS*/,		// creation flags
      NULL,			// pointer to new environment block 
      NULL,			// pointer to current directory name 
      &startupinfo,	// pointer to STARTUPINFO 
      &ProcessInformation 	// pointer to PROCESS_INFORMATION  
     );

	  if (!ret)
		  Error ("CreateProcess failed");

	  bsp_process = ProcessInformation.hProcess;

	  Sleep (100);	// give the new process a chance to open it's window

	  //BringWindowToTop( g_qeglobals.d_hwndMain );	// pop us back on top
	  //SetFocus (g_qeglobals.d_hwndCamera);
#endif
  }
}
Ejemplo n.º 3
0
Bool CCompiler::OnInit( const char* sourceCode, const char* programInput, const char* helperSolutionPath )
{
    CL_TRACE("Initializing Compiler with");
    if( !sourceCode )
    {
        CL_ERROR("Failed to init Compiler! Source code is NULL");
        return false;
    }

    m_programInput = programInput;
    m_sourceCodeToCompile = sourceCode;

    if( !helperSolutionPath )
    {
        CL_ERROR(" helper solution path not found");
        return false;
    }


    // set helper solution path and validate it;
    m_helperSolutionPath = helperSolutionPath;
    if( !CPath::IsAbsolute(m_helperSolutionPath) )
    {
        CL_ERROR("solution path provided is not absolute:[%s]", m_helperSolutionPath.GetBuffer() );
        return false;
    }
    if( !CPath::DirectoryExists(m_helperSolutionPath) )
    {
        CL_ERROR( "solution directoy does not exists:[%s]", m_helperSolutionPath.GetBuffer() );
        return false;
    }

    if( !CPath::GetCurrPath( m_workingDir ) )
    {
        CL_ERROR("initialization step failed. Cannot get current directory");
        return false;
    }

    CPath::SetCurrPath( m_helperSolutionPath );

    if( !CPath::GetAbsolutePath(ms_compilerLogFile, m_compilerOutputFile) )
    {
        CL_ERROR( "failed to get absolute path from path:[%s]", ms_compilerLogFile );
        return false;
    }

    // get path to devenv and validate it;
    CString vsToolsPath;
    ThGetEnvVariable( ms_vsEnvToolsVar, vsToolsPath );
    vsToolsPath += "..\\IDE\\";
    if( !CPath::GetAbsolutePath(vsToolsPath, m_devenvPath ) )
    {
        CL_ERROR( " failed to get devenv absolute path from tools path:[%s]", vsToolsPath.GetBuffer() );
        return false;
    }
    CString devenvExecutableFullPath = m_devenvPath + "devenv.exe";
    if( !CPath::FileExists( devenvExecutableFullPath ) )
    {
        CL_ERROR( "failed to get path to devenv.exe. We got [%s] but this file does not exists!", devenvExecutableFullPath.GetBuffer() );
        return false;
    }

    CL_TRACE("Compile initialization succeeded");
    return true;
}
Ejemplo n.º 4
0
int Run(LPTSTR /*lpstrCmdLine*/ = NULL, int /*nCmdShow*/ = SW_SHOWDEFAULT)
{ 
	int nRet = 0; // Return code
	CErrorReportDlg dlgErrorReport; // Error Report dialog
	CResendDlg dlgResend; // Resend dialog

	// Get command line parameters.
	LPCWSTR szCommandLine = GetCommandLineW();

    // Split command line.
    int argc = 0;
    LPWSTR* argv = CommandLineToArgvW(szCommandLine, &argc);

    // Check parameter count.
    if(argc!=2)
        return 1; // No arguments passed, exit.

	if(_tcscmp(argv[1], _T("/terminate"))==0)
	{
		// User wants us to find and terminate all instances of CrashSender.exe
		return CErrorReportSender::TerminateAllCrashSenderProcesses();
	}

	// Extract file mapping name from command line arg.    
    CString sFileMappingName = CString(argv[1]);
		
	// Create the sender model that will collect crash report data 
	// and send error report(s).
	CErrorReportSender* pSender = CErrorReportSender::GetInstance();

	// Init the sender object
	BOOL bInit = pSender->Init(sFileMappingName.GetBuffer(0));
	if(!bInit)
    {
		// Failed to init        
        return 0;
    }      

	// Determine what to do next 
	// (either run in GUI more or run in silent mode).
	if(!pSender->GetCrashInfo()->m_bSilentMode)
	{
		// GUI mode.
		// Create message loop.
		CMessageLoop theLoop;
		_Module.AddMessageLoop(&theLoop);

		if(!pSender->GetCrashInfo()->m_bSendRecentReports)
		{
			// Create "Error Report" dialog			
			if(dlgErrorReport.Create(NULL) == NULL)
			{
				ATLTRACE(_T("Error report dialog creation failed!\n"));
				return 1;
			}			
		}
		else
		{        
			// Create "Send Error Reports" dialog.					
			if(dlgResend.Create(NULL) == NULL)
			{
				ATLTRACE(_T("Resend dialog creation failed!\n"));
				return 1;
			}			
		}

		// Process window messages.
		nRet = theLoop.Run();	    
		_Module.RemoveMessageLoop();
	}
	else
	{
		// Silent (non-GUI mode).
		// Run the sender and wait until it exits.
		pSender->Run();
		pSender->WaitForCompletion();
		// Get return status
		nRet = pSender->GetStatus();
	}
    
	// Delete sender object.
	delete pSender;

	// Exit.
    return nRet;
}
void CUserAddDlg::OnBnClickedOk()
{
	UpdateData();

	m_strName.TrimLeft();
	m_strName.TrimRight();
	m_strGroupName.TrimLeft();
	m_strGroupName.TrimRight();
	
	//验证输入的数据是否合法
	if ( "" == m_strName )
	{
		MessageBox(_CS("AccountMSG.EmptyName"), _CS("OneClick.Prompt"));
		return;
	}
	if(m_strName[0]=='&')
	{
		
		MessageBox(_CS("AccountMSG.ErrorName"), _CS("OneClick.Prompt"));
		
		return;
	}
	if(m_strName.Find('.')!=-1||m_strName.Find('[')!=-1||m_strName.Find(']')!=-1 || m_strName.Find('%') != -1)
	{
		
		MessageBox(_CS("AccountMSG.ErrorName"), _CS("OneClick.Prompt"));
		return;
	}

	//验证密码是否匹配
	if ( m_strPsw != m_strConfirm )
	{
		MessageBox(_CS("Error.PwdErr"), _CS("OneClick.Prompt"));
		return;
	}
	
	//验证用户名是否已经存在

	if ( FindUserName(m_strName.GetBuffer(0)) )
	{
		MessageBox(_CS("AccountMSG.AddUserExist"), _CS("OneClick.Prompt"));
		return;
	}

	USER_INFO userInfo;

	//获取选择的权限列表
	int nIndex = 0;
	int nSize = m_listAuthority.GetItemCount();
	for ( int i = 0; i < nSize; i ++ )
	{
		if ( m_listAuthority.GetCheck(i) )
		{
			CString strName = (char *)m_listAuthority.GetItemData(i);
			strcpy( userInfo.rights[nIndex ++], strName.GetBuffer(0) );
		}
	}
	userInfo.rigthNum = nIndex;
	if ( nIndex <= 0 )
	{
		MessageBox(_CS("AccountMSG.EmptyAuthority"), _CS("OneClick.Prompt"));

		return;
	}

	userInfo.reserved = false;
	userInfo.shareable = m_checkReuseable.GetCheck();
	strcpy ( userInfo.Groupname, m_strGroupName.GetBuffer(0) );
	strcpy ( userInfo.memo, m_strDescribe.GetBuffer(0) );
	strcpy ( userInfo.name, m_strName.GetBuffer(0) );
	strcpy ( userInfo.passWord, m_strPsw.GetBuffer(0) );
	
		//保存用户	
		int bRet = SaveuserInfo(&userInfo);
		if ( bRet <= 0 )
		{
			CString strMsg(_CS("User.AddUserFailed"));
			CString strError = GetSdkErrorInfo( bRet );
			strMsg += strError;
			MessageBox(strMsg, _CS("OneClick.Prompt"));

			return;
		}
	

	MessageBox(_CS("AccountMSG.AddUserSuccess"), _CS("OneClick.Prompt"));
	OnOK();
}
Ejemplo n.º 6
0
void CSimSysManager::CopySIMDataFromBuffer(xmlNodePtr pDoc, ETYPE_BUS eBus)
{
    /*xmlChar* pXpath = NULL;
    xmlXPathObjectPtr pObjectPath = NULL;

    if(eBus == CAN)
    {
        pXpath = (xmlChar*)"//BUSMASTER_CONFIGURATION/Module_Configuration/CAN_Simulated_Systems";
        pObjectPath = xmlUtils::pGetNodes(pDoc, pXpath);
    }
    else if(eBus == J1939)
    {
        pXpath = (xmlChar*)"//BUSMASTER_CONFIGURATION/Module_Configuration/J1939_Simulated_Systems";
        pObjectPath = xmlUtils::pGetNodes(pDoc, pXpath);
    }

    if(m_CopyJ1939SimNode != NULL && (eBus == J1939))
    {
        xmlFreeNode(m_CopyJ1939SimNode);
        m_CopyJ1939SimNode = NULL;
    }

    else if(pObjectPath != NULL && (eBus == J1939))
    {
        m_CopyJ1939SimNode = xmlCopyNode(pObjectPath->nodesetval->nodeTab[0], 1);
    }
    else
    {
        xmlFreeNode(m_CopyJ1939SimNode);
        m_CopyJ1939SimNode = NULL;
    }*/

    xmlNodePtr pNode = pDoc;
    //if( NULL != pObjectPath )
    {
        //xmlNodeSetPtr pNodeSet = pObjectPath->nodesetval;
        //if( NULL != pNodeSet )
        //{
        //  pNode = pNodeSet->nodeTab[0];       //Take First One only
        //}
        if( NULL != pNode )
        {
            pNode = pNode->xmlChildrenNode;
            while (pNode != NULL)
            {
                if ((!xmlStrcmp(pNode->name, (const xmlChar*)"Window_Position")))
                {
                    xmlUtils::ParseWindowsPlacement(pNode, CGlobalObj::ouGetObj(m_eBus).m_wWindowPlacement);
                }
                if ((!xmlStrcmp(pNode->name, (const xmlChar*)"Sym_Path")))
                {
                    xmlChar* key = xmlNodeListGetString(pNode->doc, pNode->xmlChildrenNode, 1);
                    if(NULL != key)
                    {
                        CString omStrFileName;
                        if(PathIsRelative((char*)key) == TRUE)
                        {
                            string omStrConfigFolder;
                            string omPath;
                            char configPath[MAX_PATH];
                            AfxGetMainWnd()->SendMessage(MSG_GET_CONFIGPATH, (WPARAM)configPath, 0);
                            CUtilFunctions::nGetBaseFolder(configPath, omStrConfigFolder );
                            char chAbsPath[MAX_PATH];
                            PathCombine(chAbsPath, omStrConfigFolder.c_str(), (char*)key);
                            omStrFileName = chAbsPath;
                        }
                        else
                        {
                            omStrFileName = (char*)key;
                        }
                        vLoadSimInfoFromConfiguration(omStrFileName.GetBuffer(MAX_PATH));
                        xmlFree(key);
                    }
                }
                pNode = pNode->next;
            }
        }
        //xmlXPathFreeObject(pObjectPath);
    }
    /*
    COPY_DATA_2(&CGlobalObj::ouGetObj(m_eBus).m_wWindowPlacement, tempBuffAddress, sizeof(WINDOWPLACEMENT));
    UINT UnCount = 0;
    COPY_DATA_2(&UnCount, tempBuffAddress, sizeof(UINT));

    CString omTmp = "";
    for (UINT i = 0; i < UnCount; i++)
    {
        char acFilename[MAX_PATH] = {'\0'};
        COPY_DATA_2(acFilename, tempBuffAddress, sizeof (char) * MAX_PATH);
        omTmp.Format("%s", acFilename);
        //Add the simsys file details
        vLoadSimInfoFromConfiguration(omTmp);
    }*/
}
int GetVariableValue(int index ,CString &ret_cstring,CString &ret_unit,CString &Auto_M,int &digital_value)
{
	CStringArray temparray;
	CString temp1;
	if(index >= BAC_VARIABLE_ITEM_COUNT)
	{
		ret_cstring.Empty();
		ret_unit.Empty();
		Auto_M.Empty();
		return -1;
	}
	int i = index;

	if(m_Variable_data.at(i).auto_manual == 1)
	{
		Auto_M = _T("M");
	}
	else
	{
		Auto_M.Empty();
	}

	if(m_Variable_data.at(i).digital_analog == BAC_UNITS_DIGITAL)
	{
		if(m_Variable_data.at(i).range>30)
		{
			ret_cstring.Empty();
			return -1;
		}
		else
		{
			if((m_Variable_data.at(i).range < 23) &&(m_Variable_data.at(i).range !=0))
				temp1 = Digital_Units_Array[m_Variable_data.at(i).range];
			else if((m_Variable_data.at(i).range >=23) && (m_Variable_data.at(i).range <= 30))
			{
				if(receive_customer_unit)
					temp1 = temp_unit_no_index[m_Variable_data.at(i).range - 23];
			}
			else
			{
				ret_cstring.Empty();
				return -1;
			}


			SplitCStringA(temparray,temp1,_T("/"));
			if((temparray.GetSize()==2))
			{
				if(m_Variable_data.at(i).control == 0)
				{
					digital_value = 0;
					ret_cstring = temparray.GetAt(0);
					return 1;
				}
				else
				{
					digital_value = 1;
					ret_cstring = temparray.GetAt(1);
				}
			}

		}
	}
	else
	{
		if(m_Variable_data.at(i).range == 20)	//如果是时间;
		{
			ret_unit = Variable_Analog_Units_Array[m_Variable_data.at(i).range];
			char temp_char[50];
			int time_seconds = m_Variable_data.at(i).value / 1000;
			intervaltotext(temp_char,time_seconds,0,0);

			MultiByteToWideChar( CP_ACP, 0, temp_char, strlen(temp_char) + 1, 
				ret_cstring.GetBuffer(MAX_PATH), MAX_PATH );
			ret_cstring.ReleaseBuffer();	
			digital_value = 2;
		}
		else if((m_Variable_data.at(i).range<=sizeof(Variable_Analog_Units_Array)/sizeof(Variable_Analog_Units_Array[0])) && (m_Variable_data.at(i).range != 0))
		{
			ret_unit = Variable_Analog_Units_Array[m_Variable_data.at(i).range];
			CString cstemp_value;
			float temp_float_value;
			temp_float_value = ((float)m_Variable_data.at(i).value) / 1000;
			ret_cstring.Format(_T("%.3f"),temp_float_value);
			digital_value = 2;
		}
		else
		{
			ret_cstring.Empty();
			return -1;
		}
	}

	return 1;
}
Ejemplo n.º 8
0
CString CMpeg2DataParser::ConvertString(BYTE* pBuffer, int nLength)
{
    static const UINT16 codepages[0x20] = {
        28591,  // 00 - ISO 8859-1 Latin I
        28595,  // 01 - ISO 8859-5 Cyrillic
        28596,  // 02 - ISO 8859-6 Arabic
        28597,  // 03 - ISO 8859-7 Greek
        28598,  // 04 - ISO 8859-8 Hebrew
        28599,  // 05 - ISO 8859-9 Latin 5
        28591,  // 06 - ??? - ISO/IEC 8859-10 - Latin alphabet No. 6
        28591,  // 07 - ??? - ISO/IEC 8859-11 - Latin/Thai (draft only)
        28591,  // 08 - reserved
        28603,  // 09 - ISO 8859-13 - Estonian
        28591,  // 0a - ??? - ISO/IEC 8859-14 - Latin alphabet No. 8 (Celtic)
        28605,  // 0b - ISO 8859-15 Latin 9
        28591,  // 0c - reserved
        28591,  // 0d - reserved
        28591,  // 0e - reserved
        28591,  // 0f - reserved
        0,      // 10 - See codepages10 array
        28591,  // 11 - ??? - ISO/IEC 10646 - Basic Multilingual Plane (BMP)
        28591,  // 12 - ??? - KSX1001-2004 - Korean Character Set
        20936,  // 13 - Chinese Simplified (GB2312-80)
        950,    // 14 - Chinese Traditional (Big5)
        28591,  // 15 - ??? - UTF-8 encoding of ISO/IEC 10646 - Basic Multilingual Plane (BMP)
        28591,  // 16 - reserved
        28591,  // 17 - reserved
        28591,  // 18 - reserved
        28591,  // 19 - reserved
        28591,  // 1a - reserved
        28591,  // 1b - reserved
        28591,  // 1c - reserved
        28591,  // 1d - reserved
        28591,  // 1e - reserved
        28591   // 1f - TODO!
    };

    static const UINT16 codepages10[0x10] = {
        28591,  // 00 - reserved
        28591,  // 01 - ISO 8859-1 Western European
        28592,  // 02 - ISO 8859-2 Central European
        28593,  // 03 - ISO 8859-3 Latin 3
        28594,  // 04 - ISO 8859-4 Baltic
        28595,  // 05 - ISO 8859-5 Cyrillic
        28596,  // 06 - ISO 8859-6 Arabic
        28597,  // 07 - ISO 8859-7 Greek
        28598,  // 08 - ISO 8859-8 Hebrew
        28599,  // 09 - ISO 8859-9 Turkish
        28591,  // 0a - ??? - ISO/IEC 8859-10
        28591,  // 0b - ??? - ISO/IEC 8859-11
        28591,  // 0c - ??? - ISO/IEC 8859-12
        28603,  // 0d - ISO 8859-13 Estonian
        28591,  // 0e - ??? - ISO/IEC 8859-14
        28605,  // 0f - ISO 8859-15 Latin 9

        // 0x10 to 0xFF - reserved for future use
    };

    UINT cp = CP_ACP;
    int nDestSize;
    CString strResult;

    if (nLength > 0) {
        if (pBuffer[0] == 0x10) {
            pBuffer++;
            nLength--;
            if (pBuffer[0] == 0x00) {
                cp = codepages10[pBuffer[1]];
            } else { // if (pBuffer[0] > 0x00)
                // reserved for future use, use default codepage
                cp = codepages[0];
            }
            pBuffer += 2;
            nLength -= 2;
        } else if (pBuffer[0] < 0x20) {
            cp = codepages[pBuffer[0]];
            pBuffer++;
            nLength--;
        } else { // No code page indication, use the default
            cp = codepages[0];
        }
    }

    nDestSize = MultiByteToWideChar(cp, MB_PRECOMPOSED, (LPCSTR)pBuffer, nLength, NULL, 0);
    if (nDestSize < 0) {
        return strResult;
    }

    MultiByteToWideChar(cp, MB_PRECOMPOSED, (LPCSTR)pBuffer, nLength, strResult.GetBuffer(nLength), nDestSize);
    strResult.ReleaseBuffer();

    return strResult;
}
Ejemplo n.º 9
0
bool ImageHandler::GetDesktopImageData(ImageData& imageData)
{
	CRegKey keyColors;

	if (keyColors.Open(HKEY_CURRENT_USER, L"Control Panel\\Colors", KEY_READ) != ERROR_SUCCESS) return false;

	CString	strBackground;
	DWORD	dwDataSize = 32;

	if (keyColors.QueryStringValue(L"Background", strBackground.GetBuffer(dwDataSize), &dwDataSize) != ERROR_SUCCESS)
	{
		strBackground.ReleaseBuffer();
		return false;
	}
	strBackground.ReleaseBuffer();

	wstringstream	streamBk(wstring(strBackground.operator LPCTSTR()));
	DWORD			r = 0;
	DWORD			g = 0;
	DWORD			b = 0;

	streamBk >> r;
	streamBk >> g;
	streamBk >> b;

	CRegKey keyDesktop;
	if (keyDesktop.Open(HKEY_CURRENT_USER, L"Control Panel\\Desktop", KEY_READ) != ERROR_SUCCESS) return false;

	DWORD	dwChars = 0;
	CString	strWallpaperFile;
	CString	strWallpaperStyle;
	CString	strWallpaperTile;

	dwChars = 32;
	keyDesktop.QueryStringValue(L"WallpaperStyle", strWallpaperStyle.GetBuffer(dwChars), &dwChars);
	dwChars = 32;
	keyDesktop.QueryStringValue(L"TileWallpaper", strWallpaperTile.GetBuffer(dwChars), &dwChars);
	dwChars = MAX_PATH;
	keyDesktop.QueryStringValue(L"Wallpaper", strWallpaperFile.GetBuffer(dwChars), &dwChars);

	strWallpaperStyle.ReleaseBuffer();
	strWallpaperFile.ReleaseBuffer();
	strWallpaperTile.ReleaseBuffer();

	// set background data
	imageData.strFilename	= strWallpaperFile;
	imageData.bRelative		= true;
	imageData.bExtend		= false;
	imageData.crBackground	= RGB(static_cast<BYTE>(r), static_cast<BYTE>(g), static_cast<BYTE>(b));

	if (strWallpaperTile == L"1")
	{
		imageData.imagePosition= imagePositionTile;
	}
	else
	{
		if (strWallpaperStyle == L"0")
		{
			imageData.imagePosition= imagePositionCenter;
		}
		else if (strWallpaperStyle == L"6")
		{
			imageData.imagePosition= imagePositionFit;
		}
		else if (strWallpaperStyle == L"10")
		{
			imageData.imagePosition= imagePositionFill;
		}
		else if (strWallpaperStyle == L"22")
		{
			imageData.imagePosition= imagePositionFill;
			imageData.bExtend = true;
		}
		else
		{
			imageData.imagePosition= imagePositionStretch;
		}
	}

#if _WIN32_WINNT >= 0x0602
	if( ImageHandler::IsWin8() )
	{
		CComPtr<IDesktopWallpaper> desktopWallpaper;
		HRESULT hr = desktopWallpaper.CoCreateInstance(CLSID_DesktopWallpaper, nullptr, CLSCTX_ALL);
		if( SUCCEEDED(hr) )
		{
			DESKTOP_WALLPAPER_POSITION position;
			hr = desktopWallpaper->GetPosition(&position);

			UINT count = 0;
			hr = desktopWallpaper->GetMonitorDevicePathCount(&count);
			if( hr == S_OK && position == DWPOS_SPAN && count > 1 )
			{
				CComHeapPtr<wchar_t> spszWallpaper;
				hr = desktopWallpaper->GetWallpaper(NULL, &spszWallpaper);
				if( hr == S_OK )
					imageData.bExtend = true;
			}
		}
	}
#endif

	return true;
}
Ejemplo n.º 10
0
bool ModelFriend::setAtribut(CString& atribut_nou)
{
	atribut.Empty();
	int z,l,a;
	char data[11],zi[3],luna[34],an[5];

	strcpy(data,atribut_nou.GetBuffer());
	strcpy(zi,"");
	strcpy(luna,"");
	strcpy(an,"");

	int i=0;
	int j=0;
	while(isdigit(data[j])!=0)
		zi[i++]=data[j++];
	zi[i]=0;

	if(j==0)
		return false;

	data[j++]='/';


	i=0;
	while(isdigit(data[j])!=0)
		luna[i++]=data[j++];
	luna[i]=0;
		
	if(j==1)
		return false;

	data[j++]='/';


	i=0;
	while(isdigit(data[j])!=0)
		an[i++]=data[j++];
	an[i]=0;

	z=atoi(zi);
	l=atoi(luna);
	a=atoi(an);

	if(a<0)
		a=0;
	if(a>9999)
		a=9999;

	if(l<0)
		l=1;
	if(l>12)
		l=12;

	bool bisect;

	if(((a%4==0)&&(a%100!=0))||(a%400==0))
		bisect=true;

	if(z<0)
		z=1;

	switch(l)
	{
	case 1: case 3: case 5: case 7: case 8: case 10: case  12: if(z>31) z=31;
	case 2:
		if(bisect)
		{
			if(z>29)
				z=29;
		}
		else
			if(z>28)
				z=28;
	case 4: case 6: case 9: case 11: if(z>30) z=30;	
	}
		
	strcpy(data,"");

	strcpy(data,itoa(z,zi,10));
	strcat(data,"/");
	strcat(data,itoa(l,luna,10));
	strcat(data,"/");
	strcat(data,itoa(a,an,10));

	atribut=data;
	
	return true;
}
Ejemplo n.º 11
0
//*========================================================================================
//*函数: bool CSmartJZSRCTable::Convert(TSSmartDoc *pDoc, unsigned char *ucRawData)
//*功能: 转换结构
//*参数: 略
//*返回: 是否成功
//*说明: 虚基类程序
//*========================================================================================
bool CSmartJZSRCTable::Convert(int nAuthNo, TSSmartDoc *pDoc, unsigned char *ucRawData, char *pszAdjustCode)
{
	CString  strValue = "" ;
	CString  strText = "";
	CString  strData = "";
	char     szDateTime[7];

	CString strDealCode = "20";

	//收费机 0232 上机上网机
	if( !strcmp(pDoc->m_szMacCode, "0226") || 
		!strcmp(pDoc->m_szMacCode, "0232") )
	{
		strDealCode = "91";
	}
	//增值机
	else if( !strcmp(pDoc->m_szMacCode, "0201") )
	{
		strDealCode = "90";
	}

	CTime  t = CTime::GetCurrentTime();
	strText.Format("%04d-%02d-%02d %02d:%02d:%02d  ", 
		t.GetYear(), t.GetMonth(), t.GetDay(),
		t.GetHour(), t.GetMinute(), t.GetSecond());

	sprintf(szDateTime, "%04d%02d", t.GetYear(), t.GetMonth()); 

	m_strTableName.Format("Smart_JZSource%04d%02d", t.GetYear(), t.GetMonth());

	strValue.Format("注册号:%.2X%.2X%.2X%.2X ",ucRawData[0],ucRawData[1],ucRawData[2],ucRawData[3]); strText += strValue ;
	GetValue(strValue, m_SRC.sMachineID);
	strValue.Format("%s", m_SRC.sMachineID); strData+= strValue;

	strValue.Format("扎帐流水:%d ",  ucRawData[6]*256+ucRawData[7]); strText += strValue ;
	GetValue(strValue, m_SRC.nSettleInvoice);
	strValue.Format("%d", m_SRC.nSettleInvoice); strData+= strValue;

	if( !IsValidDateTime(&ucRawData[8])  )
	{
		char szDateTime[24];
		GetCurDateTime(szDateTime);
		strValue = szDateTime;  strText += strValue ;
		GetValue(strValue, m_SRC.sSettleTime);
	}
	else
	{
		strValue.Format("扎帐时间:%04d-%02d-%02d %02d:%02d:%02d ",ucRawData[8]+2000,ucRawData[9],ucRawData[10],ucRawData[11],ucRawData[12],ucRawData[13]);  strText += strValue ;
		GetValue(strValue, m_SRC.sSettleTime);
	}

	strValue.Format("%s", m_SRC.sSettleTime); strData+= strValue;

	strValue.Format("起始流水号:%d ",ucRawData[14]*256+ucRawData[15]); strText += strValue ;
	GetValue(strValue, m_SRC.nBeginInvoice);
	strValue.Format("%d", m_SRC.nBeginInvoice); strData+= strValue;

	strValue.Format("结束流水号:%d ",ucRawData[16]*256+ucRawData[17]); strText += strValue ;
	GetValue(strValue, m_SRC.nEndInvoice);
	strValue.Format("%d", m_SRC.nEndInvoice); strData+= strValue;

	strValue.Format("正常消费总笔数:%d ",ucRawData[18]*256+ucRawData[19]); strText += strValue ;
	GetValue(strValue, m_SRC.nDealCount);
	strValue.Format("%d", m_SRC.nDealCount); strData+= strValue;

	strValue.Format("正常消费总金额:%d ",ucRawData[20]+ucRawData[21]*256+ucRawData[22]*65536); strText += strValue ;
	GetValue(strValue, m_SRC.nDealAmount);
	strValue.Format("%d", m_SRC.nDealAmount); strData+= strValue;

	strValue.Format("冲正消费总笔数:%d ",ucRawData[23]*256+ucRawData[24]);  strText += strValue ;
	GetValue(strValue, m_SRC.nCancelCount);
	strValue.Format("%d", m_SRC.nCancelCount); strData+= strValue;

	strValue.Format("冲正消费总金额:%d ",ucRawData[25]+ucRawData[26]*256+ucRawData[27]*65536); strText += strValue ;
	GetValue(strValue, m_SRC.nCancelAmount);
	strValue.Format("%d", m_SRC.nCancelAmount); strData+= strValue;

	strValue.Format("异常消费总笔数%d\n",ucRawData[28]*256+ucRawData[29]); strText += strValue ;
	GetValue(strValue, m_SRC.nExcepCount);
	strValue.Format("%d", m_SRC.nExcepCount); strData+= strValue;

	strValue.Format("异常消费总金额%d\n",ucRawData[30]+ucRawData[31]*256+ucRawData[32]*65536); strText += strValue ;
	GetValue(strValue, m_SRC.nExcepACount);
	strValue.Format("%d", m_SRC.nExcepACount); strData+= strValue;

	strValue.Format("其他交易总笔数:%d ",ucRawData[33]*256+ucRawData[34]); strText += strValue ;
	GetValue(strValue, m_SRC.nOtherCount);
	strValue.Format("%d", m_SRC.nOtherCount); strData+= strValue;

	strValue.Format("扎帐标记:%.2X ",ucRawData[35]); strText += strValue ;
	GetValue(strValue, m_SRC.nOuterkeeper);
	strValue.Format("%d", m_SRC.nOuterkeeper); strData+= strValue;

	int nSettType = 0;

	if(ucRawData[35] == 0x00)
		strValue = "初次运行扎帐 ";
	else if(ucRawData[35] == 0x01)
		strValue = "上位机扎帐 ";
	else if(ucRawData[35] == 0x02)
		strValue = "复核扎帐 ";
	else if(ucRawData[35] == 0x03)
	{
		nSettType = 0;
		strValue = "手工扎帐 ";
	}
	else if(ucRawData[35] == 0x04)
	{
		nSettType = 1;
		strValue = "定时扎帐 ";
	}
	else if(ucRawData[35] == 0x05)
	{
		nSettType = 1;
		strValue = "开机扎帐 ";
	}
	else
		strValue = "未知类型 ";
	strValue.Format("CRC:%.2X%.2X\n", ucRawData[36],ucRawData[37]);  strText += strValue ;

	CString strAdjust=GetAdjustCode(pszAdjustCode, m_SRC.nSettleInvoice, 
		m_SRC.sSettleTime, "Smart_Settlement");

	if( strAdjust == "" && 	!IsValidDateTime(&ucRawData[8])  )
	{
		strAdjust = "0204";
	}

	m_pDoc = pDoc ;

	CString strTemp = "" ;

	strTemp = "INSERT INTO " + m_strTableName ;
	strTemp+= "(SMT_RowID, SMT_AuthNo, SMT_Data, SMT_CRC, ";
	strTemp+= "SMT_DateTime, SMT_DealWith, SMT_DealWithDateTime, SMT_AdjustCode) ";
	strTemp+= " VALUES(SMART_JZSOURCE%s_rowid.nextval, %ld, '%s', %d, SYSDATE, 0, NULL, '%s')";

	if( strAdjust == "0102" )
	{
		strSQL1.Format(strTemp, szDateTime, nAuthNo, 
			strData.GetBuffer(0), 0, strAdjust.GetBuffer(0));
	}
	else
	{
		strSQL1.Format(strTemp, szDateTime, nAuthNo, 
			strData.GetBuffer(0), 1, strAdjust.GetBuffer(0));
	}

	strTemp = "INSERT INTO Smart_Settlement(" ;
	strTemp+= " SMT_RowID, SMT_Authno, SMT_MachineID, SMT_Org_id, " ;
	strTemp+= " SMT_SettleInvoice, SMT_SettleTime, SMT_BeginInvoice, " ;
	strTemp+= " SMT_EndInvoice, SMT_DealCount, SMT_DealAmount, " ;
	strTemp+= " SMT_CancelCount, SMT_CancelAmount, SMT_OtherCount, " ;
	strTemp+= " SMT_OperatorID, SMT_KeepingDate, SMT_BatchNo, " ;
	strTemp+= " SMT_SettleType, SMT_DealCode, SMT_EXCEPTCOUNT, SMT_EXCEPTAMOUNT, SMT_ADJUSTCODE) VALUES( " ;
	strTemp+= " SMART_SETTLEMENT_ROWID.nextval, %d, '%s', '%s', " ;
	strTemp+= " %d, to_date('%s','yyyy-mm-dd hh24:mi:ss'), %d, " ;
	strTemp+= " %d, %d, %d, " ;
	strTemp+= " %d, %d, %d, " ;
	strTemp+= " '%d', SYSDATE, %d, " ;
	strTemp+= " %d, '%s', %d, %d,'%s')" ;

	char  szOrg[12];
	if( !strcmp(pDoc->m_szOrgid, "") )
		strcpy(szOrg, " ");
	else
		strcpy(szOrg, pDoc->m_szOrgid);

	strSQL2.Format(strTemp.GetBuffer(0), nAuthNo, m_SRC.sMachineID, szOrg, 
		m_SRC.nSettleInvoice, m_SRC.sSettleTime, m_SRC.nBeginInvoice, 
		m_SRC.nEndInvoice, m_SRC.nDealCount, m_SRC.nDealAmount, 
		m_SRC.nCancelCount, m_SRC.nCancelAmount, m_SRC.nOtherCount, 
		999, 0, 
		nSettType, strDealCode.GetBuffer(0), m_SRC.nExcepCount, m_SRC.nExcepACount, strAdjust.GetBuffer(0));

	strUpdate.Format("Update Smart_Commrec Set  SMT_LASTDEALDATETIME=to_date('%s','yyyy-mm-dd hh24:mi:ss'), SMT_SETTLEINVOICE=%ld, SMT_SETTLETIME=to_date('%s','yyyy-mm-dd hh24:mi:ss'), SMT_BEGININVOICE=%d, SMT_ENDINVOICE=%d Where Smt_AuthNo=%ld ", 
		m_SRC.sSettleTime, m_SRC.nSettleInvoice, m_SRC.sSettleTime, m_SRC.nBeginInvoice, 
		m_SRC.nEndInvoice, nAuthNo);
/*
	CString strString;

	pDoc->m_nFlow = m_SRC.nSettleInvoice;
	pDoc->m_nCardID = 0;
	pDoc->m_nInMoney = m_SRC.nDealAmount;
	pDoc->m_nOutMoney = m_SRC.nCancelAmount;
	pDoc->m_nDealCount++;

	strString.Format("%d&%d&%d&%s&%d&%d&%d",
		pDoc->m_nAuthID, m_SRC.nSettleInvoice, pDoc->m_nDealCount, 
		m_SRC.sSettleTime, 0, m_SRC.nDealAmount, m_SRC.nCancelAmount);

	BroadcastPro(PACKET_CMD_1002, pDoc, strString.GetBuffer(0), strString.GetLength());
*/
	return true;
}
Ejemplo n.º 12
0
void CFormat::ReplaceKeySymbol(CSymbolReplaceSetDlg* pSymbolReplaceSetDlg, CRichEditView *pRichEditView)
{
	long startPos=0,endPos=0;
	CRichEditCtrl* pRichEditCtrl=&pRichEditView->GetRichEditCtrl();

	//判断是否为全文替换,确定终止位置
	if(pSymbolReplaceSetDlg->m_nSelect==1){
		long lineCount=pRichEditCtrl->GetLineCount();
		CString strLine;
		for(long i=0;i<lineCount;i++){
			pRichEditCtrl->GetLine(i,strLine.GetBuffer());
			if(strLine.Find(_T("**注释**"))!=-1){
				endPos=pRichEditCtrl->LineIndex(i);
			}
		}
	}
	else{
		endPos=pRichEditCtrl->GetTextLength();
	}

	//开始替换
	CString strCh;
	while(startPos<endPos-1){
		pRichEditCtrl->GetTextRange(startPos,startPos+1,strCh);

		//////////单个字符比较//////////////
		//逗号
		if(pSymbolReplaceSetDlg->m_Symbol1){
			if(strCh.Compare(_T(","))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString1.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString1);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T(","));
				}
			}
		}
		//句号
		if(pSymbolReplaceSetDlg->m_Symbol2){
			if(strCh.Compare(_T("."))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString2.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString2);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T("。"));
				}
			}
		}
		//分号
		if(pSymbolReplaceSetDlg->m_Symbol3){
			if(strCh.Compare(_T(";"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString3.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString3);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T(";"));
				}
			}
		}
		//冒号
		if(pSymbolReplaceSetDlg->m_Symbol4){
			if(strCh.Compare(_T(":"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString4.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString4);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T(":"));
				}
			}
		}
		//波浪号
		if(pSymbolReplaceSetDlg->m_Symbol5){
			if(strCh.Compare(_T("~"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString5.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString5);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T("~"));
				}
			}
		}
		//括号
		if(pSymbolReplaceSetDlg->m_Symbol7){
			if(strCh.Compare(_T("("))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				pRichEditCtrl->ReplaceSel(_T("("));
			}
			else if(strCh.Compare(_T(")"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				pRichEditCtrl->ReplaceSel(_T(")"));
			}
		}
		//单破折号
		if(pSymbolReplaceSetDlg->m_Symbol8){
			if(strCh.Compare(_T("-"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString8.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString8);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T("—"));
				}
			}
		}

		/////////////双字符比较///////////////
		pRichEditCtrl->GetTextRange(startPos,startPos+2,strCh);
		//破折号
		if(pSymbolReplaceSetDlg->m_Symbol6){
			if(strCh.Compare(_T("--"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString6.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString6);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T("—"));
				}
			}
		}
		//双破折号替换
		if(pSymbolReplaceSetDlg->m_IsDoubleDash)
		{
			if(strCh.Compare(_T("——"))==0){
				CString replaceStr;
				pSymbolReplaceSetDlg->
					m_doubleDashEdit.GetWindowTextW(replaceStr);
				pRichEditCtrl->SetSel(startPos,startPos+2);
				pRichEditCtrl->ReplaceSel(replaceStr);
			}
		}

		startPos++;
	}
}
Ejemplo n.º 13
0
/**
 * @brief Helper function for selecting folder or file.
 * This function shows standard Windows file selection dialog for selecting
 * file or folder to open or file to save. The last parameter @p is_open selects
 * between open or save modes. Biggest difference is that in save-mode Windows
 * asks if user wants to override existing file.
 * @param [in] parent Handle to parent window. Can be a NULL, but then
 *     CMainFrame is used which can cause modality problems.
 * @param [out] path Selected path is returned in this string
 * @param [in] initialPath Initial path (and file) shown when dialog is opened
 * @param [in] titleid Resource string ID for dialog title.
 * @param [in] filterid 0 or STRING ID for filter string
 *     - 0 means "All files (*.*)". Note the string formatting!
 * @param [in] is_open Selects Open/Save -dialog (mode).
 * @note Be careful when setting @p parent to NULL as there are potential
 * modality problems with this. Dialog can be lost behind other windows!
 * @param [in] defaultExtension Extension to append if user doesn't provide one
 */
BOOL SelectFile(HWND parent, CString& path, LPCTSTR initialPath /*=NULL*/,
		UINT titleid /*=0*/, UINT filterid /*=0*/,
		BOOL is_open /*=TRUE*/, LPCTSTR defaultExtension /*=NULL*/)
{
	path.Empty(); // Clear output param

	// This will tell common file dialog what to show
	// and also this will hold its return value
	CString sSelectedFile;

	// check if specified path is a file
	if (initialPath && initialPath[0])
	{
		// If initial path info includes a file
		// we put the bare filename into sSelectedFile
		// so the common file dialog will start up with that file selected
		if (paths_DoesPathExist(initialPath) == IS_EXISTING_FILE)
		{
			String temp;
			SplitFilename(initialPath, 0, &temp, 0);
			sSelectedFile = temp.c_str();
		}
	}

	if (parent == NULL)
		parent = AfxGetMainWnd()->GetSafeHwnd();
	
	if (!filterid)
		filterid = IDS_ALLFILES;
	String title = theApp.LoadString(titleid);
	String filters = theApp.LoadString(filterid);

	// Convert extension mask from MFC style separators ('|')
	//  to Win32 style separators ('\0')
	LPTSTR filtersStr = &*filters.begin();
	ConvertFilter(filtersStr);

	OPENFILENAME_NT4 ofn;
	memset(&ofn, 0, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = parent;
	ofn.lpstrFilter = filtersStr;
	ofn.lpstrCustomFilter = NULL;
	ofn.nFilterIndex = 1;
	ofn.lpstrFile = sSelectedFile.GetBuffer(MAX_PATH);
	ofn.nMaxFile = MAX_PATH;
	ofn.lpstrInitialDir = initialPath;
	ofn.lpstrTitle = title.c_str();
	ofn.lpstrFileTitle = NULL;
	if (defaultExtension)
		ofn.lpstrDefExt = defaultExtension;
	ofn.Flags = OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;

	BOOL bRetVal = FALSE;
	if (is_open)
		bRetVal = GetOpenFileName((OPENFILENAME *)&ofn);
	else
		bRetVal = GetSaveFileName((OPENFILENAME *)&ofn);
	// common file dialog populated sSelectedFile variable's buffer
	sSelectedFile.ReleaseBuffer();
	SetCurrentDirectory(env_GetWindowsDirectory().c_str()); // Free handle held by GetOpenFileName

	if (bRetVal)
		path = sSelectedFile;
	
	return bRetVal;
}
Ejemplo n.º 14
0
/** 
 * @brief Shows file/folder selection dialog.
 *
 * We need this custom function so we can select files and folders with the
 * same dialog.
 * - If existing filename is selected return it
 * - If filename in (CFileDialog) editbox and current folder doesn't form
 * a valid path to file, return current folder.
 * @param [in] parent Handle to parent window. Can be a NULL, but then
 *     CMainFrame is used which can cause modality problems.
 * @param [out] path Selected folder/filename
 * @param [in] initialPath Initial file or folder shown/selected.
 * @return TRUE if user choosed a file/folder, FALSE if user canceled dialog.
 */
BOOL SelectFileOrFolder(HWND parent, CString& path, LPCTSTR initialPath /*=NULL*/)
{
	String title = theApp.LoadString(IDS_OPEN_TITLE);

	// This will tell common file dialog what to show
	// and also this will hold its return value
	CString sSelectedFile;

	// check if specified path is a file
	if (initialPath && initialPath[0])
	{
		// If initial path info includes a file
		// we put the bare filename into sSelectedFile
		// so the common file dialog will start up with that file selected
		if (paths_DoesPathExist(initialPath) == IS_EXISTING_FILE)
		{
			String temp;
			SplitFilename(initialPath, 0, &temp, 0);
			sSelectedFile = temp.c_str();
		}
	}

	if (parent == NULL)
		parent = AfxGetMainWnd()->GetSafeHwnd();

	int filterid = IDS_ALLFILES;

	if (!filterid)
		filterid = IDS_ALLFILES;

	String filters = theApp.LoadString(filterid);

	// Convert extension mask from MFC style separators ('|')
	//  to Win32 style separators ('\0')
	LPTSTR filtersStr = &*filters.begin();
	ConvertFilter(filtersStr);

	String dirSelTag = theApp.LoadString(IDS_DIRSEL_TAG);

	// Set initial filename to folder selection tag
	dirSelTag += _T("."); // Treat it as filename
	sSelectedFile = dirSelTag.c_str(); // What is assignment above good for?

	OPENFILENAME_NT4 ofn;
	memset(&ofn, 0, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = parent;
	ofn.lpstrFilter = filtersStr;
	ofn.lpstrCustomFilter = NULL;
	ofn.nFilterIndex = 1;
	ofn.lpstrFile = sSelectedFile.GetBuffer(MAX_PATH);
	ofn.nMaxFile = MAX_PATH;
	ofn.lpstrInitialDir = initialPath;
	ofn.lpstrTitle = title.c_str();
	ofn.lpstrFileTitle = NULL;
	ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_NOTESTFILECREATE;

	BOOL bRetVal = GetOpenFileName((OPENFILENAME *)&ofn);
	// common file dialog populated sSelectedFile variable's buffer
	sSelectedFile.ReleaseBuffer();
	SetCurrentDirectory(env_GetWindowsDirectory().c_str()); // Free handle held by GetOpenFileName

	if (bRetVal)
	{
		path = sSelectedFile;
		struct _stati64 statBuffer;
		int nRetVal = _tstati64(path, &statBuffer);
		if (nRetVal == -1)
		{
			// We have a valid folder name, but propably garbage as a filename.
			// Return folder name
			String folder = GetPathOnly(sSelectedFile);
			path.Format(_T("%s\\"), folder.c_str());
		}
	}
	return bRetVal;
}
Ejemplo n.º 15
0
void CGitStatusCache::Create()
{
	ATLASSERT(m_pInstance == NULL);
	m_pInstance = new CGitStatusCache;

	m_pInstance->watcher.SetFolderCrawler(&m_pInstance->m_folderCrawler);
#define LOADVALUEFROMFILE(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto exit;
#define LOADVALUEFROMFILE2(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto error;
	unsigned int value = (unsigned int)-1;
	FILE * pFile = NULL;
	// find the location of the cache
	TCHAR path[MAX_PATH];		//MAX_PATH ok here.
	TCHAR path2[MAX_PATH];
	SecureZeroMemory(path, sizeof(path));
	SecureZeroMemory(path2, sizeof(path2));
	if (SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path)==S_OK)
	{
		_tcscat_s(path, MAX_PATH, _T("\\TGitCache"));
		if (!PathIsDirectory(path))
		{
			if (CreateDirectory(path, NULL)==0)
				goto error;
		}
		_tcscat_s(path, MAX_PATH, _T("\\cache"));
		// in case the cache file is corrupt, we could crash while
		// reading it! To prevent crashing every time once that happens,
		// we make a copy of the cache file and use that copy to read from.
		// if that copy is corrupt, the original file won't exist anymore
		// and the second time we start up and try to read the file,
		// it's not there anymore and we start from scratch without a crash.
		_tcscpy_s(path2, MAX_PATH, path);
		_tcscat_s(path2, MAX_PATH, _T("2"));
		DeleteFile(path2);
		CopyFile(path, path2, FALSE);
		DeleteFile(path);
		pFile = _tfsopen(path2, _T("rb"), _SH_DENYNO);
		if (pFile)
		{
			try
			{
				LOADVALUEFROMFILE(value);
				if (value != 2)
				{
					goto error;
				}
				int mapsize = 0;
				LOADVALUEFROMFILE(mapsize);
				for (int i=0; i<mapsize; ++i)
				{
					LOADVALUEFROMFILE2(value);
					if (value > MAX_PATH)
						goto error;
					if (value)
					{
						CString sKey;
						if (fread(sKey.GetBuffer(value+1), sizeof(TCHAR), value, pFile)!=value)
						{
							sKey.ReleaseBuffer(0);
							goto error;
						}
						sKey.ReleaseBuffer(value);
						CCachedDirectory * cacheddir = new CCachedDirectory();
						if (cacheddir == NULL)
							goto error;
						if (!cacheddir->LoadFromDisk(pFile))
							goto error;
						CTGitPath KeyPath = CTGitPath(sKey);
						if (m_pInstance->IsPathAllowed(KeyPath))
						{
							m_pInstance->m_directoryCache[KeyPath] = cacheddir;
							// only add the path to the watch list if it is versioned
							if ((cacheddir->GetCurrentFullStatus() != git_wc_status_unversioned)&&(cacheddir->GetCurrentFullStatus() != git_wc_status_none))
								m_pInstance->watcher.AddPath(KeyPath, false);
							// do *not* add the paths for crawling!
							// because crawled paths will trigger a shell
							// notification, which makes the desktop flash constantly
							// until the whole first time crawling is over
							// m_pInstance->AddFolderForCrawling(KeyPath);
						}
					}
				}
			}
			catch (CAtlException)
			{
				goto error;
			}
		}
	}
exit:
	if (pFile)
		fclose(pFile);
	DeleteFile(path2);
	m_pInstance->watcher.ClearInfoMap();
	ATLTRACE("cache loaded from disk successfully!\n");
	return;
error:
	if (pFile)
		fclose(pFile);
	DeleteFile(path2);
	m_pInstance->watcher.ClearInfoMap();
	Destroy();
	m_pInstance = new CGitStatusCache;
	ATLTRACE("cache not loaded from disk\n");
}
Ejemplo n.º 16
0
void FileNavCommand()
{
    LPCTSTR filterALL[] = {
        "*.*", NULL
    };
    LPCTSTR filterCPP[] = {
        "*.zip", "*.c", "*.cpp", "*.h", NULL
    };
    LPCTSTR filterDOC[] = {
        "*.doc", "*.txt", NULL
    };
    LPCTSTR filterDWG[] = {
        "*.dwg", "*.dxb", "*.dxf", NULL
    };
    LPCTSTR filterIMG[] = {
        "*.gif", "*.jpg", "*.tif", "*.tiff", NULL
    };
    LPCTSTR filterDescription[] = {
        "All files", "C++ files", "Documents", "Drawings", "Images", NULL
    };
    LPCTSTR *filterSpec[] = {
        filterALL, filterCPP, filterDOC, filterDWG, filterIMG, NULL
    };

    CNavFilter *f;
    int  i = 0, j;

    gFilterArray.RemoveAllData();

    while (filterSpec[i] != NULL) {
        // Append a new filter.
        f = gFilterArray.AddData();

        if (f != NULL) {
            // Set the filter's description.
            f->SetDescription(filterDescription[i]);

            // Assign the filter strings.
            j = 0;
            while (filterSpec[i][j] != NULL) {
                f->Add(filterSpec[i][j]);
                j++;
            }
        }

        // Prepare to add the next filter.
        i++;
    }
    while (true)
    {
        HWND acadHandle = adsw_acadMainWnd();
        ::EnableWindow (acadHandle, true);
        ::SetFocus (acadHandle);
        CWnd *pWnd = CWnd::FromHandle(acadHandle);

        CFileNavDlg dlg(gDataArray, gFilterArray, 0, pWnd);
        dlg.SetMultiSelectAllowed(TRUE);
        dlg.SetDialogCaption("Browse down to a file");


        if (dlg.DoModal() == IDOK)
        {
            for(int i = 0; i < gDataArray.GetCount(); i++)
            {
                LPITEMIDLIST id = gDataArray[i]->GetID();
                //able to get the text string entered/selected by user in File Name Combo
                //along with its full parth
                CString sText = gDataArray[i]->GetText();
                if (sText.GetLength() != 0)
                {
                    acutPrintf ("The file name is:\n%s\n",sText.GetBuffer(sText.GetLength()));
                }
            }

        }
        break;
    }
}
Ejemplo n.º 17
0
bool CSimSysManager::bGetConfigData(xmlNodePtr pNodePtr)
{

    const char* omcVarChar ;
    UINT unCount = m_ouSimSysNodeInfo.unGetNumberOfSimSys();
    PSSIMSYSINFO pSimSysInfo = m_ouSimSysNodeInfo.psReturnSimsysInfoListPtr();
    for (UINT i = 0; (i < unCount) && (pSimSysInfo != NULL); i++)
    {
        CString omTmp = pSimSysInfo->m_omStrSimSysName;

        string omPath, omStrConfigFolder;
        char configPath[MAX_PATH];
        AfxGetMainWnd()->SendMessage(MSG_GET_CONFIGPATH, (WPARAM)configPath, 0);
        CUtilFunctions::nGetBaseFolder(configPath, omStrConfigFolder );
        CUtilFunctions::MakeRelativePath(omStrConfigFolder.c_str(), (char*)omTmp.GetBuffer(MAX_PATH), omPath);


        omcVarChar = omPath.c_str();
        xmlNodePtr pColName = xmlNewChild(pNodePtr, NULL, BAD_CAST DEF_SYS_PATH,BAD_CAST omcVarChar);
        xmlAddChild(pNodePtr, pColName);

        pSimSysInfo = pSimSysInfo->m_psSimsysNext;
    }


    //window placement
    xmlNodePtr pNodeWindowsPos = xmlNewNode(NULL, BAD_CAST DEF_WND_POS);
    xmlAddChild(pNodePtr, pNodeWindowsPos);


    WINDOWPLACEMENT sWndPlacement;
    if(CGlobalObj::ouGetObj(m_eBus).m_pomSimSysWnd != NULL)
    {
        CGlobalObj::ouGetObj(m_eBus).m_pomSimSysWnd->GetWindowPlacement(&sWndPlacement);
        xmlUtils::CreateXMLNodeFrmWindowsPlacement(pNodeWindowsPos,sWndPlacement);
    }
    else if(CGlobalObj::ouGetObj(m_eBus).m_pomSimSysWnd == NULL)
    {
        xmlUtils::CreateXMLNodeFrmWindowsPlacement(pNodeWindowsPos,CGlobalObj::ouGetObj(m_eBus).m_wWindowPlacement);
    }

    ////visibility
    //CString csVisibility;
    //csVisibility.Format("%d",  sWndPlacement.flags);
    //omcVarChar = csVisibility;
    //xmlNodePtr pVisibility = xmlNewChild(pNodeWindowsPos, NULL, BAD_CAST DEF_VISIBILITY,BAD_CAST omcVarChar);
    //xmlAddChild(pNodeWindowsPos, pVisibility);

    ////WindowPlacement
    //CString csWindowPlacement;
    //csWindowPlacement.Format("%d",  sWndPlacement.flags);
    //omcVarChar = csWindowPlacement;
    //xmlNodePtr pWindowPlacement = xmlNewChild(pNodeWindowsPos, NULL, BAD_CAST DEF_MWND_PLACEMENT,BAD_CAST omcVarChar);
    //xmlAddChild(pNodeWindowsPos, pWindowPlacement);

    ////Top
    //CString csTop;
    //csTop.Format("%d",  sWndPlacement.rcNormalPosition.top);
    //omcVarChar = csTop;
    //xmlNodePtr pTop= xmlNewChild(pNodeWindowsPos, NULL, BAD_CAST DEF_MWND_TOP,BAD_CAST omcVarChar);
    //xmlAddChild(pNodeWindowsPos, pTop);

    ////Left
    //CString csLeft;
    //csLeft.Format("%d",  sWndPlacement.rcNormalPosition.left);
    //omcVarChar = csLeft;
    //xmlNodePtr pLeft = xmlNewChild(pNodeWindowsPos, NULL, BAD_CAST DEF_MWND_LEFT,BAD_CAST omcVarChar);
    //xmlAddChild(pNodeWindowsPos, pLeft);

    ////Bottom
    //CString csBottom;
    //csBottom.Format("%d",  sWndPlacement.rcNormalPosition.bottom);
    //omcVarChar = csBottom;
    //xmlNodePtr pBottom= xmlNewChild(pNodeWindowsPos, NULL, BAD_CAST DEF_BOTTOM,BAD_CAST omcVarChar);
    //xmlAddChild(pNodeWindowsPos, pBottom);

    ////Right
    //CString csRight;
    //csRight.Format("%d",  sWndPlacement.rcNormalPosition.right);
    //omcVarChar = csRight;
    //xmlNodePtr pRight = xmlNewChild(pNodeWindowsPos, NULL, BAD_CAST DEF_RIGHT,BAD_CAST omcVarChar);
    //xmlAddChild(pNodeWindowsPos, pRight);

    return true;
}
Ejemplo n.º 18
0
void CVWSocket :: ModoError()
{
	SOCKADDR_IN		dir_Dest;
	SOCKET			sock_Send;
	char			szMensaje[256], szIPDest[20];
	int				puertodest, tim, w;
	clock_t			inicio;
	CString			csTemp;


//-- Obtener la direcion IP de destino
	m_edIPDest.GetWindowText(csTemp);
	if (csTemp.IsEmpty())
	{
		AfxMessageBox("Por favor introduzca una dirección IP de destino");
		return;
	}
	strcpy_s(szIPDest, csTemp.GetBuffer(0));

//-- Obtener el puerto a enviar
	m_edPuertDest.GetWindowText(csTemp);
	puertodest = atoi(csTemp.GetBuffer(0));
	
	if (puertodest < 1)
	{
		AfxMessageBox("Por favor introduzca un puerto UDP valido");
		return;
	}

//-- Obtener tiempo de la prueba
	m_edTiempo.GetWindowText(csTemp);
	tim=atoi(csTemp);
	csTemp.ReleaseBuffer(-1);
	if (tim < 1)
	{
		AfxMessageBox("Por favor Introduzca un tiempo de transmisión válido");
		return;
	}

//-- Crear socket UDP
	if ((sock_Send = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
		AfxMessageBox("Error:  fallo en el socket.");

//-- Llenar la estructura de datos para el enlace
	memset((char *) &dir_Dest, 0, sizeof(dir_Dest));
	dir_Dest.sin_family      = AF_INET;
	dir_Dest.sin_addr.s_addr = inet_addr(szIPDest);
	dir_Dest.sin_port        = htons(puertodest);             

//-- Envio	
	inicio = clock();
	srand((unsigned)time(0));
	while(clock()/(double)CLOCKS_PER_SEC < (inicio/(double)CLOCKS_PER_SEC)+(double)tim)
    {		
		//-- Preparar Mensaje
		//sprintf_s(szMensaje, "%i\n", i+1);
		if (sendto(sock_Send, "b", 256, 0, (sockaddr*)&dir_Dest, sizeof(dir_Dest)) == SOCKET_ERROR)//Mensaje Correcto
			AfxMessageBox("Error:  fallo de envio.");
		srand((unsigned)time(0));
		w = rand();
		if( w % 2 == 0  )
		{
			if (sendto(sock_Send, "m", 256, 0, (sockaddr*)&dir_Dest, sizeof(dir_Dest)) == SOCKET_ERROR)//mensaje Incorrecto
				AfxMessageBox("Error:  fallo de envio.");
		}
	}
	if (sendto(sock_Send, "\0", 256, 0, (sockaddr*)&dir_Dest, sizeof(dir_Dest)) == SOCKET_ERROR)
		AfxMessageBox("Error:  fallo de envio.");

	closesocket(sock_Send);
	
}
Ejemplo n.º 19
0
std::string CStringConverter::UnicodeToUTF8( CString strSource )
{
	USES_MYCP_CONVERSION;
	USES_CP_UTF8;
	return W2CP(strSource.GetBuffer(0), CP_UTF8);
}
Ejemplo n.º 20
0
void CVWSocket::RecibirUDP() 
{
	SOCKADDR_IN		dir_Srv, dir_Cli;
	SOCKET			sock_Receive;
	char			szMensaje[256], cad1[100], cad2[100], buf[256];
	int				puertoescucha;
	int				i, clilen, bitsmalos, paquetes;
	int				val = 1;
	CString			csTemp;
	ofstream		salida;
	
	
	
//-- Obtiene el puerto en el que se va a escuchar
	m_edPuertEsc.GetWindowText(csTemp);
	puertoescucha = atoi(csTemp.GetBuffer(0));
	csTemp.ReleaseBuffer(-1);
	
	if (puertoescucha < 1)
	{
		AfxMessageBox("Por favor Introduzca un puerto UDP válido");
		return;
	}

//-- Abre el socket UDP 
	if ((sock_Receive = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
		AfxMessageBox("Error, no es posible abrir el socket");

//-- Fill in structure fields for binding to local host
	memset((char *) &dir_Srv, 0, sizeof(dir_Srv));
	dir_Srv.sin_family      = AF_INET;
	dir_Srv.sin_addr.s_addr = htonl(INADDR_ANY);
	dir_Srv.sin_port        = htons(puertoescucha);

//-- Enlaza el puerto UDP
	if (bind(sock_Receive, (sockaddr*)&dir_Srv, sizeof(dir_Srv)) < 0)
		AfxMessageBox("Error:  fallo en el enlace.");

	
//-- Muestra un mensaje mientras espera la recepcion de datos
	CDGModelessMessage dg("Esperando un mensaje UDP...", "BER");
	dg.Show();
	csTemp="";

	paquetes=0;
	bitsmalos=0;
	while(1){
		//-- Prepara la direccion del cliente para la recepcion de los datos
		memset(&dir_Cli, 0, sizeof(dir_Cli));
		clilen = sizeof(dir_Cli);
		
		//-- Recibe el mensaje
		if (recvfrom(sock_Receive, szMensaje, 256, 0, (sockaddr*)&dir_Cli, &clilen) == SOCKET_ERROR)
		{
			AfxMessageBox("Error:  fallo de recepcion.");
			return;
		}
		else if(strcmp(szMensaje,"\0")==0) break;
		else
		{
			//-- Recibimos el mensaje
			
			paquetes++;
			salida.open("log.txt", ios::out);
			for(i=0; (unsigned)i < strlen(szMensaje); i++)
				salida<<bitset<8>(szMensaje[i]);
			salida.close();
			ifstream entrada("log.txt");
			entrada>>cad1;
			bitsmalos += compararbits(cad1,"01100010");
			

		}
	}
	closesocket(sock_Receive);
	dg.Kill();

	csTemp += "Transmisión Completada\n";
	csTemp += "De:  ";
	csTemp += IPString(uGetIPFromSockAddr_In(&dir_Cli), buf, 255);
	csTemp += "\n\n";
	csTemp += "Bits enviados: ";
	sprintf_s(szMensaje, "%d\n", paquetes*8);
	csTemp += szMensaje;
	csTemp += "Bits erroneos: ";
	sprintf_s(szMensaje, "%d\n", bitsmalos);
	csTemp += szMensaje;
	csTemp += "Proporción de errores: ";
	sprintf_s(szMensaje, "%.4f", (float)bitsmalos/(float)(paquetes*8));
	csTemp += szMensaje;
	
	AfxMessageBox(csTemp);
	
}
Ejemplo n.º 21
0
LONG WINAPI CMiniDump::UnhandledExceptionFilter(_EXCEPTION_POINTERS* lpTopLevelExceptionFilter)
{
    LONG    retval = EXCEPTION_CONTINUE_SEARCH;
    HMODULE hDll = NULL;
    TCHAR   szResult[800];
    szResult[0] = _T('\0');
    CString strDumpPath;

    if (!m_bMiniDumpEnabled) {
        return retval;
    }

#ifndef DISABLE_MINIDUMP
    hDll = ::LoadLibrary(_T("dbghelp.dll"));

    if (hDll != NULL) {
        MINIDUMPWRITEDUMP pMiniDumpWriteDump = (MINIDUMPWRITEDUMP)::GetProcAddress(hDll, "MiniDumpWriteDump");
        if (pMiniDumpWriteDump != NULL) {
            if (!AfxGetMyApp()->IsIniValid()) {
                HRESULT hr = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, strDumpPath.GetBuffer(MAX_PATH));
                if (FAILED(hr)) {
                    FreeLibrary(hDll);
                    return retval;
                }

                strDumpPath.ReleaseBuffer();
                strDumpPath.Append(_T("\\Media Player Classic\\"));
                strDumpPath.Append(AfxGetApp()->m_pszExeName);
                strDumpPath.Append(_T(".exe"));
            } else {
                strDumpPath = GetProgramPath(true);
            }
            strDumpPath.AppendFormat(_T(".%d.%d.%d.%d.dmp"), MPC_VERSION_NUM);

            // create the file
            HANDLE hFile = ::CreateFile(strDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
                                        FILE_ATTRIBUTE_NORMAL, NULL);

            if (hFile != INVALID_HANDLE_VALUE) {
                _MINIDUMP_EXCEPTION_INFORMATION ExInfo;

                ExInfo.ThreadId = ::GetCurrentThreadId();
                ExInfo.ExceptionPointers = lpTopLevelExceptionFilter;
                ExInfo.ClientPointers = NULL;

                // write the dump
                BOOL bOK = pMiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, NULL, NULL);
                if (bOK) {
                    _stprintf_s(szResult, _countof(szResult), ResStr(IDS_MPC_CRASH), strDumpPath);
                    retval = EXCEPTION_EXECUTE_HANDLER;
                } else {
                    _stprintf_s(szResult, _countof(szResult), ResStr(IDS_MPC_MINIDUMP_FAIL), strDumpPath, GetLastError());
                }

                ::CloseHandle(hFile);
            } else {
                _stprintf_s(szResult, _countof(szResult), ResStr(IDS_MPC_MINIDUMP_FAIL), strDumpPath, GetLastError());
            }
        }
        FreeLibrary(hDll);
    }

    if (szResult[0]) {
        switch (MessageBox(NULL, szResult, _T("MPC-HC - Mini Dump"), retval ? MB_YESNO : MB_OK)) {
            case IDYES:
                ShellExecute(NULL, _T("open"), BUGS_URL, NULL, NULL, SW_SHOWDEFAULT);
                ExploreToFile(strDumpPath);
                break;
            case IDNO:
                retval = EXCEPTION_CONTINUE_SEARCH; // rethrow the exception to make easier attaching a debugger
                break;
        }
    }
#else
    if (MessageBox(NULL, ResStr(IDS_MPC_BUG_REPORT), ResStr(IDS_MPC_BUG_REPORT_TITLE), MB_YESNO) == IDYES) {
        ShellExecute(NULL, _T("open"), DOWNLOAD_URL, NULL, NULL, SW_SHOWDEFAULT);
    }
#endif // DISABLE_MINIDUMP

    return retval;
}
Ejemplo n.º 22
0
/////////////////////////////////////////////////////////////////////////////
// IShellInit Functions
/////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CShellExt::XShellInit::Initialize(LPCITEMIDLIST pidlFolder, IDataObject *pdobj, HKEY hkeyProgID)
{
    METHOD_PROLOGUE(CShellExt, ShellInit);

    HRESULT hres = E_FAIL;
    FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
    STGMEDIUM medium;

    // We must have a data object
    if (pdobj == NULL)
	    return E_FAIL;

    //  Use the given IDataObject to get a list of filenames (CF_HDROP)
    hres = pdobj->GetData(&fmte, &medium);
    if (FAILED(hres)) {
	return E_FAIL;
    }

    int nNumFiles = DragQueryFile((HDROP)medium.hGlobal, 0xFFFFFFFF, NULL, 0);
    if (nNumFiles == 0)
	hres = E_FAIL;
    else {
	pThis->m_bDirSelected = FALSE;

	for (int ii = 0; ii < nNumFiles; ii++) {
	    CString strFileName;

	    // Get the size of the file name string
	    int nNameLen = DragQueryFile((HDROP)medium.hGlobal, ii, 0, 0);

	    // Make room for it in our string object
	    LPTSTR pszFileNameBuf = strFileName.GetBuffer(nNameLen + 1);	// +1 for the terminating NULL
	    ASSERT(pszFileNameBuf);

	    // Get the file name
	    DragQueryFile((HDROP)medium.hGlobal, ii, pszFileNameBuf, nNameLen + 1);

	    strFileName.ReleaseBuffer();

	    if (!IsPathInAfs(strFileName)) {
		pThis->m_astrFileNames.RemoveAll();
		break;
	    } else {
		pThis->m_bIsSymlink=IsSymlink(strFileName);
	    }

	    if (IsADir(strFileName))
		pThis->m_bDirSelected = TRUE;

	    pThis->m_astrFileNames.Add(strFileName);
	}

	if (pThis->m_astrFileNames.GetSize() > 0)
	    hres = NOERROR;
	else
	    hres = E_FAIL;
    }
 
    //	Release the data
    ReleaseStgMedium(&medium);

    return hres;
}
Ejemplo n.º 23
0
/*
 * This function is called when the remote connection, whant to send a file.  
 *
 */  
void MyIOCP::PackageFileTransfer(CIOCPBuffer *pOverlapBuff,int nSize,ClientContext *pContext)
{
#ifdef TRANSFERFILEFUNCTIONALITY
	
	CString sFileName="";
	UINT	iMaxFileSize=0;
	BYTE dummy=0;
	if(pOverlapBuff->GetPackageInfo(dummy,iMaxFileSize,sFileName))
	{
		// Get The Current Path name and application name.
		CString sFilePath="";		
		char drive[_MAX_DRIVE];
		char dir[_MAX_DIR];
		char fname[_MAX_FNAME];
		char ext[_MAX_EXT];
		CString strTemp;
		GetModuleFileName(NULL,strTemp.GetBuffer(MAX_PATH),MAX_PATH);
		strTemp.ReleaseBuffer();
		_splitpath( strTemp, drive, dir, fname, ext );
		sFilePath=drive; //Drive
		sFilePath+=dir; //dir
		sFilePath+=sFileName; //name.. 
		TRACE("Incoming File >%s.\r\n",sFilePath);
		// Perpare for Receive
	
		if(PrepareReceiveFile(pContext->m_Socket,sFilePath,iMaxFileSize))
		{
			// Send start file transfer.. 
			CIOCPBuffer *pOverlapBuff=AllocateBuffer(IOWrite);
			if(pOverlapBuff)
			{
				if(pOverlapBuff->CreatePackage(Job_StartFileTransfer))
			     ASend(pContext,pOverlapBuff);

			}
		}else
		{
		   // Abort Transfer. 
			CIOCPBuffer *pOverlapBuff=AllocateBuffer(IOWrite);
			if(pOverlapBuff)
			{
				if(pOverlapBuff->CreatePackage(Job_AbortFileTransfer))
			     ASend(pContext,pOverlapBuff);

			}
		}
		
		// to be sure that pcontext Suddenly does not dissapear.. 
		m_ContextMapLock.Lock();
		pContext->m_ContextLock.Lock();
		pContext->m_sReceived=sFilePath;
		// Update that we have data
		pContext->m_iNumberOfReceivedMsg++;
		pContext->m_ContextLock.Unlock();
		m_ContextMapLock.Unlock();

		// Update Statistics. 
		m_StatusLock.Lock();
		m_iNumberOfMsg++;
		m_StatusLock.Unlock();
	}
#endif
}
bool CWebCDCovers::DownloadImage(CString strLetter, CString strName, CString strFilename, RESOURCEHOST* pHost, HWND hwndProgress, HWND hwndStatus, CString& strLocalFilename)
{
	// get the html page for the image source
	*m_pbCancelDownload = false;

	WCC_GETIMAGEREQUEST* pfn_wccRequest = (WCC_GETIMAGEREQUEST*) GetProcAddress (pHost->hInst, "GetImageRequest");
	WCC_GETIMAGEURL* pfn_wccImgURL = (WCC_GETIMAGEURL*) GetProcAddress (pHost->hInst, "GetImageURL");

	char szUrl[300], szHeaders[300], szData[300];
	int nMethod;
	pfn_wccRequest (strFilename.GetBuffer (0), strLetter.GetBuffer (0), "", szUrl, &nMethod, szHeaders, szData);

	CString strHTML = (*szUrl == 0) ? strFilename.GetBuffer (0) :
		CHttpRequest::DownloadBuffer (szUrl, nMethod, szHeaders, szData,
			m_pbCancelDownload, m_dwDownloadId, m_nError);

	// MCH 29/08/04
	// Send version info to the DLL
	strcpy (szData, ((CCdCoverCreator2App*) AfxGetApp ())->GetVersion ().GetBuffer (-1));

	// get the URL of the image
	CString strURL;
	if (!pfn_wccImgURL (strHTML.GetBuffer (0), strURL.GetBuffer (500), &nMethod, szHeaders, szData))
		return false;
	strURL.ReleaseBuffer ();

	// generate a local temporary file name
	strLocalFilename = ((CCdCoverCreator2App*) AfxGetApp ())->GetImageCacheDir () + strURL.Mid (strURL.ReverseFind ('/') + 1);
	if (strLocalFilename.Find (".php?") >= 0)
	{
		// MCH 15/09/04
		// www.darktown.to sends again JPGs, but via a PHP script. Filename provided as HTTP header which is not available here
		strLocalFilename = ((CCdCoverCreator2App*) AfxGetApp ())->GetImageCacheDir ();
		strLocalFilename.AppendFormat ("dld%d.jpg", GetTickCount ());
	}

	// get the jpeg image
	*m_pbCancelDownload = false;
	CHttpRequest::DownloadFile (strURL, nMethod, szHeaders, szData, strLocalFilename,
		m_pbCancelDownload, m_dwDownloadId, m_nError, 0, hwndProgress, hwndStatus);

	if (m_nError)
		return false;

	// MCH 29/08/04
	// if the download is a zip file, extract the image
	if (strLocalFilename.Right (4).MakeLower () == ".zip")
	{
		CString strPath = strLocalFilename.Left (strLocalFilename.ReverseFind ('\\'));
		CString strZipFile = strLocalFilename;

		// set up and open a zip archive, get the image files inside the zip file
		CZipArchive zip;
		zip.Open (strZipFile);
		CZipWordArray ar;
		zip.FindMatches ("*.jp*g", ar);

		strLocalFilename.Empty ();

		// extract the image files
		for (int i = 0; i < ar.GetSize (); i++)
		{
			// set the local file name
			CZipFileHeader info;
			zip.GetFileInfo (info, i);
			if (!strLocalFilename.IsEmpty ())
				strLocalFilename += ";";
			strLocalFilename += strPath + "\\" + info.GetFileName ();
			
			// extract the file
			zip.ExtractFile (ar.GetAt (i), strPath, false);
		}

		zip.Close ();

		// delete the zip file
		::DeleteFile (strZipFile);
	}

	return true;
}
Ejemplo n.º 25
0
UINT ShowMessageBox (UINT Id, UINT Button, UINT Help, ...) {

    CString temp;
    TCHAR *pszstring,
    *pszpaste,
    *pszcut,
    *pszdone,
    *pszconvert;
    TCHAR chread;
    va_list params;
    int x;

    pszconvert = new TCHAR[255];
    va_start(params, Help);
    LoadString (temp, Id);
    pszstring = temp.GetBuffer(512);
    _tcscpy(pszstring,pszstring);
    temp.ReleaseBuffer();
    // Look and see - is there a need to insert chars (95% of the time, there won't)
    if (!_tcsstr(pszstring, _T("%"))) {
	delete pszconvert;
	return AfxMessageBox(pszstring, Button, Help);
    }

    x = _tcscspn(pszstring, _T("%"));
    pszdone = new TCHAR[512];
    pszcut = new TCHAR[512];
    pszpaste = new TCHAR[512];
    _tcscpy(pszcut, &pszstring[x+2]);
    _tcsncpy(pszpaste, pszstring, x);
    pszpaste[x] = _T('\0');
    chread = pszstring[x+1];

    for ( ; ; ) {

	switch (chread) {
	case	_T('i') :
	case	_T('d') :
	{
	    int anint = va_arg(params, int);
	    _itot( anint, pszconvert, 10);
	    break;
	}
	case	_T('u') :
	{
	    UINT anuint = va_arg(params, UINT);
	    _itot( anuint, pszconvert, 10);
	    break;
	}

	case	_T('x') :
	case	_T('X') :
	{
	    int ahex = va_arg(params, int);
	    _itot( ahex, pszconvert, 16);
	    break;
	}
	case	_T('g') :
	case	_T('f') :
	case	_T('e') :
	{
	    double adbl = va_arg(params, double);
            _stprintf(pszconvert, _T("%g"), adbl);
	    break;
	}
	case	_T('s') :
	{
	    TCHAR *pStr = va_arg(params, TCHAR*);
	    ASSERT(_tcslen(pStr) <= 255);
	    _tcscpy(pszconvert, pStr);
	    break;
	}
	case	_T('l') :
	{
	    chread = pszdone[x+2];
	    switch(chread) {
	    case	_T('x')	:
	    {
		long int alhex = va_arg(params, long int);
		_ltot(alhex, pszconvert, 16);
		_tcscpy(pszcut, &pszcut[1]);
		break;
	    }
	    case 	_T('d')	:
		default 	:
		{
		    long int along = va_arg(params, long int);
		    _ltot( along, pszconvert, 10);
		    // For the L, there will be one character after it,
		    //   so move ahead another letter
		    _tcscpy(pszcut, &pszcut[1]);
		    break;
		}
	    }
	    break;
	}

	case	_T('c') :
	{
	    int letter = va_arg(params, int);
	    pszconvert[0] = (TCHAR)letter;
	    pszconvert[1] = '\0';
	    break;
	}
	case 	_T('a')	:
	{
	    CString zeta;
	    TCHAR* lsc;
	    UINT ls = va_arg(params, UINT);
	    LoadString (zeta, ls);
	    lsc = zeta.GetBuffer(255);
	    _tcscpy(pszconvert, lsc);
	    zeta.ReleaseBuffer();
	    break;
	}
	case	_T('o')	:
	{
	    CString get = va_arg(params, CString);
	    TCHAR* ex = get.GetBuffer(255);
	    _tcscpy(pszconvert,ex);
	    get.ReleaseBuffer();
	    break;
	}
	    default 	:
	    {
		_tcscpy(pszconvert, _T(" Could not load message. Invalid %type in string table entry. "));
		delete pszdone;
		pszdone = new TCHAR[_tcslen(pszpaste)+_tcslen(pszcut)+_tcslen(pszconvert)+5];
		_tcscpy(pszdone, pszpaste);
		_tcscat(pszdone, pszconvert);
		_tcscat(pszdone, pszcut);
		AfxMessageBox(pszdone, Button, Help);
		delete pszcut;
		delete pszpaste;
		delete pszconvert;
		delete pszdone;
		ASSERT(FALSE);
		return 0;
	    }
	} // case

	delete pszdone;
	pszdone = new TCHAR[_tcslen(pszpaste)+_tcslen(pszcut)+_tcslen(pszconvert)+5];
	_tcscpy(pszdone, pszpaste);
	_tcscat(pszdone, pszconvert);
	_tcscat(pszdone, pszcut);
	// Now pszdone holds the entire message.
	// Check to see if there are more insertions to be made or not

	if (!_tcsstr(pszdone, _T("%")))	{
	    UINT rt_type = AfxMessageBox(pszdone, Button, Help);
	    delete pszcut;
	    delete pszpaste;
	    delete pszconvert;
	    delete pszdone;
	    return rt_type;
	} // if

	// there are more insertions to make, prepare the strings to use.
	x = _tcscspn(pszdone, _T("%"));
	_tcscpy(pszcut, &pszdone[x+2]);
	_tcsncpy(pszpaste, pszdone, x);
	pszpaste[x] = _T('\0');
	chread = pszdone[x+1];

    } // for
    ASSERT(FALSE);
    return 0;

} // ShowMessageBox
bool CWebCDCovers::RetrieveList(int nIndex, CString strCriteria, HWND hwndList, HTREEITEM htiParent, HWND hwndProgress, HWND hwndStatus, CString strMsg)
{
	bool bSuccess = false;

	COVERIMAGES* pCoverImages;

	HOSTMAP* pMap = &((CCdCoverCreator2App*) AfxGetApp ())->m_mapCoverHosts;
	RESOURCEHOST* pHost;

	char* lpszData = NULL;
	CString strHTML, strName;
	char szUrl[300], szHeaders[300], szData[300];
	int nMethod, nPages;
	bool bPagesSet, bExpanded = false;

	::PostMessage (hwndProgress, PBM_SETPOS, 0, 0);
	::ShowWindow (hwndProgress, SW_SHOW);

	for (HOSTMAP::iterator it = pMap->begin (); it != pMap->end (); it++)
	{
		pHost = (*it).second;
		if (!pHost->bEnabled)
			continue;

		WCC_GETREQUEST* pfn_wccRequest = (WCC_GETREQUEST*) GetProcAddress (pHost->hInst, nIndex == WCC_LIST ? "GetListCoversRequest" : "GetSearchCoversRequest");
		WCC_GETLIST* pfn_wccList = (WCC_GETLIST*) GetProcAddress (pHost->hInst, nIndex == WCC_LIST ? "ListCovers" : "SearchCovers");

		bSuccess = true;
		bPagesSet = false;

		pfn_wccRequest (strCriteria.GetBuffer (0), "", szUrl, &nMethod, szHeaders, szData);

		while (*szUrl)
		{
			// Send the request
			AfxGetApp ()->BeginWaitCursor ();
			strHTML = CHttpRequest::DownloadBuffer (szUrl, nMethod, szHeaders, szData,
				m_pbCancelDownload, m_dwDownloadId, m_nError, 0, NULL, hwndStatus, strMsg);
			AfxGetApp ()->EndWaitCursor ();
			
			lpszData = new char[strHTML.GetLength () + 1];

			// Parse the list
			if (!pfn_wccList (strHTML.GetBuffer (0), strCriteria.GetBuffer (0), lpszData, szUrl, &nMethod, szHeaders, szData, &nPages))
			{
				delete lpszData;
				lpszData = NULL;
				continue;
			}

			if (nPages >= 1)
			{
				// has multiple pages
				if (!bPagesSet)
				{
					::SendMessage (hwndProgress, PBM_SETRANGE32, 1, nPages);
					::SendMessage (hwndProgress, PBM_SETSTEP, 1, 0);
					::SendMessage (hwndProgress, PBM_SETPOS, 0, 0);
					::ShowWindow (hwndProgress, SW_SHOW);
					bPagesSet = true;
				}
				else
					::SendMessage (hwndProgress, PBM_STEPIT, 0, 0);
			}
			else
			{
				// only one page...
				::ShowWindow (hwndProgress, SW_HIDE);
			}

			// fill the List
			for (int nPos = 0; ; )
			{
				pCoverImages = new COVERIMAGES;
				pCoverImages->pHost = pHost;

				if (!GetData (lpszData, nPos, strName, pCoverImages))
				{
					delete pCoverImages;
					break;
				}

				if (htiParent == NULL)
				{
					// this is a list control

					LVITEM item;
					item.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
					item.iItem = ListView_GetItemCount (hwndList);
					item.iSubItem = 0;
					item.pszText = (LPSTR) (LPCTSTR) strName;
					item.iImage = 1;
					item.lParam = (DWORD) pCoverImages;
					ListView_InsertItem (hwndList, &item);
				}
				else
				{
					bool bChanged = true;

					// look for item already in the tree
					TVITEM item;
					char szText[500];
					for (HTREEITEM hItem = TreeView_GetChild (hwndList, htiParent); hItem != NULL; hItem = TreeView_GetNextSibling (hwndList, hItem))
					{
						item.mask = TVIF_TEXT | TVIF_PARAM;
						item.hItem = hItem;
						item.pszText = szText;
						item.cchTextMax = 500;
						TreeView_GetItem (hwndList, &item);

						// item has been found
						if (strName == szText)
						{
							if (!CoverImagesAreEqual (pCoverImages, (COVERIMAGES*) item.lParam))
							{
								// remove old item and replace it by new one if it has changed
								delete (COVERIMAGES*) item.lParam;
								TreeView_DeleteItem (hwndList, hItem);
							}
							else
								bChanged = false;

							break;
						}
					}

					// insert the item if it has changed (or is new)
					if (bChanged)
					{
						TVINSERTSTRUCT insert;
						insert.hParent = htiParent;
						insert.hInsertAfter = TVI_SORT;
						insert.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
						insert.item.pszText = (LPSTR) (LPCTSTR) strName;
						insert.item.iImage = 1;
						insert.item.iSelectedImage = 1;
						insert.item.lParam = (DWORD) pCoverImages;

						TreeView_InsertItem (hwndList, &insert);
					}
				}
			}

			// expand the branch
			if (!bExpanded)
			{
				TreeView_Expand (hwndList, htiParent, TVE_EXPAND);
				bExpanded = true;
			}

			// clean up
			if (lpszData != NULL)
			{
				delete lpszData;
				lpszData = NULL;
			}
		}
	}

	::ShowWindow (hwndProgress, SW_HIDE);

	return bSuccess;
}
Ejemplo n.º 27
0
Bool CCompiler::OnCompileSucceeded( )
{
    CString exePath = GetCompiledExeFilePath();
    if( !CPath::FileExists(exePath) )
    {
        CL_ERROR( "Compiled succeeded but the file:[%s] was not found", exePath.GetBuffer() );
        return false;
    }
    
    CString inputFileName = GetExePath() + "input.in";
    CString outputFileName = GetExePath() + "output.out";

    CPath::DeleteFile( inputFileName );
    CPath::DeleteFile( outputFileName );

    // write the program input to the file
    FileSystem::FileHandle inputFileHandle = FileSystem::CreateFile( EFileType::E_FILE_TYPE_MEMORY );
    if(!inputFileHandle->Open( inputFileName, EAccesMode::E_ACCES_MODE_WRITE ) )
    {
        CL_ERROR("failed to set the program input");
        return false;
    }

    if( !inputFileHandle->Write( m_programInput, m_programInput.GetLenght(), 1 ) )
    {
        CL_ERROR("failed to set the program input");
        return false;
    }

    // close the input file so that the new program can read from it;
    inputFileHandle->Close();

#if !defined (CL_USE_PROCESS)

    CString command = "call " +  StringUtils::Quote(exePath) + " < " + StringUtils::Quote( inputFileName ) + " > " + StringUtils::Quote( outputFileName );

    RunCommand( command );

    Sleep( 3000 );//sleep 3 second so we can let the process to do the job;
    FileSystem::FileHandle outputFileHandle = FileSystem::CreateFile( EFileType::E_FILE_TYPE_MEMORY );

    if( !outputFileHandle->Open( outputFileName, EAccesMode::E_ACCES_MODE_READ ) )
    {
        CL_ERROR("failed to get the output of the your program" );
        return false;
    }

    u64 fileSize = outputFileHandle->GetSize();
    if(fileSize == 0)
    {
        CL_ERROR("failed to get the output of your program");
        return false;
    }
    
    CString outputFileContent;
    outputFileContent.Resize( fileSize + 1 );

    if( !outputFileHandle->Read( outputFileContent.GetBuffer(), fileSize, 1 ) )
    {
        CL_ERROR( "failed to get the output of your program" );
        return false;
    }

    m_programOutput = outputFileContent;

#elif defined( CL_USE_PROCESS )
    SECURITY_ATTRIBUTES sa;
    ThZeroMemoryTmpl(sa);
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE; 



    HANDLE inputFileHandle = CreateFileA(   inputFile.GetBuffer(),
                                            FILE_APPEND_DATA,
                                            FILE_SHARE_WRITE | FILE_SHARE_READ,
                                            &sa,
                                            OPEN_ALWAYS,
                                            FILE_ATTRIBUTE_NORMAL,
                                            NULL
                                        );

    if( inputFileHandle == INVALID_HANDLE_VALUE )
    {
        CL_ERROR("failed to redirect child process stdin ");
        CL_ERROR("WIN last error = %d", GetLastError());
        return false;
    }

    HANDLE outputFileHandle = CreateFileA(outputFile.GetBuffer(),
                                            GENERIC_READ | GENERIC_WRITE,
                                            FILE_SHARE_WRITE | FILE_SHARE_READ,
                                            &sa,
                                            CREATE_ALWAYS,
                                            FILE_ATTRIBUTE_NORMAL,
                                            NULL
                                        );

    if( outputFileHandle == INVALID_HANDLE_VALUE )
    {
        CL_ERROR("failed to redirect child process stout ");
        CL_ERROR("WIN last error = %d", GetLastError());
        return false;
    }


    SetHandleInformation(inputFileHandle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);

    // setup startup info
    STARTUPINFO processStartupInfo;
    ThZeroMemoryTmpl(processStartupInfo);
    processStartupInfo.cb = sizeof(processStartupInfo);
    processStartupInfo.dwFlags |= STARTF_USESTDHANDLES;
    processStartupInfo.hStdInput = inputFileHandle;
    processStartupInfo.hStdOutput = outputFileHandle;


    PROCESS_INFORMATION processInfo;

    if( !CreateProcessA( exePath.GetBuffer() // application name  
                        ,exePath.GetBuffer()
                        ,NULL
                        ,NULL
                        ,TRUE
                        ,0
                        ,NULL
                        ,NULL
                        ,&processStartupInfo
                        ,&processInfo) 
        )
    {
        CL_ERROR("Cannot start process:[%s]", exePath.GetBuffer());
        return false;
    }

    WaitForSingleObject(processInfo.hProcess, 3000 );
    CloseHandle( processInfo.hThread );
    CloseHandle( processInfo.hProcess );
#endif
    return true;
}
Ejemplo n.º 28
0
void SessionLayout::DoDisplayHistoryMsgToIE(std::vector<MessageEntity>& msgList, BOOL scrollBottom)
{
	Json::Value root;
	for (auto itMsg = msgList.rbegin();itMsg != msgList.rend(); ++itMsg)
	{
		module::UserInfoEntity userInfo;
		if (!module::getUserListModule()->getUserInfoBySId(itMsg->talkerSid, userInfo))
			continue;

		//组装json data
		Json::Value msgItem;
		msgItem["name"] = util::cStringToString(userInfo.getRealName());
		msgItem["avatar"] = userInfo.getAvatarPathWithoutOnlineState();
		msgItem["mtype"] = itMsg->isMySendMsg() ? "me" : "other";
		CTime time(itMsg->msgTime);
		msgItem["time"] = util::cStringToString(time.Format(_T("%Y-%m-%d %H:%M:%S")));
		msgItem["uuid"] = itMsg->talkerSid;
		msgItem["msgtype"] = itMsg->msgRenderType;

		if (MESSAGE_RENDERTYPE_AUDIO == itMsg->msgRenderType)
		{
			msgItem["voiceid"] = itMsg->content;
			CString sVoicetime;
			sVoicetime.Format(_T("%d秒"), itMsg->msgAudioTime);
			msgItem["voicetime"] = util::cStringToString(sVoicetime, CP_UTF8);
			msgItem["voiceisread"] = itMsg->isReaded() ? std::string("true") : string("false");
		}
		else
		{
			std::string msgDecrptyCnt;
			DECRYPT_MSG(itMsg->content, msgDecrptyCnt);
			CString content = util::stringToCString(msgDecrptyCnt);
			ReceiveMsgManage::getInstance()->parseContent(content, FALSE, GetWidth());
			msgItem["content"] = util::cStringToString(content);
		}

		root.append(msgItem);
	}

	Json::StyledWriter styleWrite;
	std::string record = styleWrite.write(root);
	CString jsData = _T("[]");
	Json::Reader jsonRead;
	Json::Value rootRead;
	if (!jsonRead.parse(record, rootRead) || rootRead.isNull())
	{
		CString csError = util::stringToCString(record, CP_UTF8);
		LOG__(ERR, _T("history is null or json parse error:%s"), csError);
		jsData = _T("[]");
	}
	else
	{
		jsData = util::stringToCString(record);
	}

	//调用js
	CComVariant result;
	BOOL bRet = m_pWebBrowser->CallJScript(_T("historyMessage"), jsData.GetBuffer(), &result);
	if (!bRet)
		LOG__(ERR, _T("CallJScript failed,%s"), jsData);
	if (scrollBottom)
	{
		module::getEventManager()->asynFireUIEventWithLambda(
			[=]()
		{
			CComVariant result;
			m_pWebBrowser->CallJScript(_T("scrollBottom"), _T(""), &result);
		});
	}
}
Ejemplo n.º 29
0
/**
* Handles keyboard input to process the "Enter" key to execute 
* commands and command history.
*/
BOOL ConsoleView::PreTranslateMessage(MSG* pMsg) {

	if (pMsg->hwnd == editInput.GetSafeHwnd()) {

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN ) {
			this->ExecuteCommand();
			return TRUE;
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_UP ) {     
			//save off the current in-progress command so we can get back to it
			if ( saveCurrentCommand == true ) {
				CString str;
				editInput.GetWindowText ( str );
				currentCommand = str.GetBuffer ( 0 );
				saveCurrentCommand = false;
			}

			if ( consoleHistory.Num () > 0 ) {
				editInput.SetWindowText ( consoleHistory[currentHistoryPosition] );

				int selLocation = consoleHistory[currentHistoryPosition].Length ();
				editInput.SetSel ( selLocation , selLocation + 1);
			}

			if ( currentHistoryPosition > 0) {
				--currentHistoryPosition;
			}

			return TRUE;
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_DOWN ) {  
			int selLocation = 0;
			if ( currentHistoryPosition < consoleHistory.Num () - 1 ) {
				++currentHistoryPosition;
				editInput.SetWindowText ( consoleHistory[currentHistoryPosition] );
				selLocation = consoleHistory[currentHistoryPosition].Length ();
			}
			else {
				editInput.SetWindowText ( currentCommand );
				selLocation = currentCommand.Length ();
				currentCommand.Clear ();
				saveCurrentCommand = true;
			}

			editInput.SetSel ( selLocation , selLocation + 1);

			return TRUE;
		}
		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_TAB ) {  
			common->Printf ( "Command History\n----------------\n" );
			for ( int i = 0 ; i < consoleHistory.Num ();i++ )
			{
				common->Printf ( "[cmd %d]:  %s\n" , i , consoleHistory[i].c_str() );
			}
			common->Printf ( "----------------\n" );
		}
		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_NEXT) {  
			editConsole.LineScroll ( 10 );	
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_PRIOR ) {  
			editConsole.LineScroll ( -10 );	
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_HOME ) {  
			editConsole.LineScroll ( -editConsole.GetLineCount() );	
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_END ) {  
			editConsole.LineScroll ( editConsole.GetLineCount() );	
		}
	}

	return CFormView::PreTranslateMessage(pMsg);
}
Ejemplo n.º 30
0
bool init_excel_file(const char* excel_name, std::vector<item_attire_data>& items)
{
	char* names[] = {"ºï", "ÍÃ", "ÐÜ", "Áú"};
	for(int i =0; i< sizeof(names)/sizeof(names[0]); i++)
	{
		std::map<int, CString> column_names;
		CSpreadSheet ss(excel_name, names[i]);
		for(int i = 1; i<= ss.GetTotalColumns(); i++)
		{
			CString name;
			ss.ReadCell(name, i, 1);
			column_names[i] = name;
		}

		
		for(int i = 2; i<= ss.GetTotalRows(); i++)
		{
			item_attire_data data;
			for(int j = 1; j< ss.GetTotalColumns(); j++)
			{
				CString value;

				ss.ReadCell(value, j, i);
				if( column_names[j] == "Item ID" && value != "")
				{
					data.id = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Item ID", i);
				if( column_names[j] == "Name" && value != "")
				{		
					std::string utf_str = GBToUTF8(value.GetBuffer(0));
					//strcpy(data.name,  value.GetBuffer(0));	
					strcpy(data.name, utf_str.c_str());
					continue;
				}
				//ss.ReadCell(value, "Name", i);
				if( column_names[j] == "DropLv" && value != "")
				{
					data.droplv = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "DropLv", i);
				if( column_names[j] == "QualityLevel" && value != "")
				{
					data.quality_level = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "QualityLevel", i);
				if( column_names[j] == "EquipPart" && value != "")
				{
					data.equip_part = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "EquipPart", i);
				if( column_names[j] == "Price" && value != "")
				{
					data.price = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Price", i);
				if( column_names[j] == "SellPrice" && value != "")
				{
					data.sell_price = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "SellPrice", i);
				if( column_names[j] == "RepairPrice" && value != "")
				{
					data.repair_price = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "RepairPrice", i);
				if( column_names[j] == "UseLv" && value != "")
				{
					data.uselv = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "UseLv", i);
				if( column_names[j] == "Strength" && value != "")
				{
					data.strength = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Strength", i);
				if( column_names[j] == "BodyQuality" && value != "")
				{
					data.body_quality = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "BodyQuality", i);
				if( column_names[j] == "Stamina" && value != "")
				{
					data.stamina = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Stamina", i);
				if( column_names[j] == "Atk" && value != "")
				{
					strcpy(data.atk, value.GetBuffer(0));
					continue;
				}
				//ss.ReadCell(value, "Atk", i);
				if( column_names[j] == "Def" && value != "")
				{
					data.def = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Def", i);
				if( column_names[j] == "Duration" && value != "")
				{
					data.duration = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Duration", i);
				if( column_names[j] == "Hit" && value != "")
				{
					data.hit = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Hit", i);
				if( column_names[j] == "Dodge" && value != "")
				{
					data.dodge = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Dodge", i);
				if( column_names[j] == "Crit" && value != "")
				{
					data.crit = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Crit", i);
				if( column_names[j] == "Hp" && value != "")
				{
					data.hp = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Hp", i);
				if( column_names[j] == "Mp" && value != "")
				{
					data.mp = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Mp", i);
				if( column_names[j] == "AddHp" && value != "")
				{
					data.add_hp = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "AddHp", i);
				if( column_names[j] == "AddMp" && value != "")
				{
					data.add_mp = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "AddMp", i);
				if( column_names[j] == "Slot" && value != "")
				{
					data.slot = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Slot", i);
				if( column_names[j] == "Tradability" && value != "")
				{
					data.trade_ability = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Tradability", i);
				if( column_names[j] == "VipTradability" && value != "")
				{
					data.vip_trade_ability = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "VipTradability", i);
				if( column_names[j] == "Tradable" && value != "")
				{
					data.trade_able = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Tradable", i);
				if( column_names[j] == "SetID" && value != "")
				{
					data.setid = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "SetID", i);
				if( column_names[j] == "DailyId" && value != "")
				{
					data.dailyid = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "DailyId", i);
				if( column_names[j] == "ExploitValue" && value != "")
				{
					data.exploit_value = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "ExploitValue", i);
				if( column_names[j] == "honorLevel" && value != "")
				{
					data.honor_level = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "honorLevel", i);
				if( column_names[j] == "VipOnly" && value != "")
				{
					data.vip_only = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "VipOnly", i);
				if( column_names[j] == "decompose" && value != "")
				{
					data.decompose = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "decompose", i);
				if( column_names[j] == "Shop" && value != "")
				{
					data.shop = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "Shop", i);
				if( column_names[j] == "UnStorage" && value != "")
				{
					data.un_storage = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "UnStorage", i);
				if( column_names[j] == "resID" && value != "")
				{
					data.res_id = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "resID", i);
				if( column_names[j] == "LifeTime" && value != "")
				{
					data.life_time = atoi(value);
					continue;
				}
				//ss.ReadCell(value, "LifeTime", i);
				if( column_names[j] == "descript" && value != "")
				{
					string utf_str = GBToUTF8( value.GetBuffer(0));
					strcpy(data.descipt, utf_str.c_str());
					continue;
				}
				//ss.ReadCell(value, "descript", i);
				continue;
				//
			}//for
			
			if(data.id == 0)
			{
				continue;
			}
			items.push_back(data);
		}

	}


	return true;
}