Esempio n. 1
0
HINSTANCE CVSFilterApp::LoadAppLangResourceDLL()
{
    CString fn;
    fn.ReleaseBufferSetLength(::GetModuleFileName(m_hInstance, fn.GetBuffer(MAX_PATH), MAX_PATH));
    fn = fn.Mid(fn.ReverseFind('\\') + 1);
    fn = fn.Left(fn.ReverseFind('.') + 1);
    fn = fn + _T("lang");
    return ::LoadLibrary(fn);
}
Esempio n. 2
0
CString Utils::GetAppFullPath(void)
{
	static CString s_appFullPath;
	if (s_appFullPath.IsEmpty())
	{
		s_appFullPath.ReleaseBufferSetLength(::GetModuleFileName(NULL, s_appFullPath.GetBuffer(MAX_PATH), MAX_PATH));
	}
	return s_appFullPath.GetString();
}
Esempio n. 3
0
int MoveDirectory(CString ExistingDirectoryPath, CString NewDirectoryInfoPath)
{
	if (ExistingDirectoryPath[ExistingDirectoryPath.GetLength() - 1] == L'\\')
		ExistingDirectoryPath.ReleaseBufferSetLength(ExistingDirectoryPath.GetLength() - 1);

	ExistingDirectoryPath.AppendChar(NULL);

	if (NewDirectoryInfoPath[NewDirectoryInfoPath.GetLength() - 1] == L'\\')
		NewDirectoryInfoPath.ReleaseBufferSetLength(NewDirectoryInfoPath.GetLength() - 1);


	SHFILEOPSTRUCT FileOp = { 0 };
	FileOp.fFlags = FOF_NO_UI;
	FileOp.pFrom = ExistingDirectoryPath;
	FileOp.pTo = NewDirectoryInfoPath;
	FileOp.wFunc = FO_MOVE;
	return SHFileOperation(&FileOp);
}
Esempio n. 4
0
CString Utils::CLogger::FormatString( LPCTSTR pstrFormat, ... )
{
	int nSize = 0;
	CString strTemp;
	va_list args;
	va_start(args, pstrFormat);
	nSize = _vsntprintf_s( strTemp.GetBufferSetLength(MAX_LOG_SIZE),MAX_LOG_SIZE -1, MAX_LOG_SIZE-2, pstrFormat, args);
	strTemp.ReleaseBufferSetLength(nSize);
	va_end(args);
	return strTemp;
}
CString getPathToCurrentExeContainer()
{
	// Get the current path that we are running from
	CString fullPath;
	DWORD count = ::GetModuleFileName(nullptr, fullPath.GetBuffer(MAX_PATH), MAX_PATH);
	fullPath.ReleaseBufferSetLength(count);

	LPWSTR buffer = fullPath.GetBuffer();
	LPWSTR newPath = ::PathFindFileName(buffer);
	if (newPath && newPath != buffer)
	{
		fullPath.ReleaseBufferSetLength((newPath - buffer));
	}
	else
	{
		fullPath.ReleaseBuffer();
	}

	return fullPath;
}
Esempio n. 6
0
void Utils::CLogger::Log( LogLevel level, LPCTSTR pstrFormat, ... )
{
	log4cplus::Logger rootLogger = log4cplus::Logger::getRoot();
	if ( rootLogger.isEnabledFor(level))
	{
		int nSize = 0;
		CString strTemp;
		va_list args;
		va_start(args, pstrFormat);
		nSize = _vsntprintf_s( strTemp.GetBufferSetLength(MAX_LOG_SIZE),MAX_LOG_SIZE -1, MAX_LOG_SIZE-2, pstrFormat, args);
		strTemp.ReleaseBufferSetLength(nSize);
		va_end(args);
		rootLogger.forcedLog(level, strTemp.GetString());
	}
	CleanThread();
}
Esempio n. 7
0
void Utils::CLogger::FatalBy( LPCTSTR lpInstance,LPCTSTR pstrFormat, ... )
{
	log4cplus::Logger logger = log4cplus::Logger::getInstance(lpInstance);
	if ( logger.isEnabledFor(FATAL_LOG_LEVEL))
	{
		int nSize = 0;
		CString strTemp;
		va_list args;
		va_start(args, pstrFormat);
		nSize = _vsntprintf_s( strTemp.GetBufferSetLength(MAX_LOG_SIZE),MAX_LOG_SIZE -1, MAX_LOG_SIZE-2, pstrFormat, args);
		strTemp.ReleaseBufferSetLength(nSize);
		va_end(args);
		logger.forcedLog(FATAL_LOG_LEVEL, strTemp.GetString());
	}
	CleanThread();
}
Esempio n. 8
0
CString Utils::GetAppPath(void)
{
	static CString s_appPath;
	if (s_appPath.IsEmpty())
	{
		s_appPath=GetAppFullPath();
		if (s_appPath.GetLength()>0)
		{
			int pos = s_appPath.ReverseFind(_T('\\'));
			if (pos>=0)
			{
				s_appPath.ReleaseBufferSetLength(pos+1);
			}
		}
	}
	return s_appPath;
}
// ----------------------------------------------------------------------------
//
void SimpleJsonParser::parse( FILE* fp )
{
    // These files are not that big- just read into a buffer and treat as a LPCSTR
    CString json;

    fseek( fp, 0L, SEEK_END );
    long size = ftell( fp ) * 2;        // * 2 for newline expansion
    fseek( fp, 0L, SEEK_SET );

    LPSTR buffer = json.GetBufferSetLength( size );

    size = fread( buffer, 1, size, fp );

    json.ReleaseBufferSetLength( size );

    parse( json );
}
Esempio n. 10
0
static CString CreateString( const WORD *data )
{
	int len=*data;
	data++;
	if (len==0) return NULL;

	CString str;
	wchar_t *ptr=str.GetBuffer(len);
	if (ptr)
	{
		memcpy(ptr,data,len*2);
		ptr[len]=0;
		str.ReleaseBufferSetLength(len);
	}

	return str;
}
Esempio n. 11
0
// Use sparingly!
// Dump string buffer in the log
void
LogAnalysis::BareStringLog(const char* p_buffer,int p_length)
{
  // Multi threaded protection
  AutoCritSec lock(&m_lock);

  CString buffer;
  char* pointer = buffer.GetBufferSetLength(p_length + 1);
  memcpy_s(pointer,p_length+1,p_buffer,p_length);
  pointer[p_length] = 0;
  buffer.ReleaseBufferSetLength(p_length);

  // Test for newline
  if(buffer.Right(1) != "\n")
  {
    buffer += "\n";
  }

  // Keep the line
  m_list.push_back(buffer);
}
Esempio n. 12
0
LPCTSTR GetDefaultCookieFile()
{
	static TCHAR c_szCookieFile[MAX_PATH] = {0};

	if(c_szCookieFile[0] == 0)
	{
		CString strName;
		LPTSTR lpszName = strName.GetBuffer(MAX_PATH);

		DWORD rs = ::GetModuleFileName(nullptr, lpszName, MAX_PATH);
		ASSERT(rs > 0 && rs < MAX_PATH);

		int iPos = strName.ReverseFind('.');
		ASSERT(iPos == (int)(rs - 4));

		strName.ReleaseBufferSetLength(iPos + 1);
		strName.Append(_T("cki"));

		lstrcpy(c_szCookieFile, strName);
	}

	return c_szCookieFile;
}
Esempio n. 13
0
//----------------------------------------------------------------------------
//  ResolveModuleID
//  @TODO: The handling of file extensions might have to be changed in
//         future.
HRESULT CMagpieApplication::ResolveModuleID(
  CMagpieModule * pSrcModule,
  LPCOLESTR       lpszModuleID,
  CString       & sAbsoluteModuleID)
{
  if (!lpszModuleID || !_tcslen(lpszModuleID))
  {
    // empty id? no way!
    return E_FAIL;
  }

  // if ID is already absolute...
  if (lpszModuleID[0] != _T('.'))
  {
    // ...return it as it is...
    sAbsoluteModuleID = lpszModuleID;
    // ...but strip off .js file extension if exists.
    if (sAbsoluteModuleID.Right(3) == _T(".js"))
    {
      sAbsoluteModuleID.ReleaseBufferSetLength(
        sAbsoluteModuleID.GetLength() - 3);
    }
    return S_OK;
  }

  HRESULT hr = E_FAIL;
  CString sSrcModuleID;
  // if no source module is given id will be
  // relative to root (means sSrcModuleID will be empty)
  if (pSrcModule)
  {
    pSrcModule->GetID(sSrcModuleID);
  }

  CAtlList<CString> srcIdList, idList;

  SplitString(lpszModuleID, _T("/"), idList);
  SplitString(sSrcModuleID, _T("/"), srcIdList);
  if (!srcIdList.IsEmpty())
  {
    // Remove last part, it is the "filename" part of the srcID.
    // dstID should be relative to the "folder" of srcID
    srcIdList.RemoveTailNoReturn();
  }

  // Adjust the srcIdList according to the parts in idList.
  // Any './' will change nothing.
  // Any '../' will pop off the tail of srcIdList.
  // Anything else will be appended to srcIdList.
  POSITION pos = idList.GetHeadPosition();
  while(pos)
  {
    const CString & cur = idList.GetNext(pos);
    if (cur == _T("."))
    {
      // current folder, do nothing
      continue;
    }
    if (cur == _T(".."))
    {
      // one up, remove tail from srcIdList
      if (srcIdList.IsEmpty())
      {
        // Oops, already top level.
        // Return an error.
        return E_FAIL;
      }
      srcIdList.RemoveTailNoReturn();
    }
    else
    {
      // append
      srcIdList.AddTail(cur);
    }
  }

  // Now compose final id.
  // sAbsoluteModuleID does NOT get emptied before, allowing to pass in
  // a parent path.
  pos = srcIdList.GetHeadPosition();
  while(pos)
  {
    sAbsoluteModuleID.Append(idList.GetNext(pos));
    if (pos)
    {
      sAbsoluteModuleID.AppendChar(_T('/'));
    }
  }

  // strip off .js file extension if exists.
  if (sAbsoluteModuleID.Right(3) == _T(".js"))
  {
    sAbsoluteModuleID.ReleaseBufferSetLength(
      sAbsoluteModuleID.GetLength() - 3);
  }

  return S_OK;
}
Esempio n. 14
0
int wmain(int argc, wchar_t* argv[])
{
    // Initialize COM and deinitialize when we go out of scope
    HRESULT hrCoInit = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    shared_ptr<HRESULT> spCoInit(&hrCoInit, [](const HRESULT* hrCom) -> void { if (SUCCEEDED(*hrCom)) { ::CoUninitialize(); } });
    {
        // Set a close handler to shutdown the chrome instance we launch
        ::SetConsoleCtrlHandler(OnClose, TRUE);

        // Launch chrome
        {
            CString chromePath;

            // Find the chrome install location via the registry
            CString keyPath = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe";

            CRegKey regKey;

            // First see if we can find where Chrome is installed from the registry. This will only succeed if Chrome is installed for all users
            if (regKey.Open(HKEY_LOCAL_MACHINE, keyPath, KEY_READ) == ERROR_SUCCESS)
            {
                ULONG bufferSize = MAX_PATH;
                CString path;
                LRESULT result = regKey.QueryStringValue(nullptr, path.GetBufferSetLength(bufferSize), &bufferSize);
                path.ReleaseBufferSetLength(bufferSize);
                if (result == ERROR_SUCCESS)
                {
                    chromePath = path;
                }
            }

            if (chromePath.GetLength() == 0)
            {
                // If Chrome is only installed for the current user, look in \AppData\Local\Google\Chrome\Application\ for Chrome.exe
                CString appPath;
                ::SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appPath.GetBuffer(MAX_PATH + 1));
                appPath.ReleaseBuffer();
                chromePath = appPath + L"\\Google\\Chrome\\Application\\chrome.exe";
            }

            // Get a temp location
            CString temp;
            Helpers::ExpandEnvironmentString(L"%Temp%", temp);

            // Set arguments for the chrome that we launch
            CString arguments;
            arguments.Format(L"about:blank --remote-debugging-port=9223 --window-size=0,0 --silent-launch --no-first-run --no-default-browser-check --user-data-dir=\"%s\"", temp);

            // Launch the process
            STARTUPINFO si = { 0 };
            PROCESS_INFORMATION pi = { 0 };
            si.cb = sizeof(si);
            si.wShowWindow = SW_MINIMIZE;

            BOOL result = ::CreateProcess(
                chromePath,
                arguments.GetBuffer(),
                nullptr,
                nullptr,
                FALSE,
                0,
                nullptr,
                temp,
                &si,
                &pi);
            arguments.ReleaseBuffer();

            if (result)
            {
                // Store the handles
                CHandle hThread(pi.hThread);
                hChromeProcess.Attach(pi.hProcess);
                DWORD waitResult = ::WaitForInputIdle(hChromeProcess, 30000);
            }
            else
            {
                std::cerr << "Could not open Chrome. Please ensure that Chrome is installed." << std::endl;
                system("pause");
                return -1;
            }
        }
        
        // Get the current path that we are running from
        CString fullPath;
        DWORD count = ::GetModuleFileName(nullptr, fullPath.GetBuffer(MAX_PATH), MAX_PATH);
        fullPath.ReleaseBufferSetLength(count);

        LPWSTR buffer = fullPath.GetBuffer();
        LPWSTR newPath = ::PathFindFileName(buffer);
        if (newPath && newPath != buffer)
        {
            fullPath.ReleaseBufferSetLength((newPath - buffer));
        }
        else
        {
            fullPath.ReleaseBuffer();
        }

        // Load the proxy server
        IEDiagnosticsAdapter proxy(fullPath);

        // Create a message pump
        MSG msg;
        ::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

        // Thread message loop
        BOOL getMessageRet;
        while ((getMessageRet = ::GetMessage(&msg, NULL, 0, 0)) != 0)
        {
            if (getMessageRet != -1)
            {
                ::TranslateMessage(&msg);
                ::DispatchMessage(&msg);
            }
        }

        // Leave the window open so we can read the log file
        wcout << endl << L"Press [ENTER] to exit." << endl;
        cin.ignore();
    }

    return 0;
}
HRESULT IEDiagnosticsAdapter::PopulateIEInstances()
{
    map<HWND, IEInstance> current;

    // Enumerate all the windows looking for instances of Internet Explorer
    Helpers::EnumWindowsHelper([&](HWND hwndTop) -> BOOL
    {
        Helpers::EnumChildWindowsHelper(hwndTop, [&](HWND hwnd) -> BOOL
        {
            if (Helpers::IsWindowClass(hwnd, L"Internet Explorer_Server"))
            {
                DWORD processId;
                ::GetWindowThreadProcessId(hwnd, &processId);

                CComPtr<IHTMLDocument2> spDocument;
                HRESULT hr = Helpers::GetDocumentFromHwnd(hwnd, spDocument);
                if (hr == S_OK)
                {
                    UUID guid;
                    if (m_instances.find(hwnd) != m_instances.end())
                    {
                        if (!m_instances[hwnd].isConnected)
                        {
                            guid = m_instances[hwnd].guid;
                        }
                        else
                        {
                            current[hwnd] = m_instances[hwnd];
                            return TRUE;
                        }
                    }
                    else
                    {
                        ::UuidCreate(&guid);
                    }

                    CComBSTR url;
                    hr = spDocument->get_URL(&url);
                    if (hr != S_OK)
                    {
                        url = L"unknown";
                    }

                    CComBSTR title;
                    hr = spDocument->get_title(&title);
                    if (hr != S_OK)
                    {
                        title = L"";
                    }

                    CString filePath;
                    CHandle handle(::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId));
                    if (handle)
                    {
                        DWORD bufferSize = MAX_PATH;
                        DWORD count = ::GetModuleFileNameEx(handle, nullptr, filePath.GetBuffer(bufferSize), bufferSize);
                        filePath.ReleaseBufferSetLength(count);
                    }

                    current[hwnd] = IEInstance(guid, processId, hwnd, url, title, filePath);
                }
            }

            return TRUE;
        });

        return TRUE;
    });

    m_instances.clear();
    m_instances = current;

    return S_OK;
}
int wmain(int argc, wchar_t* argv[])
{
	//::MessageBox(NULL, L"Stop here", L"STOP!", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON3);

	std:cout << "Edge Diagnostics Adapter" << std::endl;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "Prints this help text.")
		("launch,l", po::value<string>(), "Launches Edge. Optionally at the URL specified in the value")
		("killall,k", "Kills all running Edge processes.")
		("chrome,c", "Launches Crhome in the background to serve the Chrome Developer Tools frontend.")
		("port,p", po::value<string>(), "The port number to listen on. Default is 9222.");

	po::variables_map vm;
	try
	{
		po::store(po::parse_command_line(argc, argv, desc), vm);
	}
	catch (po::error& e)
	{
		std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
		std::cerr << desc << std::endl;
		return E_FAIL;
	}

	if (vm.count("help"))
	{
		std::cout << desc << std::endl;
		return S_OK;
	}


	// Initialize COM and deinitialize when we go out of scope
	HRESULT hrCoInit = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

	shared_ptr<HRESULT> spCoInit(&hrCoInit, [](const HRESULT* hrCom) -> void { if (SUCCEEDED(*hrCom)) { ::CoUninitialize(); } });
	{
		// Set a close handler to shutdown the chrome instance we launch
		::SetConsoleCtrlHandler(OnClose, TRUE);

		// Launch chrome
		if (vm.count("chrome"))
		{
			CString chromePath;

			// Find the chrome install location via the registry
			CString keyPath = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe";

			CRegKey regKey;

			// First see if we can find where Chrome is installed from the registry. This will only succeed if Chrome is installed for all users
			if (regKey.Open(HKEY_LOCAL_MACHINE, keyPath, KEY_READ) == ERROR_SUCCESS)
			{
				ULONG bufferSize = MAX_PATH;
				CString path;
				LRESULT result = regKey.QueryStringValue(nullptr, path.GetBufferSetLength(bufferSize), &bufferSize);
				path.ReleaseBufferSetLength(bufferSize);
				if (result == ERROR_SUCCESS)
				{
					chromePath = path;
				}
			}

			if (chromePath.GetLength() == 0)
			{
				// If Chrome is only installed for the current user, look in \AppData\Local\Google\Chrome\Application\ for Chrome.exe
				CString appPath;
				::SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appPath.GetBuffer(MAX_PATH + 1));
				appPath.ReleaseBuffer();
				chromePath = appPath + L"\\Google\\Chrome\\Application\\chrome.exe";
			}

			// Get a temp location
			CString temp;
			Helpers::ExpandEnvironmentString(L"%Temp%", temp);

			// Set arguments for the chrome that we launch
			CString arguments;
			arguments.Format(L"about:blank --remote-debugging-port=9223 --window-size=0,0 --silent-launch --no-first-run --no-default-browser-check --user-data-dir=\"%s\"", temp);

			// Launch the process
			STARTUPINFO si = { 0 };
			PROCESS_INFORMATION pi = { 0 };
			si.cb = sizeof(si);
			si.wShowWindow = SW_MINIMIZE;

			BOOL result = ::CreateProcess(
				chromePath,
				arguments.GetBuffer(),
				nullptr,
				nullptr,
				FALSE,
				0,
				nullptr,
				temp,
				&si,
				&pi);
			arguments.ReleaseBuffer();

			if (result)
			{
				// Store the handles
				CHandle hThread(pi.hThread);
				hChromeProcess.Attach(pi.hProcess);
				DWORD waitResult = ::WaitForInputIdle(hChromeProcess, 30000);
			}
			else
			{
				std::cerr << "Could not open Chrome. Please ensure that Chrome is installed." << std::endl;
				system("pause");
				return -1;
			}
		}

		// Kill all Edge instances if their is an aegument /killall
		if (vm.count("killall"))
		{
			//killAllProcessByExe(L"MicrosoftEdgeCP.exe");
			Helpers::KillAllProcessByExe(L"MicrosoftEdge.exe");
		}

		// Launch Edge if their is an argument set /launch:<url>
		if (vm.count("launch"))
		{
			CString url(vm["launch"].as<string>().c_str());
			if (url.GetLength() == 0)
			{
				url = L"https://www.bing.com";
			}

			HRESULT hr = Helpers::OpenUrlInMicrosoftEdge(url);

			if (FAILED(hr))
			{
				std::cout << L"Failed to launch Microsoft Edge";
			}
		}

		string port = EdgeDiagnosticsAdapter::s_Default_Port;
		if (vm.count("port"))
		{
			port = vm["port"].as<string>();
		}

		// We don't care if this fails as the developer can set it manually.
		setSecurityACLs();

		// We don't care if this fails or not as maybe the developer wants to do something that won't hit the PLM. In case errors went to the console.
		setEdgeForDebugging(true);

		// Load the proxy server
		EdgeDiagnosticsAdapter proxy(getPathToCurrentExeContainer(), port);

		if (proxy.IsServerRunning)
		{

			// Create a message pump
			MSG msg;
			::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

			// Thread message loop
			BOOL getMessageRet;
			while ((getMessageRet = ::GetMessage(&msg, NULL, 0, 0)) != 0)
			{
				if (getMessageRet != -1)
				{
					::TranslateMessage(&msg);
					::DispatchMessage(&msg);
				}
			}

			// Leave the window open so we can read the log file
			wcout << endl << L"Press [ENTER] to exit." << endl;
			cin.ignore();
		}
		else
		{
			wcout << L"Error starting. Quiting.";
			return E_FAIL;
		}
	}

	return S_OK;
}