示例#1
0
bool UpkUse7z(LPCTSTR szExeFile, LPCTSTR szExtractPath, Files &files)
{
#if 0 
	static CExeUnpack7z *upk=NULL;
	if(!upk)
	{
		upk = new CExeUnpack7z;
		upk->Initialize(szPath7z, szPathWcx);
	}
	
	strings fs;
	CStringA s1 = CT2CA(szExeFile);
	CStringA s2 = CT2CA(szExtractPath);
	bool bRet = upk->Extract(s1, s2, fs);
	if(bRet)
	{
		for(size_t i=0; i<fs.size(); ++i)
		{
			files.push_back( CString(CA2CT(fs[i].c_str())) );
		}
	}
	return bRet;
#endif
	return false;
}
// CDialogConfig message handlers
void CDialogConfig::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here
	if(this->isValidate())
	{
		CString lpszTemp;

		m_cWeatherAddress.GetWindowText(m_systemConfig.lpszWeatherAddress);
		m_cWeatherPort.GetWindowText(lpszTemp);
		m_systemConfig.nWeatherPort = atoi(CT2CA(lpszTemp));

		m_cAlarmAddress.GetWindowText(m_systemConfig.lpszAlarmAddress);
		m_cAlarmPort.GetWindowText(lpszTemp);
		m_systemConfig.nAlarmPort = atoi(CT2CA(lpszTemp));

		m_cAdminPort.GetWindowText(lpszTemp);
		m_systemConfig.nAdminPort = atoi(CT2CA(lpszTemp));
		////////////++Add 14/01/2013 ThangNH7///////////////
		m_systemConfig.crColorTemperare = this->m_ColorTemperature.GetColor();
		m_systemConfig.crColorPressure = this->m_ColorPressure.GetColor();
		m_systemConfig.crColorWind = this->m_ColorWind.GetColor();
		////////--Add 14/01/2013 ThangNH7///////////////
		CGlobalFunction::WriteFile(FILENAME, m_systemConfig);
	}

	CDialogEx::OnOK();
}
示例#3
0
	bool Open(LPCTSTR szFilename) throw()
	{
		if ( hArchive )
			unzClose( hArchive );
		hArchive = unzOpen( CT2CA( szFilename ) );
		if ( ! hArchive )
		{
			TCHAR szFileShort[ MAX_PATH ];
			if ( GetShortPathName( szFilename, szFileShort, MAX_PATH ) )
				hArchive = unzOpen( CT2CA( szFileShort ) );
		}
		return ( hArchive != NULL );
	}
示例#4
0
BOOL CDlgVidMan::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) 
{
	LPNMHDR nm = (LPNMHDR) lParam;
	USES_CONVERSION;

	int nID = 0;

	if (nm->code == TBN_GETINFOTIPA)
	{
		if (nm->hwndFrom == m_barMute.m_hWnd)
			nID = ID_DLD_VID_MUTE;
		else if (nm->hwndFrom == m_barMan.m_hWnd)
			nID = ((LPNMTBGETINFOTIPA) nm)->iItem;
	}

	if (nID == 0)
		return CDialog::OnNotify(wParam, lParam, pResult);
 
	switch (nm->code)
	{
		case TBN_GETINFOTIPA:	
		{
			LPNMTBGETINFOTIPA inf = (LPNMTBGETINFOTIPA) nm;
			
			switch (nID)
			{
				case ID_DLD_VID_MUTE:
					strcpy (inf->pszText, CT2CA((LPCTSTR)LS (L_MUTE)));
					break;

				case ID_DLD_VID_PLAY:
					strcpy (inf->pszText, CT2CA((LPCTSTR)LS (L_PLAY)));
					break;

				case ID_DLD_VID_PAUSE:
					strcpy (inf->pszText, CT2CA((LPCTSTR)LS (L_PAUSE)));
					break;

				case ID_DLD_VID_STOP:
					strcpy (inf->pszText, CT2CA((LPCTSTR)LS (L_STOP)));
					break;

			}
		}
		break;
	}

	*pResult = TRUE;

	return TRUE;
}
示例#5
0
void CNewsHubDlg::OnBnClickedServerStart()
{
  CEdit* pPort = (CEdit*)GetDlgItem(IDC_SERVER_PORT);
  CString strPort;
  pPort->GetWindowText(strPort);
  int port = atoi(CT2CA(strPort));

  CButton* pServerTcp = (CButton*)GetDlgItem(IDC_SERVER_TCP);
  bool bTcp = (pServerTcp->GetCheck() == BST_CHECKED);

  ServerLoop* serverLoop;
  try
  {
    NewsHub::Server* server;
    if (bTcp)
      server = new NewsHub::TcpServer(port);
    else
      server = new NewsHub::UdpServer(port);
    serverLoop = new ServerLoop(server, new NewsHub::ServerThreadLoop(*server, *this, bTcp));
  }
  catch (std::exception & e)
  {
    MessageBox(CString(e.what()), _T("Exception"), MB_OK);
    return;
  }

  CString serverDescription = CString(bTcp?"TCP":"UDP") + CString(" server is listening on port ") + strPort; 

  CListBox* pRunningServers = (CListBox*)GetDlgItem(IDC_RUNNING_SERVERS);
  int row = pRunningServers->AddString(serverDescription);
  pRunningServers->SetItemDataPtr(row, serverLoop);
}
示例#6
0
UINT_PTR CBkSafeMsgBox::ShowPanelMsg( LPCWSTR lpszXml, LPCRECT lpRect
									 , LPCWSTR lpszCaption /*= NULL*/, UINT uType /*= MB_OK*/, BOOL *pbNoNotifyLater /*= NULL*/, HWND hWndParent /*= NULL */ )
{
	ATLASSERT(lpRect);
	if (!lpRect || !Load(IDR_BK_MESSAGEBOX))
		return -1;
	
	m_isTextXml = TRUE;
	m_rcXml = *lpRect;
	m_uType = uType;
	SetItemVisible(60016, TRUE);
	SetItemVisible(IDC_LBL_MSGBOX_TEXT, FALSE);
	SetPanelXml(60016, CT2CA(lpszXml, CP_UTF8));
	if (lpszCaption)
	{
		m_strCaption    = lpszCaption;
		SetWindowCaption(m_strCaption);
		SetItemText(IDC_LBL_MSGBOX_TITLE, lpszCaption);
	}
	_InitLayout(pbNoNotifyLater);

	UINT_PTR nRet = DoModal(hWndParent);
	if (pbNoNotifyLater)
		*pbNoNotifyLater = m_bNoNotifyLater;

	return nRet;
}
示例#7
0
BOOL file_put_contents(LPCTSTR lpszFilename, LPCTSTR lpszBuffer)
{
	CStringA strA;
	USES_CONVERSION;
	strA = CT2CA( lpszBuffer );
	return file_put_contents(lpszFilename, (BYTE*)strA.GetString(), strA.GetLength());
}
示例#8
0
void CNewsHubDlg::OnBnClickedSend()
{
  CListBox* pRunningClients = (CListBox*)GetDlgItem(IDC_RUNNING_CLIENTS);

  int row = pRunningClients->GetCurSel();
  if (row == LB_ERR)
  {
    MessageBox(_T("Please select one of running clients to send message through"), _T("No client selected"), MB_OK);
    return;
  }

  CEdit* pMessage = (CEdit*)GetDlgItem(IDC_MESSAGE);
  CString message;
  pMessage->GetWindowText(message);

  ClientLoop* clientLoop = (ClientLoop*)pRunningClients->GetItemDataPtr(row);
  unsigned int messageId = clientLoop->nextMessageId();
  clientLoop->Queue()->AddMessage(messageId, std::string(CT2CA(message)));

  CListBox* pSentMessages = (CListBox*)GetDlgItem(IDC_SENT_MESSAGES);
  NewsHub::TcpClient* tcpClient = (NewsHub::TcpClient*)clientLoop->Client();
  CString str;
  str.Format(_T("(To: %s:%d msgId:%d): %s"), 
    CString(tcpClient->Host().c_str()), tcpClient->Port(), messageId, message);

  row = pSentMessages->AddString(str);

  MessageInfo* messageInfo = new MessageInfo;
  messageInfo->queue = clientLoop->Queue();
  messageInfo->messageId = messageId;
  pSentMessages->SetItemDataPtr(row, messageInfo);

  pSentMessages->SetCurSel(row);
}
示例#9
0
	bool Extract(LPCTSTR szSrc, char** ppBuf, DWORD* pdwSize = NULL) throw()
	{
		if ( pdwSize )
			*pdwSize = 0;
		*ppBuf = NULL;

		bool ret = false;
		if ( unzLocateFile( hArchive, CT2CA( szSrc ), 2 ) == UNZ_OK )
		{
			unz_file_info fi = {};
			if ( unzGetCurrentFileInfo( hArchive, &fi, NULL, NULL, NULL, NULL, NULL, NULL ) == UNZ_OK )
			{
				if ( unzOpenCurrentFile( hArchive ) == UNZ_OK ) 
				{
					if ( pdwSize )
						*pdwSize = fi.uncompressed_size;
					*ppBuf = new char[ fi.uncompressed_size + 2 ];
					if ( *ppBuf )
					{
						ZeroMemory( *ppBuf, fi.uncompressed_size + 2 );
						ret = ( unzReadCurrentFile( hArchive, *ppBuf, fi.uncompressed_size ) == (int)fi.uncompressed_size );
					}
					unzCloseCurrentFile( hArchive );
				}
			}
		}
		return ret;
	}
int CIpRuleFile::CompareIpAddress( LPCTSTR address1,LPCTSTR address2 )
{
	USES_CONVERSION;
	ULONG a = ntohl(inet_addr(CT2CA(address1)));
	ULONG b = ntohl(inet_addr(CT2CA(address2)));
	if (a <b)
	{
		return -1;
	}
	else if (a ==b)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
示例#11
0
bool UpdateEntity::Update() {	
	bool bHasError = false;
	std::vector<std::shared_ptr<UP_PACK>>	cmp;		//需要清除的队列
	std::shared_ptr<UP_PACK> pack = mUpData_.getBegin();

	svy::SinglePtr<AppModule> app;	//

	while (pack = mUpData_.getNext()) {
		CString dst = svy::FindFilePath(mExe_.getPathFile());
		CString src = pack->path;
		if (!svy::CopyDir(src, dst)) {
			bHasError = true;
			break;
		}
		pack->step = Step::CompleteAll;
		cmp.push_back(pack);
		lua_State *L = app->getLua();
		CString luaMain = svy::catUrl(dst,_T("maintain\\maintain.lua"));
		if (luaL_dofile(L, CT2CA(luaMain))) {
			lua_getglobal(L, "UpdateComplete");
			lua_pushstring(L, CT2CA(pack->ver));
			lua_pushstring(L, CT2CA(dst));
			lua_pcall(L, 2, 0, 0);
		}
		//移除升级文件
		svy::DeleteDir(src);
	}
	//清除完成的包对于错误的下次继续执行
	//可能由于程序关闭后没有完全释放导致覆盖失败
	size_t nCount = cmp.size();
	for (size_t nI = 0; nI < nCount;nI++) {
		pack = cmp[nI];
		mCurVer_ = pack->ver;
		mUpData_.erase(pack);
	}
	if(!bHasError){
		//清除所有数据
		mUpData_.clear();
	}
	cmp.clear();
	return (!bHasError);
}
示例#12
0
文件: ALog.cpp 项目: ddavison/Jaangle
BOOL FileViewer::Show(LPCTSTR description)
{
	if (m_hFile != INVALID_HANDLE_VALUE)
	{
		DWORD bytesWritten = 0;
		if (!WriteFile(m_hFile, (LPCSTR)CT2CA(description), (DWORD)_tcslen(description), &bytesWritten, NULL))
			return FALSE;//FlushFileBuffers(m_hFile);
		return bytesWritten > 0;
	}
	return FALSE;
}
示例#13
0
bool saveVerConfigToFile(const CString& file, VerConfig &ret) {
	tinyxml2::XMLDocument	doc;
	tinyxml2::XMLElement *root = doc.NewElement("Root");
	tinyxml2::XMLElement *nd1  = doc.NewElement("Version");
	tinyxml2::XMLElement *nd2  = doc.NewElement("ProductCode");
	tinyxml2::XMLElement *nd3  = doc.NewElement("EntryName");	
	if (root && nd1 && nd2 && nd3)
	{
		root->InsertEndChild(nd1);
		root->InsertEndChild(nd2);
		root->InsertEndChild(nd3);

		nd1->SetText(CT2CA(ret.mVer_));
		nd2->SetText(CT2CA(ret.mProductCode_));
		nd3->SetText(CT2CA(ret.mEntryName_));

		if( tinyxml2::XML_SUCCESS==doc.SaveFile(CT2CA(file)) )
			return true;
	}
	return false;
}
示例#14
0
void CNewsHubDlg::OnBnClickedClientStart()
{
  CEdit* pPort = (CEdit*)GetDlgItem(IDC_PORT);
  CEdit* pHost = (CEdit*)GetDlgItem(IDC_HOST);
  CEdit* pTimeout = (CEdit*)GetDlgItem(IDC_TIMEOUT);

  CString host, strPort, strTimeout;
  pHost->GetWindowText(host);
  pPort->GetWindowText(strPort);
  pTimeout->GetWindowText(strTimeout);
  int port = atoi(CT2CA(strPort));
  int timeout = atoi(CT2CA(strTimeout));

  CButton* pClientTcp = (CButton*)GetDlgItem(IDC_CLIENT_TCP);
  bool bTcp = (pClientTcp->GetCheck() == BST_CHECKED);

  ClientLoop* clientLoop;
  try
  {
    NewsHub::Client* client;
    if (bTcp)
      client = new NewsHub::TcpClient(std::string(CT2CA(host)), port);
    else
      client = new NewsHub::UdpClient(std::string(CT2CA(host)), port);

    clientLoop = new ClientLoop(client, new NewsHub::ClientQueueThreadLoop(*client, *this, timeout * 1000));
  }
  catch (std::exception & e)
  {
    MessageBox(CString(e.what()), _T("Exception"), MB_OK);
    return;
  }

  CString clientDescription = CString(bTcp?"TCP":"UDP") + CString(" client to host ") + host + CString(" on port ") + strPort; 

  CListBox* pRunningClients = (CListBox*)GetDlgItem(IDC_RUNNING_CLIENTS);
  int row = pRunningClients->AddString(clientDescription);
  pRunningClients->SetItemDataPtr(row, clientLoop);
}
示例#15
0
std::string UpdateEntity::BuildBody(XML_TYPE t) {
	CString val;
	
	tinyxml2::XMLDocument	doc;
	tinyxml2::XMLElement *root = doc.NewElement("SQSJREQUEST");
	tinyxml2::XMLElement *ver  = doc.NewElement("VERSION");
	tinyxml2::XMLElement *body = doc.NewElement("BODY");
	tinyxml2::XMLElement *nsrsbh = doc.NewElement("NSRSBH");
	tinyxml2::XMLElement *actcode = doc.NewElement("ACTIONCODE");
	tinyxml2::XMLElement *zsmd5 = doc.NewElement("ZSMD5");
	tinyxml2::XMLElement *extend = doc.NewElement("EXTEND");
	tinyxml2::XMLElement *products = doc.NewElement("PRODUCTS");
	tinyxml2::XMLElement *product = doc.NewElement("PRODUCT");
	//生成关系
	root->InsertEndChild(ver);
	root->InsertEndChild(body);	
	body->InsertEndChild(nsrsbh);
	body->InsertEndChild(actcode);
	body->InsertEndChild(zsmd5);
	body->InsertEndChild(extend);
	body->InsertEndChild(products);
	products->InsertEndChild(product);
	doc.LinkEndChild(root);
	//赋值
	ver->SetText("V1.0");
	nsrsbh->SetText("SERVYOU001");
	actcode->SetText("5002");
	{
		val.Format(_T("%s_%s"), mExe_.getPublicCA(), mExe_.getPrivateCA());
		val.MakeUpper();
		if (1 < val.GetLength()) {
			zsmd5->SetText(CT2CA(val,CP_UTF8));
		}
	}
	{
		NetConfig::SERVICE netcfg = mNetCfg_.mSvrs[0];
		val.Format(_T("serverip=%s"), netcfg.ip);
		extend->SetText(CT2CA(val, CP_UTF8));
	}
	{
		product->SetAttribute("CODE", CT2CA(mExe_.mVer_.mProductCode_, CP_UTF8));
		product->SetAttribute("TYPE", "001");
		product->SetAttribute("VERSION", CT2CA(mCurVer_, CP_UTF8) );
		product->SetAttribute("FBWJMD5", "");
	}
	std::string ret;
	if (t == BUILD_XML_FILE) {
		CString path;
		path.Format(_T("%s.xml"), svy::PathGetFileName(mExe_.getPathFile()));
		if (tinyxml2::XML_NO_ERROR == doc.SaveFile(CT2CA(path)))
			ret = CT2CA(path);
	}
	else	{
		tinyxml2::XMLPrinter printer;
		if( doc.Accept(&printer) )
			ret = printer.CStr();
	}
	return ret;
}
示例#16
0
void CSearchMonitorWnd::OnSecurityBan()
{
	int nItem = m_wndList.GetNextItem( -1, LVNI_SELECTED );
	if ( nItem >= 0 )
	{
		SOCKADDR_IN pHost = { 0 };
		pHost.sin_family = AF_INET;
		CString strNode = m_wndList.GetItemText( nItem, 3 );
		int nPos = strNode.Find( _T(':') );
		pHost.sin_addr.s_addr = inet_addr( CT2CA( (LPCTSTR)strNode.Left( nPos ) ) );
		pHost.sin_port = htons( (WORD)_tstoi( strNode.Mid( nPos + 1 ) ) );
		Security.Ban( &pHost.sin_addr, banSession );
	}
}
示例#17
0
void CSearchMonitorWnd::OnBrowseLaunch()
{
	int nItem = m_wndList.GetNextItem( -1, LVNI_SELECTED );
	if ( nItem >= 0 )
	{
		SOCKADDR_IN pHost = { 0 };
		pHost.sin_family = AF_INET;
		CString strNode = m_wndList.GetItemText( nItem, 3 );
		int nPos = strNode.Find( _T(':') );
		pHost.sin_addr.s_addr = inet_addr( CT2CA( (LPCTSTR)strNode.Left( nPos ) ) );
		pHost.sin_port = htons( (WORD)_tstoi( strNode.Mid( nPos + 1 ) ) );
		new CBrowseHostWnd( PROTOCOL_ANY, &pHost );
	}
}
/*******************************************************************
* ++
* Method name   :    void CDialogConfig::OnBnClickedOk()
* Description   :    CDialogConfig message handlers click OK
* 
* Parameters    :	 none
* Return values :	 none
* Mod. History  :    8.JAN.2013 - AnDB
*
* --
*******************************************************************/
void CDialogConfig::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here
	if(this->isValidate())
	{
		CString lpszTemp;
		// Get IP and Port Admin Center
		m_cAdminAddress.GetWindowText(m_systemConfig.lpszAdminAddress);
		m_cAdminPort.GetWindowText(lpszTemp);
		m_systemConfig.nAdminPort = atoi(CT2CA(lpszTemp));
		// Get IP and Port Alarm System
		m_cAlarmAddress.GetWindowText(m_systemConfig.lpszAlarmAddress);
		m_cAlarmPort.GetWindowText(lpszTemp);
		m_systemConfig.nAlarmPort = atoi(CT2CA(lpszTemp));
		// Get IP and Port Weather System
		m_cWeatherPort.GetWindowText(lpszTemp);
		m_systemConfig.nWeatherPort = atoi(CT2CA(lpszTemp));
		// Write new data to file init
		CGlobalFunction::WriteFile(FILENAME, m_systemConfig);
	}

	CDialogEx::OnOK();
}
示例#19
0
bool CExeUnpackPkg::Extract( LPCTSTR szfile, LPCTSTR szpath, strings &files )
{
	USES_CONVERSION;
	Files	filelist;
	if ( EE_SUCCESS == ExtractOfficePackage(szfile, szpath, filelist) )
	{
		for (int i=0; i<filelist.size(); i++)
		{
			std::string	str = CT2CA(filelist[i].GetString());
			files.push_back(str);
		}
		return true;
	}
	return false;
}
CStringA GetAnsiFromUnicode(LPCTSTR a_wstrString)
{
	USES_CONVERSION;
/*	static char	szBuffer[1024*1024+1]; // 1MB buffer to handle string 

	if (_tcslen( a_wstrString) > 1024*1024)
		AfxThrowMemoryException();
	strcpy_s( szBuffer, 1024*1024, CT2CA(a_wstrString));
	return szBuffer;
*/
	static CStringA csAnsi;

	csAnsi = CT2CA(a_wstrString);
	return csAnsi;
}
示例#21
0
int CTwain::LoadSourceManager(void)
{
	USES_CONVERSION;
	
	OFSTRUCT	of;

	if (nState >= SOURCE_MANAGER_LOADED) {
		return TRUE;			// SM already loaded
	}

	TCHAR szSM[MAX_PATH];
	GetWindowsDirectory(szSM, MAX_PATH);

	if (szSM[_tcsclen(szSM)-1] != '\\') 
	{
		_tcscat_s(szSM, MAX_PATH, _T("\\"));
	}

	_tcscat_s(szSM, MAX_PATH, _T(DSM_FILENAME));			// could crash!

	if (OpenFile(CT2CA(szSM), &of, OF_EXIST) != -1) 
	{
		hSMLib = LoadLibrary(szSM);
	} 
	else 
	{
		if (bTrace) ATLTRACE(_T("TWAIN:LoadLibrary(%s) failed\n"), szSM);
		hSMLib = NULL;
	}

	if (IsValidHandle(hSMLib)) {
		pSM_Entry = (DSMENTRYPROC) GetProcAddress(hSMLib, DSM_ENTRYPOINT);
		if (pSM_Entry) {
			iAvailable = 1;
			SetState(SOURCE_MANAGER_LOADED);
		} else {
			if (bTrace) ATLTRACE(_T("TWAIN:GetProcAddress() failed!!\n"));
			FreeLibrary(hSMLib);
			hSMLib = NULL;
		}
	} else {
		pSM_Entry = NULL;
	}

	if (nState != SOURCE_MANAGER_LOADED && bTrace) ATLTRACE(_T("TWAIN:LoadSourceManager() failed.\n"));
	return (nState >= SOURCE_MANAGER_LOADED);
} // LoadSourceManager
示例#22
0
文件: GZipFile.cpp 项目: e1z0/sMule
bool CGZIPFile::Open(LPCTSTR pszFilePath)
{
	ASSERT( m_gzFile == 0 );
	Close();

	m_gzFile = gzopen(CT2CA(pszFilePath), "rb");
	if (m_gzFile)
	{
		// Use gzip-uncompress only for real gzip-compressed files and do not let handle it also uncompressed files.
		// This way the 'Open' function can be used to check if that file is a 'gzip' file at all.
		if (gzdirect(m_gzFile) != 0)
			Close();
		else
			m_strGzFilePath = pszFilePath;
	}
	return m_gzFile != 0;
}
HRESULT CContextMenuHandler::GetCommandString(UINT_PTR idCmd, UINT uFlags, UINT *pwReserved, LPSTR pszName, UINT cchMax)
{
	if (uFlags == GCS_VERBA)
	{
		if (idCmd == IDM_PHOTORESIZE)
		{
			CStringA::CopyChars(pszName, cchMax, CT2CA(VERB_PHOTORESIZE), CString(VERB_PHOTORESIZE).GetLength());
			
			return S_OK;
		}
	}
	else if (uFlags == GCS_VERBW)
	{
		if (idCmd == IDM_PHOTORESIZE)
		{
			CStringW::CopyChars((LPWSTR)pszName, cchMax, CT2CW(VERB_PHOTORESIZE), CString(VERB_PHOTORESIZE).GetLength());

			return S_OK;
		}
	}

	return E_INVALIDARG;
}
示例#24
0
int _tmain(int argc, _TCHAR* argv[])
{
	cout << "Zhou's obj -> objx Converter, Mar.2016." << endl << endl;
	if(argc < 2)
	{
		cout << "Usage:" << endl << endl 
			 << "objcvt.exe [-a] [-c] [-p] \"input file path name\"" << endl<< endl 
			 << "-a: amalgamate groups as much as possible. Groups using different materials, or belonging to different objects, cannot be merged together." << endl 
			 << "-c: move geometry centre to the origin. Use it only when the source file contains one mesh" << endl 
			 << "-p: remove path from texture file name." << endl << endl;
		system("pause");
		return E_INVALIDARG;
	}

	TCHAR infile[MAX_PATH], outfile[MAX_PATH];
	bool amalgamation = false, centralization = false, removepath = false;
	for(int i = 1; i < argc; i++)
	{
		if(0 == StrCmpI(_T("-a"), argv[i]))
			amalgamation = true;
		else if(0 == StrCmpI(_T("-c"), argv[i]))
			centralization = true;
		else if(0 == StrCmpI(_T("-p"), argv[i]))
			removepath = true;
		else
			_tcscpy_s(infile, MAX_PATH, argv[i]);
	}
	_tcscpy_s(outfile, MAX_PATH, infile);
	PathRenameExtension(outfile, _T(".objx"));

	obj_mesh_data data;
	objects objs;
	mtllib mtlib;
	scene scn;
	if(!load_obj_file(infile, data, objs, mtlib, scn, amalgamation, removepath, disp_propress))
	{
		int err = GetLastError();
		printf("Failed to open input file, error code: %X.\n\n", err);
		system("pause");
		return err;
	}

	if(centralization)
		centralize(data.vertices);

	disp_statistics(data, objs, mtlib);

	scene_desc sd;
	sd.camera_pos = scn.cameraPosition;
	sd.camera_ypr = scn.cameraYPR;
	for(int i = 0; i < MAXLIGHTS; i++)
	{
		sd.light_pos[i] = scn.lightPositions[i];
		sd.light_dir[i] = scn.lightDirections[i];
	}
	HOBJXIO hobjxio = create_objx(outfile, sd);
	if(!hobjxio)
	{
		int err = GetLastError();
		printf("Failed to open input file, error code: %X.\n\n", err);
		system("pause");
		return err;
	}

	mesh_info mesh;
	for(int o = 0; o < (int)objs.size(); o++)
	{
		groups& grps = objs[o];
		for(groups::iterator g = grps.begin(); g != grps.end(); g++)
		{
			group& grp = g->second;
			for(group::iterator it = grp.begin(); it != grp.end(); it++)
			{
				material mtl;
				mtllib::iterator it_mtl = mtlib.find(it->first);
				if(mtlib.end() == it_mtl)
					mtl = DEF_MATERIAL;
				else
					mtl = it_mtl->second;

				faces& fs = it->second;
				if(!write_face(hobjxio, g->first, fs, data, mtl))
				{
					int err = GetLastError();
					printf("Failed to write output file, error code: %X.\n\n", err);
					break;
				}
			}
		}
	}

	close_objx(hobjxio);
	cout << endl << endl << "Succeeded." << endl << "Output file: \"" << CT2CA(outfile) << "\"" << endl << endl;
	system("pause");
	return 0;
}
示例#25
0
BOOL LastFMServices::HandShake(std::basic_string<TCHAR>& sessionID, 
							   std::basic_string<TCHAR>& nowPlayingURL, 
							   std::basic_string<TCHAR>& submissionURL)
{
	sessionID.clear();
	nowPlayingURL.clear();
	submissionURL.clear();
	if (m_username.empty() || m_MD5password.empty())
	{
		//TRACE(_T("@4 LastFMServices::HandShake. Empty Authorization.\r\n"));
		m_error = ERR_BadAuth;
		return FALSE;
	}
	SYSTEMTIME st;
	GetSystemTime(&st);
	UINT ts = SystemTime2UnixTimeStamp(st);
	LPCTSTR auth = _T("auth");
	cMD5 md5;
	CHAR authStr[100];
	_snprintf(authStr, 100, "%s%u", (LPCSTR)CT2CA(m_MD5password.c_str()), ts);


	//http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=<client-id>&v=<client-ver>&u=<user>&t=<timestamp>&a=<auth>
	TCHAR url[2000];
	_sntprintf(url, 2000, 
		_T("http://post.audioscrobbler.com/?hs=true&p=%s&c=%s&v=%s&u=%s&t=%u&a=%.32s"),
		sProtocolVer,
		sClientID,
		sClientVer,
		m_username.c_str(),
		ts,
		(LPCTSTR)CA2CT(_strlwr(md5.CalcMD5FromString(authStr))));

	TRACE(_T("About to request: '%s'\r\n"), url);
	m_state = ST_Connecting;

	std::string page;
	if (DownloadWebPage(page, m_hNet, url))
	{
		std::string delimiter = "\n";
		std::string line;
		INT pos = getToken(page, 0, delimiter, line);
		INT count = 0;
		while (pos != -1)
		{
			switch (count)
			{
			case 0:
				m_errorString = line;
				if (line == "OK")
					m_error = ERR_None;
				else if (line == "BANNED")
					m_error = ERR_Banned;
				else if (line == "BADAUTH")
					m_error = ERR_BadAuth;
				else if (line == "BADTIME")
					m_error = ERR_BadTime;
				else 
					m_error = ERR_Failed;
				break;
			case 1:
				sessionID = (LPCTSTR)CA2CT(line.c_str());
				break;
			case 2:
				nowPlayingURL = (LPCTSTR)CA2CT(line.c_str());
				break;
			case 3:
				submissionURL = (LPCTSTR)CA2CT(line.c_str());
				break;
			default:
				break;
			}
			if (m_error != ERR_None)
				break;
			count++;
			pos = getToken(page, pos, delimiter, line);
		}
		if (m_error == ERR_None)
		{
			TRACE(_T("@4 LastFMServices::HandShake. success.\r\n"));
			m_state = ST_Idle;
		}
		else
		{
			TRACE(_T("@4 LastFMServices::HandShake. fail: '%s'.\r\n"), CA2CT(GetErrorString()));
			m_state = ST_Error;
		}
	}
	else //---Download page failed
	{
		m_error = ERR_CommunicationError;
		m_state = ST_Error;
		TRACE(_T("@4 LastFMServices::HandShake. fail: Communication Error.\r\n"));
	}
	return m_state == ST_Idle;

}
示例#26
0
BOOL LastFMServices::SubmitTracks(LPCTSTR sessionID, LPCTSTR submissionURL)
{
	ASSERT(sessionID != NULL && submissionURL != NULL);
	if (!(sessionID != NULL && submissionURL != NULL))
		return FALSE;
	ASSERT(sessionID[0] != 0 && submissionURL[0]);
	if (!(sessionID[0] != 0 && submissionURL[0]))
		return FALSE;
	TRACEST(_T("LastFMServices::SubmitTracks"));
	std::string postData;
	const INT bfSize = 1000;
	postData.reserve(bfSize);
	CHAR bf[bfSize];
	CHAR utf8bf[bfSize];
	//s=<sessionID>
	//The Session ID string returned by the handshake request. Required
	_snprintf(bf, bfSize, "s=%s&", CT2CA(sessionID));
	postData = bf;
	{
		CSingleLock lock(&m_cs);
		std::list<LastFMSubmitTrack>::const_iterator it = m_jobs.begin();
		UINT i = 0;
		for (;it != m_jobs.end(); it++)
		{
			const LastFMSubmitTrack& track = *it;
			//a[0]=<artist>
			//The artist name. Required.
			ConvertString(track.artist.c_str(), utf8bf, bfSize);
			_snprintf(bf, bfSize, "a[%d]=%s&", i, utf8bf);
			bf[bfSize - 1] = 0;
			postData += bf;
			//t[0]=<track>
			//The track title. Required.
			ConvertString(track.track.c_str(), utf8bf, bfSize);
			_snprintf(bf, bfSize, "t[%d]=%s&", i, utf8bf);
			bf[bfSize - 1] = 0;
			postData += bf;
			//i[0]=<time>
			//The time the track started playing, in UNIX timestamp format. 
			//This must be in the UTC time zone, and is required.
			_snprintf(bf, bfSize, "i[%d]=%u&", i, track.unixTimeStamp);
			bf[bfSize - 1] = 0;
			postData += bf;
			//o[0]=<source>
			//The source of the track. Required
			_snprintf(bf, bfSize, "o[%d]=P&", i);
			postData += bf;
			//r[0]=<rating>
			//A single character denoting the rating of the track
			_snprintf(bf, bfSize, "r[%d]=&", i);
			bf[bfSize - 1] = 0;
			postData += bf;

			//l[0]=<secs>
			//The length of the track in seconds. Required when the source is P, optional otherwise.
			_snprintf(bf, bfSize, "l[%d]=%d&", i, track.length);
			bf[bfSize - 1] = 0;
			postData += bf;

			//b[0]=<album>
			//The album title, or an empty string if not known.
			ConvertString(track.album.c_str(), utf8bf, bfSize);
			_snprintf(bf, bfSize, "b[%d]=%s&", i, utf8bf);
			bf[bfSize - 1] = 0;
			postData += bf;

			//n[0]=<tracknumber>
			//The position of the track on the album, or an empty string if not known.
			_snprintf(bf, bfSize, "n[%d]=%d&", i, track.trackNo);
			bf[bfSize - 1] = 0;
			postData += bf;

			//m[0]=<mb-trackid>
			//The MusicBrainz Track ID, or an empty string if not known.
			_snprintf(bf, bfSize, "m[%d]=&", i);
			bf[bfSize - 1] = 0;
			postData += bf;
			i++;
		}
	}
	postData.erase(postData.size() - 1);

	TRACE(_T("@4 LastFMServices::SubmitTracks. postingData '%s'\n"), CA2CT(postData.c_str()));
	std::string page;
	if (DownloadWebPagePost(page, m_hNet, submissionURL, postData.c_str()))
	{
		m_errorString = page;
		if (strncmp(page.c_str(), "OK", 2) == 0)
		{
			//TRACE(_T("@4 LastFMServices::SubmitTracks. Track Succesfully submitted.\n"));
			m_error = ERR_None;
			m_state = ST_Idle;
		}
		else 
		{
			m_state = ST_Error;
			if (strncmp(page.c_str(), "BADSESSION", 10) == 0)
				m_error = ERR_BadSession;
			else 
				m_error = ERR_Failed;
			TRACE(_T("@1 LastFMServices::SubmitTracks. Track Failed (%d):'%s'.\n"), m_error, CA2CT(GetErrorString()));
			TRACE(_T("@1 ... postedData '%s'.\n"), CA2CT(postData.c_str()));
		}
	}
	else
	{
		m_state = ST_Error;
		m_error = ERR_CommunicationError;
		TRACE(_T("@4 LastFMServices::SubmitTracks. DownloadWebPage Failed\n"));
	}
	if (m_state == ST_Error)
		return FALSE;
	return TRUE;
}
示例#27
0
int _tmain(int argc, TCHAR* argv[])
{
    CoInitializeEx(NULL, COINIT_MULTITHREADED);

    try
    {
        if (argv[1] != 0 && argv[2] != 0 && argv[3] == 0) {
            CComPtr<IXMLDOMDocument2> xdoc;
            if (xdoc.CoCreateInstance(L"Msxml2.DOMDocument.6.0") != S_OK)
                throw MyMsgException(TEXT("Fail to create XML parser object!"));

            CComVariant strFileName;
            strFileName = SysAllocString( CT2CW(argv[1]) );
            VARIANT_BOOL bIsSucc;
            xdoc->load(strFileName, &bIsSucc);
            if (bIsSucc != VARIANT_TRUE)
                throw MyMsgException(TEXT("Fail to load input file %s!"), argv[1]);

            CComPtr<IXMLDOMNode> xDllNameNode;
            CComBSTR strXPath;
            strXPath = L"/ImportLibrary/DllName";
            xdoc->selectSingleNode(strXPath, &xDllNameNode);
            if (xDllNameNode == NULL)
                throw MyMsgException(TEXT("No DllName node!"));

            Sora::IImportLibraryBuilder* impBuilder;
            CComBSTR strDllName;
            xDllNameNode->get_text(&strDllName);
            CW2AEX<> cvtstrDllName(strDllName, CP_ACP);

            CComPtr<IXMLDOMNode> xAmd64Node;
            strXPath = L"/ImportLibrary/ArchAMD64";
            xdoc->selectSingleNode(strXPath, &xAmd64Node);
            if (xAmd64Node == NULL)
                impBuilder = Sora::CreateX86ImpLibBuilder(cvtstrDllName, cvtstrDllName);
            else
                impBuilder = Sora::CreateX64ImpLibBuilder(cvtstrDllName, cvtstrDllName);

            strXPath = L"/ImportLibrary/Import";
            CComPtr<IXMLDOMNodeList> xImportNodes;
            if (xdoc->selectNodes(strXPath, &xImportNodes) != S_OK)
                throw MyMsgException(TEXT("No Import nodes found!"));

            for(;;) {
                CComPtr<IXMLDOMNode> xImportNode;
                if (xImportNodes->nextNode(&xImportNode) != S_OK)
                    break;

                CComPtr<IXMLDOMNode> xLinkNameNode, xStubNameNode, xImportNameNode, xImportOrdinalNode;
                CComBSTR strLinkName, strStubName, strImportName, strImportOrdinal;

                strXPath = L"./LinkName";
                if (xImportNode->selectSingleNode(strXPath, &xLinkNameNode) != S_OK)
                    throw MyMsgException(TEXT("No LinkName Node!"));

                strXPath = L"./StubName";
                xImportNode->selectSingleNode(strXPath, &xStubNameNode);
                //if no stubname node found, will not generate callstub

                xLinkNameNode->get_text(&strLinkName);
                if (xStubNameNode != NULL) xStubNameNode->get_text(&strStubName);

                HRESULT selectImportName;
                HRESULT selectOrdinal;
                strXPath = L"./ImportName";
                selectImportName = xImportNode->selectSingleNode(strXPath, &xImportNameNode);
                strXPath = L"./Ordinal";
                selectOrdinal = xImportNode->selectSingleNode(strXPath, &xImportOrdinalNode);
                int nOrdinal = 0;

                if (selectImportName == S_OK || selectOrdinal == S_OK) {
                    if (selectImportName == S_OK)
                        xImportNameNode->get_text(&strImportName);

                    if (selectOrdinal == S_OK) {
                        xImportOrdinalNode->get_text(&strImportOrdinal);
                        LPCWSTR pszImportOrdinal = strImportOrdinal;

                        while(*pszImportOrdinal != 0) {
                            nOrdinal *= 10;
                            nOrdinal += *pszImportOrdinal - L'0';
                            ++pszImportOrdinal;
                        }
                    }

                    if (selectImportName == S_OK && selectOrdinal == S_OK) {
                        impBuilder->AddImportFunctionByNameWithHint(
                            CW2AEX<>(strLinkName, CP_UTF8),
                            CW2AEX<>(strStubName, CP_UTF8),
                            CW2AEX<>(strImportName, CP_UTF8),
                            nOrdinal
                        );
                    } else if (selectImportName == S_OK) {
                        impBuilder->AddImportFunctionByName(
                            CW2AEX<>(strLinkName, CP_UTF8),
                            CW2AEX<>(strStubName, CP_UTF8),
                            CW2AEX<>(strImportName, CP_UTF8)
                        );
                    } else if (selectOrdinal == S_OK) {
                        impBuilder->AddImportFunctionByOrdinal(
                            CW2AEX<>(strLinkName, CP_UTF8),
                            CW2AEX<>(strStubName, CP_UTF8),
                            nOrdinal
                        );
                    }
                } else {
                    throw MyMsgException(TEXT("No ImportName or Ordinal Node!"));
                }
            }

            //save file
            impBuilder->Build();

            int nFileSize = impBuilder->GetDataLength();
            CHandle hFile( CreateFile(argv[2], GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL) );
            if ( (HANDLE)hFile == INVALID_HANDLE_VALUE )
                throw MyMsgException(TEXT("Fail to create library File %s!"), argv[2]);

            if (SetFilePointer(hFile, nFileSize, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
                if (GetLastError() != 0)
                    throw MyMsgException(TEXT("Can't allocate disk space for output file!"));

            if (SetEndOfFile(hFile) == FALSE)
                throw MyMsgException(TEXT("Can't allocate disk space for output file!"));

            CHandle hFileMap( CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, nFileSize, 0) );
            if ((HANDLE)hFileMap == NULL)
                throw MyMsgException(TEXT("Can't map output file for writing!"));

            LPVOID pFile = MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0);
            if (pFile == 0)
                throw MyMsgException(TEXT("Can't map output file for writing!"));

            impBuilder->GetRawData((PBYTE)pFile);
            impBuilder->Dispose();
            UnmapViewOfFile(pFile);
        } else {
            fprintf(stdout, "%s",
                "Make import library from XML\n"
                "using: MakeImpLib <input xml> <output lib>\n"
                "\n"
                "XML Sample\n"
                "<ImportLibrary>\n"
                "  <!-- <ArchAMD64 /> -->\n"
                "  <!-- If no ArchAMD64 node, it creates i386 import library -->\n"
                "  <DllName>Kernel32.dll</DllName>\n"
                "  <Import>\n"
                "    <LinkName>__imp__SleepEx@8</LinkName>\n"
                "    <!-- StubName can be removed, so no call stub will generated -->\n"
                "    <StubName>_SleepEx@8</StubName>\n"
                "    <!-- For Ordinal and ImportName, you can use either or both -->\n"
                "    <!-- When use both, it's import by name and ordinal works as hint -->\n"
                "    <!-- In most case only ImportName is used, that's enough -->\n"
                "    <!-- But you can't strip both -->\n"
                "    <Ordinal>1208</Ordinal>\n"
                "    <ImportName>SleepEx</ImportName>\n"
                "  </Import>\n"
                "  <Import>\n"
                "    <LinkName>__imp__WaitForSingleObject@8</LinkName>\n"
                "    <ImportName>WaitForSingleObject</ImportName>\n"
                "  </Import>\n"
                "</ImportLibrary>\n"
                "\n"
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?> is needed "
                "for filename or function other than English letters.\n"
            );
        }
    }
    catch (MyMsgException e)
    {
        fprintf(stderr, CT2CA(e.fmt), CT2CA(e.msg));
    }

    CoUninitialize();
}
示例#28
0
bool UpdateEntity::FetchUpdate(const std::string& val) {
	{
		//解析xml判断当前动作
		tinyxml2::XMLDocument doc;
		if (tinyxml2::XML_NO_ERROR != doc.Parse(val.c_str())) {
			CString body = svy::strFormat(_T("无法解析 %s"), (LPCTSTR)CA2CT(val.c_str()));
			LOG_FILE(svy::Log::L_INFO, body);
			return false;
		}
		tinyxml2::XMLElement *root = doc.RootElement();
		tinyxml2::XMLElement *ndExt= root->FirstChildElement("EXTEND");	//扩展字段
		tinyxml2::XMLElement *body = root->FirstChildElement("BODY");
		if (!body) {
			CString body = svy::strFormat(_T("不符合规范 %s"), (LPCTSTR)CA2CT(val.c_str()));
			LOG_FILE(svy::Log::L_INFO, body);
			return false;
		}
		tinyxml2::XMLElement *response = body->FirstChildElement("RETURN");
		if (!response) {
			CString body = svy::strFormat(_T("不符合规范 %s"), (LPCTSTR)CA2CT(val.c_str()));
			LOG_FILE(svy::Log::L_INFO, body);
			return false;
		}
		if (0 != strcmp(response->Attribute("CODE"), "0000")) {
			CString body = svy::strFormat(_T("异常 %s"), (LPCTSTR)CA2CT(val.c_str()));
			LOG_FILE(svy::Log::L_INFO, body);
			return false;
		}
		tinyxml2::XMLElement *ndSJXX = body->FirstChildElement("SJXX");		//产品字段
		tinyxml2::XMLElement *product = nullptr;
		if (!ndSJXX) {
			CString body = svy::strFormat(_T("不符合规范 %s"), (LPCTSTR)CA2CT(val.c_str()));
			LOG_FILE(svy::Log::L_INFO, body);
			return false;
		}
		//找到该产品的升级node
		for (tinyxml2::XMLElement *next = ndSJXX->FirstChildElement(); next; next = next->NextSiblingElement()) {
			if (strcmp(next->Name(), "PRODUCT"))
				continue;
			CString a = (LPCTSTR)CA2CT(next->Attribute("CODE"));
			if (a != mExe_.mVer_.mProductCode_)
				continue;
			product = next;
			break;
		}
		if (product==nullptr) {
			CString body = svy::strFormat(_T("缺少对应产品 %s"), (LPCTSTR)CA2CT(val.c_str()));
			LOG_FILE(svy::Log::L_INFO, body);
			return false;
		}
		//存第一个版本升级包
		std::shared_ptr<UP_PACK> info = std::make_shared<UP_PACK>();
		info->url = CA2CT(product->Attribute("UPDATEURL"));
		if (info->url.IsEmpty()) {
			info->url = CA2CT(product->Attribute("OTHERURL"));
			long dot = info->url.Find(',');
			if (dot != -1 && dot > 0)
				info->url = info->url.Mid(0, dot);
		}
		info->ver = CA2CT(product->Attribute("END_VERSION"));
		CString bNeedUp = CA2CT(product->Attribute("HAS_UPDATE"));
		bNeedUp.Trim();
		if (0 == bNeedUp.CompareNoCase(_T("0"))) {
			LOG_FILE(svy::Log::L_INFO,(LPCTSTR)CA2CT(val.c_str()));
			return true;
		}
		if ( !info->ver.IsEmpty() || !info->url.IsEmpty()) {
			mUpData_.push_back(info);
		}
		//存其他版本升级包
		tinyxml2::XMLElement *packs = product->FirstChildElement("GREATERVERSION");
		for (tinyxml2::XMLElement *next = packs; next; next = next->NextSiblingElement()) {
			std::shared_ptr<UP_PACK> info = std::make_shared<UP_PACK>();
			info->url = CA2CT(next->Attribute("UPDATEURL"));
			if (info->url.IsEmpty()) {
				info->url = CA2CT(next->Attribute("OTHERURL"));
				long dot = info->url.Find(',');
				if (dot != -1 && dot > 0)
					info->url = info->url.Mid(0, dot);
			}
			info->ver = CA2CT(next->Attribute("END_VERSION"));
			if (!info->ver.IsEmpty() || !info->url.IsEmpty()) {
				mUpData_.push_back(info);
			}
		}
	}
	std::vector<CString>	badVers;	//异常版本队列,可能是下载错误或写入错误也可能是挂包错误导致
	size_t nCount = mUpData_.count();
	for (size_t nI = 0; nI < nCount; nI++) {
		std::shared_ptr<UP_PACK> info = mUpData_[nI];
		//生成文件
		CString path;
		long	hCode = 0;
		{
			path.Format(_T("%s_%s.zip"),svy::PathGetFileName(mExe_.getPathFile()), info->ver);
			FILE *f = nullptr;
			errno_t err;
			if ((err = fopen_s(&f, CT2CA(path), "wb")) != 0) {
				LOG_FILE(svy::Log::L_ERROR, svy::strFormat(_T("file open filed %d"), err));
				return false;
			}
			//下载数据
			svy::CHttpClient	http;
			http.BodySaveFile(f);
			http.PerformParam(info->url);
			hCode = svy::CHttpClient::PerformUrl(http.GetCURL());
			fclose(f);
			f = nullptr;
		}
		if (hCode != 200) {
			//异常文件
			LOG_FILE(svy::Log::L_ERROR,info->url);
			::DeleteFile(path);
			badVers.push_back(info->ver);
			continue;
		}
		//需要解压缩
		info->step = Step::ExtractFiles;
		info->path = path;
	}
	//移除异常的数据
	nCount = badVers.size();
	for (size_t nI = 0; nI < nCount; nI++) {
		CString key = badVers[nI];
		std::shared_ptr<UP_PACK> pack = mUpData_.getBegin();
		while (pack=mUpData_.getNext()) {
			if (key == pack->ver) {
				mUpData_.erase(pack);
				break;
			}
		}		
	}
	//处理升级包
	HandleUpdatePack();
	return true;
}
示例#29
0
bool CGPSgeneric::openPort(CGPSport &select)
{
#if USE_GARXFACE == 1
#if GARXFACE_HAS_SCOPE_ISSUES != 1
    GarXface4::GpsComPortDevice comDevice;
    GarXface4::GpsUsbDevice usbDevice;
#endif
#endif

    switch (select.getType()) {
#if USE_RPNMEA == 1
    case CGPSPortTypesSerialNMEA:
        if (garNMEA.setGarminPort(select.getPortNameHR()) &&
                garNMEA.openGarminPort())
        {
            // @@@ we should really do a test read here to validate this is an NMEA device ...
            isopen=true;
            curPort=select;
            return true;
        }
        isopen=false;
        return false;
        break;
#endif
#if USE_GARXFACE == 1
    case CGPSPortTypesSerialGarXface:
        // I am tempted to just do nothing *here* and return trune
        // then do the open close for each read ...

        if (garGPS.IsOpen()) {
            garGPS.Close();
            isopen=false;
        }


        try
        {
            const char *portname=CT2CA(select.getPortName());
            comDevice.SetPortName(portname);
            garGPS.Open(&comDevice);
        }
        catch (GarXface4::Exceptions::GxException)
        {
            // Something went wrong ... bail
            isopen=false;
            return false;
        }
        isopen=true;
        curPort=select;
        return true;
        break;

    case CGPSPortTypesUSBGarXface:
        // I am tempted to just do nothing *here* and return trune
        // then do the open close for each read ...

        if (garGPS.IsOpen()) {
            garGPS.Close();
            isopen=false;
        }

        try
        {
            const char *portname=CT2CA(select.getPortName());
            usbDevice.SetDeviceName(portname);
            garGPS.Open(&usbDevice);
        }
        catch (GarXface4::Exceptions::GxException)
        {
            // Something went wrong ... bail
            isopen=false;
            return false;
        }
        isopen=true;
        curPort=select;
        return true;
        break;
#endif
    default:
        return false;

    }

    return true;
}
// Write C code for corresponding to the feed forward network into a given file.
void MultipleBackPropagation::GenerateCCode(OutputFile & f, VariablesData & trainVariables, BOOL inputLayerIsConnectedWithOutputLayer, BOOL spaceInputLayerIsConnectedWithOutputLayer) {
	CString s;

	CString MBPVersion;
	MBPVersion.LoadString(IDS_VERSION);

	f.WriteLine("/**");
	f.WriteLine(_TEXT(" Generated by ") + MBPVersion);
	f.WriteLine(" Multiple Back-Propagation can be freely obtained at http://dit.ipg.pt/MBP");
	f.WriteLine("*/\n");

	f.WriteLine("#include <math.h>");
	
	f.WriteLine("/**");
	s.Format(_TEXT(" inputs  - should be an array of %d element(s), containing the network input(s)."), inputs);

	bool hasMissingValues = false;
	for(int i = 0; i < inputs; i++) {
		if (trainVariables.HasMissingValues(i)) {
			s += " Inputs with NaN value are considered missing values.";
			hasMissingValues = true;
			break;
		}
	}

	f.WriteLine(s);
		
	s.Format(_TEXT(" outputs - should be an array of %d element(s), that will contain the network output(s)."), outputs);
	f.WriteLine(s);
	s = " Note : The array inputs will also be changed.";
	if (!hasMissingValues) s += "Its values will be rescaled between -1 and 1.";
	s += "\n*/";
	f.WriteLine(s);

	s = f.GetFileName();
	int p = s.Find('.');
	if (p != -1) s = s.Left(p);
	f.WriteLine(_TEXT("void ") +  s + _TEXT("(double * inputs, double * outputs) {"));

	f.WriteString("\tdouble mainWeights[] = {");
	SaveWeights(f, ", ");
	f.WriteLine("};");
	f.WriteLine("\tdouble * mw = mainWeights;");
	if (hasMissingValues) f.WriteLine("\tdouble b;");

	if (!spaceNetwork.IsNull()) {
		f.WriteString("\tdouble spaceWeights[] = {");
		spaceNetwork->SaveWeights(f, ", ");
		f.WriteLine("};");
		f.WriteLine("\tdouble * sw = spaceWeights;");
		s.Format(_TEXT("\tdouble mk[%d];"), spaceNetwork->Outputs());
		f.WriteLine(s);
		f.WriteLine("\tdouble *m = mk;");
		
		if (hasMissingValues) {
			s.Format(L"\tdouble spaceInputs[%d];", inputs);
			f.WriteLine(s);
		}
	}

	int numberLayers = layers.Lenght();

	for (int l = 1; l < numberLayers - 1; l++) {
		s.Format(L"\tdouble hiddenLayer%doutputs[%d];", l, layers.Element(l)->neurons.Lenght());
		f.WriteLine(s);
	}

	int numberSpaceLayers = (spaceNetwork.IsNull()) ? 0 : spaceNetwork->layers.Lenght();

	for (int l = 1; l < numberSpaceLayers - 1; l++) {
		s.Format(_TEXT("\tdouble spaceHiddenLayer%doutputs[%d];"), l, spaceNetwork->layers.Element(l)->neurons.Lenght());
		f.WriteLine(s);
	}

	f.WriteLine("\tint c;");

	f.WriteString("\n");

	// input variables will be rescaled between -1 and 1
	if (trainVariables.Number() == inputs + outputs) {
		for (int i = 0; i < inputs; i++) { 
			double min = trainVariables.Minimum(i);
			double max = trainVariables.Maximum(i);

			if (trainVariables.HasMissingValues(i)) {
				s.Format(L"\tif(inputs[%d] == inputs[%d]) { /* compiler must have support for NaN numbers */\n\t", i, i);
				f.WriteString(s);
			}

			if (min != max) {
				s.Format(L"\tinputs[%d] = -1.0 + (inputs[%d] - %1.15f) / %1.15f;", i, i, min, (max - min)/2);				
			} else {
				s.Format(L"\tinputs[%d] = inputs[%d] / %1.15f; /* WARNING: During the training this variable remain always constant */", i, i, max);
			}
			f.WriteLine(s);

			if (hasMissingValues && !spaceNetwork.IsNull()) {
				if (trainVariables.HasMissingValues(i)) f.WriteString("\t");
				s.Format(L"\tspaceInputs[%d] = inputs[%d];", i, i);
				f.WriteLine(s);
			}

			if (trainVariables.HasMissingValues(i)) {
				if (!spaceNetwork.IsNull()) {
					f.WriteLine("\t\tb = *sw++;");
					s.Format(L"\t\tspaceInputs[%d] = tanh(b + spaceInputs[%d] * *sw++);", i, i);
					f.WriteLine(s);
				}

				f.WriteLine("\t\tb = *mw++;");
				s.Format(L"\t\tinputs[%d] = tanh(b + inputs[%d] * *mw++);", i, i);
				f.WriteLine(s);
				f.WriteLine("\t} else {");
				s.Format(L"\t\tspaceInputs[%d] = inputs[%d] = 0.0;", i, i);
				f.WriteLine(s);
				f.WriteLine("\t}");
			}
		}
	}

	// space network
	for (int l = 1; l < numberSpaceLayers; l++) {
		List<Neuron> * neurons = &(spaceNetwork->layers.Element(l)->neurons);

		int nn = 0;
		for(NeuronWithInputConnections * n = dynamic_cast<NeuronWithInputConnections *>(neurons->First()); n != NULL; n = dynamic_cast<NeuronWithInputConnections *>(neurons->Next())) {
			CString aux;

			if (l == numberSpaceLayers -1) {
				aux.Format(_TEXT("mk[%d]"), nn);
			} else {
				aux.Format(_TEXT("spaceHiddenLayer%doutputs[%d]"), l, nn);
			}

			f.WriteString("\t");
			f.WriteString(aux);
			f.WriteLine(" = *sw++;");

			int numberInputsFromLastLayer = n->inputs.Lenght() - 1; // - bias
			if (spaceInputLayerIsConnectedWithOutputLayer  && l == numberSpaceLayers -1) numberInputsFromLastLayer -= inputs;

			s.Format(_TEXT("\tfor(c = 0; c < %d; c++) "), numberInputsFromLastLayer);
			f.WriteString(s);
			f.WriteString(aux);
			f.WriteString(" += *sw++ * ");

			if (l == 1) {
				s = (hasMissingValues) ? "spaceI" : "i";
				s+= "nputs[c];";
			} else {
				s.Format(_TEXT("spaceHiddenLayer%doutputs[c];"), l-1);
			}
			f.WriteLine(s);

			if (spaceInputLayerIsConnectedWithOutputLayer  && l == numberSpaceLayers -1) {
				s.Format(_TEXT("\tfor(c = 0; c < %d; c++) "), inputs);
				f.WriteString(s);
				f.WriteLine(aux + L" += *sw++ * " + ((hasMissingValues) ? "spaceI" : "i") + "nputs[c];");
			}

			WriteActivationFunctionCCode(f, n, CT2CA(aux));

			nn++;
		}
	}

	// main network

	for (int l = 1; l < numberLayers; l++) {
		List<Neuron> * neurons = &(layers.Element(l)->neurons);

		int nn = 0;
		for(NeuronWithInputConnections * n = dynamic_cast<NeuronWithInputConnections *>(neurons->First()); n != NULL; n = dynamic_cast<NeuronWithInputConnections *>(neurons->Next())) {
			CString aux;

			if (l == numberLayers -1) {
				aux.Format(_TEXT("outputs[%d]"), nn);
			} else {
				aux.Format(_TEXT("hiddenLayer%doutputs[%d]"), l, nn);
			}

			f.WriteString("\t");
			f.WriteString(aux);
			f.WriteLine(" = *mw++;");
			
			int numberInputsFromLastLayer = n->inputs.Lenght() - 1; // - bias
			if (inputLayerIsConnectedWithOutputLayer && l == numberLayers -1) numberInputsFromLastLayer -= inputs;

			s.Format(_TEXT("\tfor(c = 0; c < %d; c++) "), numberInputsFromLastLayer);
			f.WriteString(s);
			f.WriteString(aux);
			f.WriteString(" += *mw++ * ");

			if (l == 1) {
				s = "inputs[c];";
			} else {
				s.Format(_TEXT("hiddenLayer%doutputs[c];"), l-1);
			}

			f.WriteLine(s);

			if (inputLayerIsConnectedWithOutputLayer && l == numberLayers -1) {
				s.Format(_TEXT("\tfor(c = 0; c < %d; c++) "), inputs);
				f.WriteString(s);
				f.WriteLine(aux + _TEXT(" += *mw++ * inputs[c];"));
			}

			WriteActivationFunctionCCode(f, n, CT2CA(aux));

			if (!spaceNetwork.IsNull() && nn < neuronsWithSelectiveActivation[l]) {
				f.WriteString("\t");
				f.WriteString(aux);
				f.WriteLine(" *= *m++;");
			}

			nn++;
		}
	}

	// Rescale the outputs
	if (trainVariables.Number() == inputs + outputs) {
		for (int o = 0; o < outputs; o++) {
			int outVar = o + inputs;

			double min = trainVariables.Minimum(outVar);
			double max = trainVariables.Maximum(outVar);
			double nmin = trainVariables.newMinimum[outVar];

			s.Format(_TEXT("\toutputs[%d] = %1.15f + (outputs[%d] - %f) * %1.15f;"), o, min, o, nmin, (max - min) / (1.0 - nmin));
			f.WriteLine(s);
		}
	}

	f.WriteLine("}");
}