int ProcessHDDIsInActive(std::wstring& disk)
{
	WCHAR letter[SIZELETTERWCHAR] = {0};
	CreateLetterFromVolume(disk.c_str(), letter);
	int result = 0;
	map<wstring, wstring>::iterator it = ListMutex->find(wstring(letter));
	map<wstring, wstring>::iterator itTimer;
	if (it != ListMutex->end()){
		HANDLE waitTimer = INVALID_HANDLE_VALUE;

		EnterCriticalSection(CriticalSection);	
			itTimer = ListTimers->find(wstring(letter));
	    LeaveCriticalSection(CriticalSection);	

		if(itTimer != ListTimers->end())
		{
			waitTimer = OpenWaitableTimer(TIMER_ALL_ACCESS, FALSE, itTimer->second.c_str());
			if(waitTimer != INVALID_HANDLE_VALUE)
				CancelWaitableTimer(waitTimer);
			ListTimers->erase(itTimer);
			CloseHandle(waitTimer);
		}
		ListMutex->erase(it);
		map<wstring, Operations>::iterator itOps = ListCurrentBusyDisks->find(wstring(letter));
		if(itOps != ListCurrentBusyDisks->end())
			ListCurrentBusyDisks->erase(itOps);
	}
	else
		result = 1;
	return result;
}
// Uses jpg as the extension
void TimeToSubDirectoryAndFilename(SYSTEMTIME st, wstring& subDirectory, wstring& filename, wstring const& ext = L".jpg")
{
    WCHAR buffer[100];
    swprintf_s(buffer, L"\\%04d%02d%02d\\", st.wYear, st.wMonth, st.wDay);
    subDirectory = wstring(buffer);
    swprintf_s(buffer, L"%02d%02d%02d", st.wHour, st.wMinute, st.wSecond);
    filename = wstring(buffer) + ext;
}
Example #3
0
TEST_F(SorterTest, TestCaseInsensitiveStringCompares)
{
    // Check case insensitive string compares.
    EXPECT_EQ(0, CaseInsensitiveCmp(wstring(L"blah"), wstring(L"Blah")));
    EXPECT_EQ(0, CaseInsensitiveCmp(wstring(L"foo"), wstring(L"foo")));
    EXPECT_EQ(-1, CaseInsensitiveCmp(wstring(L"meep"), wstring(L"meepz")));
    EXPECT_EQ(-1, CaseInsensitiveCmp(wstring(L"meep"), wstring(L"meep baz")));
    EXPECT_EQ(1, CaseInsensitiveCmp(wstring(L"abc"), wstring(L"ABB")));
}
TEST(StringOperationsTest, ConvertToWidechar)
{
    wstring wideString;
    utf8ToWideChar("Teststring", wideString);
    EXPECT_TRUE(wstring(L"Teststring") == wideString);

    utf8ToWideChar("Trentemøller", wideString);
    EXPECT_TRUE(wstring(L"Trentemøller") == wideString);
}
static wstring descriptionSuitableForTestResult(IWebError* error, unsigned long identifier)
{
    wstring result = L"<NSError ";

    BSTR domainSTR;
    if (FAILED(error->domain(&domainSTR)))
        return wstring();

    wstring domain = wstringFromBSTR(domainSTR);
    ::SysFreeString(domainSTR);

    int code;
    if (FAILED(error->code(&code)))
        return wstring();

    if (domain == L"CFURLErrorDomain") {
        domain = L"NSURLErrorDomain";

        // Convert kCFURLErrorUnknown to NSURLErrorUnknown
        if (code == -998)
            code = -1;
    } else if (domain == L"kCFErrorDomainWinSock") {
        domain = L"NSURLErrorDomain";

        // Convert the winsock error code to an NSURLError code.
        if (code == WSAEADDRNOTAVAIL)
            code = -1004; // NSURLErrorCannotConnectToHose;
    }

    result += L"domain " + domain;
    result += L", code " + wstringFromInt(code);

    BSTR failingURLSTR;
    if (FAILED(error->failingURL(&failingURLSTR)))
        return wstring();

    wstring failingURL;
    
    // If the error doesn't have a failing URL, we fake one by using the URL the resource had 
    // at creation time. This seems to work fine for now.
    // See <rdar://problem/5064234> CFErrors should have failingURL key.
    if (failingURLSTR)
        failingURL = wstringFromBSTR(failingURLSTR);
    else
        failingURL = descriptionSuitableForTestResult(identifier);

    ::SysFreeString(failingURLSTR);

    result += L", failing URL \"" + urlSuitableForTestResult(failingURL) + L"\">";

    return result;
}
JSStringRef AccessibilityUIElement::role()
{
    if (!m_element)
        return JSStringCreateWithCharacters(0, 0);

    VARIANT vRole;
    if (FAILED(m_element->get_accRole(self(), &vRole)))
        return JSStringCreateWithCharacters(0, 0);

    ASSERT(V_VT(&vRole) == VT_I4 || V_VT(&vRole) == VT_BSTR);

    wstring result;
    if (V_VT(&vRole) == VT_I4) {
        unsigned roleTextLength = ::GetRoleText(V_I4(&vRole), 0, 0) + 1;

        Vector<TCHAR> roleText(roleTextLength);

        ::GetRoleText(V_I4(&vRole), roleText.data(), roleTextLength);

        result = roleText.data();
    } else if (V_VT(&vRole) == VT_BSTR)
        result = wstring(V_BSTR(&vRole), ::SysStringLen(V_BSTR(&vRole)));

    ::VariantClear(&vRole);

    return JSStringCreateWithCharacters(result.data(), result.length());
}
Example #7
0
static bool followShortcuts(wstring& path)
{
    if (PathFileExists(path.c_str()))
        return true;

    // Do we have a shortcut?
    wstring linkPath = path;
    linkPath.append(TEXT(".lnk"));
    if (!PathFileExists(linkPath.c_str()))
       return true;

    // We have a shortcut, find its target.
    COMPtr<IShellLink> shortcut(Create, CLSID_ShellLink);
    if (!shortcut)
       return false;
    COMPtr<IPersistFile> persistFile(Query, shortcut);
    if (!shortcut)
        return false;
    if (FAILED(persistFile->Load(linkPath.c_str(), STGM_READ)))
        return false;
    if (FAILED(shortcut->Resolve(0, 0)))
        return false;
    WCHAR targetPath[MAX_PATH];
    DWORD targetPathLen = _countof(targetPath);
    if (FAILED(shortcut->GetPath(targetPath, targetPathLen, 0, 0)))
        return false;
    if (!PathFileExists(targetPath))
        return false;
    // Use the target path as the result path instead.
    path = wstring(targetPath);

    return true;
}
Example #8
0
static wstring cfStringRefToWString(CFStringRef cfStr)
{
    Vector<wchar_t> v(CFStringGetLength(cfStr));
    CFStringGetCharacters(cfStr, CFRangeMake(0, CFStringGetLength(cfStr)), (UniChar *)v.data());

    return wstring(v.data(), v.size());
}
int wmain(int argc, WCHAR* argv[])
{
	if (argc != 2 && argc != 3)
	{
		printf("exe file [mode]\n");
		getchar();
		return 0;
	}

	if (argc == 3)
	{
		JPMode = FALSE;
	}

	if (wcsstr(argv[1], L".txt") || wcsstr(argv[1], L".exe") || wcsstr(argv[1], L".bat"))
	{
		//·ÀÖ¹ÍæÎÚÁú233
		return 0;
	}

	WinFile File;
	if (FAILED(File.Open(argv[1], WinFile::FileRead)))
	{
		return 0;
	}

	PBYTE Buffer = (PBYTE)HeapAlloc(GetProcessHeap(), 0, File.GetSize32());
	File.Read(Buffer, File.GetSize32());

	HRESULT Result = DisasmProc((wstring(argv[1]) + POST_NAME), Buffer, File.GetSize32());

	HeapFree(GetProcessHeap(), 0, Buffer);
	File.Release();
	return 0;
}
Example #10
0
wstring GetUsername()
{
	char buf[256] = {0};
	getlogin_r(buf, 255);

	return wstring(buf, buf+strlen(buf));
}
Example #11
0
   static wstring widen( const char* str )
   {
      if (*str == 0)
         return wstring();

      int chars_in = static_cast<int>(strlen(str));

      int chars_out = MultiByteToWideChar(
            CP_UTF8, // convert from UTF-8
            MB_ERR_INVALID_CHARS, // be strict
            str, chars_in,
            NULL, 0  // request required buffer size
            );

      if (chars_out == 0)
         throw_nowide_error();

      wstring out;
      out.resize(chars_out);

      int result = MultiByteToWideChar(
            CP_UTF8, // convert from UTF-8
            MB_ERR_INVALID_CHARS, // be strict
            str, chars_in,
            &out[0], chars_out
            );

      if (result == 0)
         throw_nowide_error();

      return out;
   }
void WriteToFile(vector<BYTE> *pdata, wstring & rootname)
{
	DWORD numbytes;
	GetLocalTime(&timeinfo);
	wstring extension = L".spaceball";
	swprintf_s(holdertime, L"%02d%02d%02d%ls", timeinfo.wHour, timeinfo.wMinute, timeinfo.wSecond,extension.c_str());
	wstring filename = rootname + wstring(holdertime);
	HANDLE fileholder;
	LPCWSTR stuff= (wchar_t*)filename.c_str();
	fileholder = CreateFile(stuff, GENERIC_WRITE , FILE_SHARE_READ, NULL,CREATE_NEW, 0,NULL);

	int datasize = (int)pdata->size();
	//int datasize = (int)pdata->size()- 8; I assume subtracting 8 was to trim off delimiters. Dunno!
	vector<BYTE>::iterator it = pdata ->begin();
	char * buffer = (char *)calloc(datasize,sizeof(BYTE));
	for( int i = 0; i < datasize; ++i)
	{
		buffer[i]=*it;
		pdata->erase(it);
	}

	if(!WriteFile(fileholder, buffer,(DWORD)datasize,&numbytes,NULL))
		printf("Error Writing to file?");
	else
		printf("Wrote to file just fine.");
	free(buffer);
	CloseHandle(fileholder);
}
	static inline wstring ToAppropriateStr(string str, wchar_t typeOfCharInReturnString)
	{
		const size_t MAX_OPTIONS_LENGTH = 8192;
		wchar_t wideString[MAX_OPTIONS_LENGTH] = {0};
		_snwprintf_s(wideString, MAX_OPTIONS_LENGTH, _TRUNCATE, L"%hs", str.c_str());
		return wstring(wideString);
	}
Example #14
0
const bool Registry::Read(const wstring keyName, wstring *out, const wstring defaultValue) const
{
   // Default the return value immediately
   *out = defaultValue;
   if (!good) return false;

   // Read the value once to get the size of the string
   long result = 0;
   DWORD size = 0;
   result = RegQueryValueEx(key, keyName.c_str(), 0, NULL, NULL, &size);

   // Read the value again to get the actual string
   if (result == ERROR_SUCCESS)
   {
      wchar_t *data = new wchar_t[size + 1];
      if (!data) return false;

      result = RegQueryValueEx(key, keyName.c_str(), 0, NULL, (LPBYTE)data, &size);

      if (result == ERROR_SUCCESS) *out = wstring(data);

      if (data) delete[] data;
      data = 0;
   }

   // 'out' would have only been set on success, otherwise the
   // default still exists in 'out', so we're all set
   return (result == ERROR_SUCCESS);
}
Example #15
0
HRESULT ComReg::UnRegisterCoclass(const GUID& clsid)
{
    enum { clsid_strlen = 39 };
    wchar_t clsid_str[clsid_strlen];

    const int n = StringFromGUID2(clsid, clsid_str, clsid_strlen);
    assert(n == clsid_strlen);
    n;

    const wstring clsid_keyname = wstring(L"CLSID\\") + clsid_str;

    Registry::Key clsid_key(HKEY_CLASSES_ROOT, clsid_keyname);
    //TODO: KEY_QUERY_VALUE | KEY_SET_VALUE);

    if (!clsid_key.is_open())
        return S_OK;

    Registry::Key subkey(clsid_key, L"VersionIndependentProgID");  //open

    if (subkey.is_open())
    {
        wstring val;

        if (subkey(val))
        {
            const DWORD dw = Registry::SHDeleteKey(HKEY_CLASSES_ROOT, val);
            assert((dw == ERROR_SUCCESS) || (dw == ERROR_FILE_NOT_FOUND));
            dw;

            //TODO: delete subkey from clsid_key
        }
    }

    subkey.open(clsid_key, L"ProgID");

    if (subkey.is_open())
    {
        wstring val;

        if (subkey(val))
        {
            const DWORD dw = Registry::SHDeleteKey(HKEY_CLASSES_ROOT, val);
            assert((dw == ERROR_SUCCESS) || (dw == ERROR_FILE_NOT_FOUND));
            dw;

            //TODO: delete subkey
        }

    }

    subkey.close();
    clsid_key.close();

    const DWORD dw = Registry::SHDeleteKey(HKEY_CLASSES_ROOT, clsid_keyname);
    assert((dw == ERROR_SUCCESS) || (dw == ERROR_FILE_NOT_FOUND));
    dw;

    return S_OK;
}
    void OriginalMethodPreparation::FillIndirectionPreparation(MetadataDispenser const *pDisp, MethodGenerator *pTarget, PrigData &prigData)
    {
        using boost::timer::cpu_timer;
        using boost::timer::default_places;
        using std::wstring;
        using std::vector;

        auto timer = cpu_timer();

        _ASSERTE(prigData.m_pMSCorLibDll);
        auto const *pMSCorLibDll = prigData.m_pMSCorLibDll;
        auto const *pInt32 = pMSCorLibDll->GetType(L"System.Int32");
        auto const *pBoolean = pMSCorLibDll->GetType(L"System.Boolean");

        CPPANONYM_V_LOG1("Processing time to get BCL definitions: %|1$s|.", timer.format(default_places, "%ws wall, %us user + %ss system = %ts CPU (%p%)"));
        timer = cpu_timer();
            
        auto const *pTryPrigTarget = static_cast<IMethod *>(nullptr);
        {
            auto *pDeclaringTypeGen = pTarget->GetDeclaringTypeGenerator();
            auto name = wstring(L"TryPrig") + pTarget->GetName();
            auto attr = MethodAttributes::MA_PRIVATE | MethodAttributes::MA_HIDE_BY_SIG | MethodAttributes::MA_STATIC;
            auto callingConvention = CallingConventions::CC_STANDARD;
            auto const *pRetType = pBoolean;
            auto paramTypes = vector<IType const *>();
            {
                if (pTarget->GetReturnType()->GetKind() != TypeKinds::TK_VOID)
                    paramTypes.push_back(pTarget->GetReturnType()->MakeByRefType());
                if (!pTarget->IsStatic())
                {
                    auto const *pDeclaringType = pTarget->GetDeclaringType();
                    auto isGenericType = pDeclaringType->IsGenericType();
                    auto isValueType = pDeclaringType->IsValueType();
                    if (isGenericType)
                        pDeclaringType = MakeGenericExplicitItsInstance(pDeclaringType);
                    if (isValueType)
                        pDeclaringType = pDeclaringType->MakeByRefType();
                    paramTypes.push_back(pDeclaringType);
                }
                auto const &params = pTarget->GetParameters();
                BOOST_FOREACH (auto const &pParam, params)
                {
                    auto const *pParamType = pParam->GetParameterType();
                    paramTypes.push_back(pParamType);
                }
            }
            auto *pTryPrigTargetGen = pDeclaringTypeGen->DefineMethod(name, attr, callingConvention, pRetType, paramTypes);
            if (pTarget->IsGenericMethod())
            {
                auto names = vector<wstring>();
                auto const &genericArgs = pTarget->GetGenericArguments();
                BOOST_FOREACH (auto const &pGenericArg, genericArgs)
                    names.push_back(pGenericArg->GetFullName());
                
                pTryPrigTargetGen->DefineGenericParameters(names);
            }
Example #17
0
static bool resolveCygwinPath(const wstring& cygwinPath, wstring& windowsPath)
{
    wstring fileProtocol = L"file://";
    bool isFileProtocol = cygwinPath.find(fileProtocol) != string::npos;
    if (cygwinPath[isFileProtocol ? 7 : 0] != '/')  // ensure path is absolute
        return false;

    // Get the Root path.
    WCHAR rootPath[MAX_PATH];
    DWORD rootPathSize = _countof(rootPath);
    DWORD keyType;
    DWORD result = ::SHGetValueW(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2\\/"), TEXT("native"), &keyType, &rootPath, &rootPathSize);

    if (result != ERROR_SUCCESS || keyType != REG_SZ) {
        // Cygwin 1.7 doesn't store Cygwin's root as a mount point anymore, because mount points are now stored in /etc/fstab.
        // However, /etc/fstab doesn't contain any information about where / is located as a Windows path, so we need to use Cygwin's
        // new registry key that has the root.
        result = ::SHGetValueW(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Cygwin\\setup"), TEXT("rootdir"), &keyType, &rootPath, &rootPathSize);
        if (result != ERROR_SUCCESS || keyType != REG_SZ)
            return false;
    }

    windowsPath = wstring(rootPath, rootPathSize);

    int oldPos = isFileProtocol ? 8 : 1;
    while (1) {
        int newPos = cygwinPath.find('/', oldPos);

        if (newPos == -1) {
            wstring pathComponent = cygwinPath.substr(oldPos);

            if (!appendComponentToPath(windowsPath, pathComponent))
               return false;

            if (!followShortcuts(windowsPath))
                return false;

            break;
        }

        wstring pathComponent = cygwinPath.substr(oldPos, newPos - oldPos);
        if (!appendComponentToPath(windowsPath, pathComponent))
            return false;

        if (!followShortcuts(windowsPath))
            return false;

        oldPos = newPos + 1;
    }

    if (isFileProtocol)
        windowsPath = fileProtocol + windowsPath;

    return true;
}
Example #18
0
wstring ChunkFormattingBrackets ::  FormatWord(const wstring& token, const wstring& label)
{
	wstring bio = label;
	wstring prev = prevBIO;
	prevBIO = bio;

	wstring res0;

	if(label == L"BH" || label == L"IH")
	{
		res0 = token;
		res0.append(L"[X]");
	}
	else
	{
		res0 = token;
	}

	if(bio == L"I" || bio == L"IH")
	{
		return res0;
	}

	if(bio == L"B" || bio == L"BH")
	{
		if(prev != L"O")
		{
			return wstring(L"] [").append(res0);
		}
		else
		{
			return wstring(L"[").append(res0);
		}
	}

	if(prev != L"O")
	{
		return wstring(L"] ").append(res0);
	}

	return res0;
}
Example #19
0
wstring MultiBaseSymbol::to_string() const noexcept {
  auto representation = wstring();

  representation.reserve(20);

  for (const auto &symbol : _bases) {
    representation.append(symbol.to_string());
  }

  return representation;
}
Example #20
0
wstring to_wstring(const char* s)
{
	auto len = strlen(s);	// length without null terminator
	auto wlen = MultiByteToWideChar(CP_ACP, 0, s, len, nullptr, 0);
	if (len == -1)
		return wstring();

	wstring str(wlen, L'\0');
	MultiByteToWideChar(CP_ACP, 0, s, len, &str.front(), wlen);
	return str;
}
Example #21
0
wstring NBTools::GetApplicationPath()
{
    std::vector<WCHAR> curDir(MAX_PATH);
    DWORD result = GetModuleFileName(NULL, &curDir[0], MAX_PATH);
    while(result == curDir.size()) {
        curDir.resize(curDir.size() * 2);
        result = GetModuleFileName(NULL, &curDir[0], (DWORD)curDir.size());
    }
    return wstring(curDir.begin(), curDir.begin() + result);
    return L"";
}
Example #22
0
wstring StrToWstr(const string& str, UINT code_page) {
  if (!str.empty()) {
    int length = MultiByteToWideChar(code_page, 0, str.c_str(), -1, nullptr, 0);
    if (length > 0) {
      vector<wchar_t> output(length);
      MultiByteToWideChar(code_page, 0, str.c_str(), -1, &output[0], length);
      return &output[0];
    }
  }

  return wstring();
}
BOOL MainDialog::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(icon_, TRUE);            // Set big icon
    SetIcon(icon_, FALSE);        // Set small icon

    const wchar_t* defaultDir = L"c:/";
    wstring d = Preference::GetInstance()->GetAudioDir();
    audioDir_.SetWindowText(d.empty() ? defaultDir : d.c_str());
    if (d.empty())
        Preference::GetInstance()->SetAudioDir(wstring(defaultDir));

    d = Preference::GetInstance()->GetResultDir();
    resultDir_.SetWindowText(d.empty() ? defaultDir : d.c_str());
    if (d.empty())
        Preference::GetInstance()->SetResultDir(wstring(defaultDir));

    return TRUE;  // return TRUE  unless you set the focus to a control
}
static wstring descriptionSuitableForTestResult(IWebURLResponse* response)
{
    if (!response)
        return L"(null)";

    BSTR urlBSTR;
    if (FAILED(response->URL(&urlBSTR)))
        return wstring();
    
    wstring url = urlSuitableForTestResult(wstringFromBSTR(urlBSTR));
    ::SysFreeString(urlBSTR);

    return L"<NSURLResponse " + url + L">";
}
Example #25
0
Tokenizer::Tokenizer()
	: character_(initialize_character_set())
	, delimiter_(initialize_delimiters(L".,;:?+#=@|_`-*/^$%~&!\\'\"()<>[]{}\0\r\n\t\b\a\v\f\r"))
{
	auto start = high_resolution_clock::now();
	
	char const * filename_[] = {
		"vietnamese.txt" ,
		"vietnamese-stopwords.txt"
	};
	
	TokenContainer * data_[2] = {
		&vocabulary , &stopword_
	};

	auto not_character = character_.end();

	for (int i = 0; i < 2; ++i)
	{		
		boost::iostreams::mapped_file reader(filename_[i] , mapped_file::readonly);
		
		if (!reader.is_open())
			//	Cannot read vocabulary, cannot proceed on
			throw "Cannot open " + string(filename_[i]) + " to read vocabulary.\n";
		
		wchar const * it , *endit;
		it = 1 + reinterpret_cast<wchar const *>(reader.const_begin());
		endit = reinterpret_cast<wchar const *>(reader.const_end());

		while (it != endit)
		{
			Token token;
			while (true)
			{
				auto begin = it;
				while (character_.find(*it) != not_character)
					++it;
				token.push_back(wstring(begin , it - begin));
				if ((*it) == L'\n' || (*it) == L'\0')
					break;
				++it;
			}
			data_[i]->insert(token);
			++it;
		}
		reader.close();
	}
	auto finish = high_resolution_clock::now();
	cout << "Reading vocabulary and stop words: " << duration_cast<milliseconds>(finish - start).count() << "ms\n";
}
Example #26
0
static bool resolveCygwinPath(const wstring& cygwinPath, wstring& windowsPath)
{
    wstring fileProtocol = L"file://";
    bool isFileProtocol = cygwinPath.find(fileProtocol) != string::npos;
    if (cygwinPath[isFileProtocol ? 7 : 0] != '/')  // ensure path is absolute
        return false;

    // Get the Root path.
    WCHAR rootPath[MAX_PATH];
    DWORD rootPathSize = _countof(rootPath);
    DWORD keyType;
    DWORD result = ::SHGetValueW(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2\\/"), TEXT("native"), &keyType, &rootPath, &rootPathSize);

    if (result != ERROR_SUCCESS || keyType != REG_SZ)
        return false;

    windowsPath = wstring(rootPath, rootPathSize);

    int oldPos = isFileProtocol ? 8 : 1;
    while (1) {
        int newPos = cygwinPath.find('/', oldPos);

        if (newPos == -1) {
            wstring pathComponent = cygwinPath.substr(oldPos);

            if (!appendComponentToPath(windowsPath, pathComponent))
               return false;

            if (!followShortcuts(windowsPath))
                return false;

            break;
        }

        wstring pathComponent = cygwinPath.substr(oldPos, newPos - oldPos);
        if (!appendComponentToPath(windowsPath, pathComponent))
            return false;

        if (!followShortcuts(windowsPath))
            return false;

        oldPos = newPos + 1;
    }

    if (isFileProtocol)
        windowsPath = fileProtocol + windowsPath;

    return true;
}
Example #27
0
wstring ConvertCodepageToWString( std::string s, int iCodePage )
{
	if( s.empty() )
		return wstring();

	int iBytes = MultiByteToWideChar( iCodePage, 0, s.data(), s.size(), nullptr, 0 );
	ASSERT_M( iBytes > 0, werr_format( GetLastError(), "MultiByteToWideChar" ).c_str() );

	wchar_t *pTemp = new wchar_t[iBytes];
	MultiByteToWideChar( iCodePage, 0, s.data(), s.size(), pTemp, iBytes );
	wstring sRet( pTemp, iBytes );
	delete [] pTemp;

	return sRet;
}
Example #28
0
wstring string_to_wstring(const string& src,bool utf8)
{
  if(src.empty())
    return wstring();
  UINT cp=utf8?CP_UTF8:CP_ACP;
  int size=MultiByteToWideChar(cp,0,src.c_str(),-1,NULL,0);
  if(size==0)
    throw runtime_error("Unable to convert a string");
  wstring s(size,'\0');
  wchar_t *buff=new wchar_t[size];
  MultiByteToWideChar(cp,0,src.c_str(),-1,buff,size);
  s.assign(buff);
  delete[] buff;
  return s;
}
Example #29
0
int check_network(vector <nInterface>& vInterfaces) 
{
	const wchar_t *perfIn = L"\\Network Interface(*)\\Bytes Received/sec";
	const wchar_t *perfOut = L"\\Network Interface(*)\\Bytes Sent/sec";

	PDH_HQUERY phQuery = NULL;
	PDH_HCOUNTER phCounterIn, phCounterOut;
	DWORD dwBufferSizeIn = 0, dwBufferSizeOut = 0, dwItemCount = 0;
	PDH_FMT_COUNTERVALUE_ITEM *pDisplayValuesIn = NULL, *pDisplayValuesOut = NULL;

	if (PdhOpenQuery(NULL, NULL, &phQuery) != ERROR_SUCCESS)
		goto die;

    //Totaly reasonable statement
	if (PdhOpenQuery(NULL, NULL, &phQuery) == ERROR_SUCCESS) {
		if (PdhAddEnglishCounter(phQuery, perfIn, NULL, &phCounterIn) == ERROR_SUCCESS) {
			if (PdhAddEnglishCounter(phQuery, perfOut, NULL, &phCounterOut) == ERROR_SUCCESS) {
				if (PdhCollectQueryData(phQuery) == ERROR_SUCCESS) {
					Sleep(1000);
					if (PdhCollectQueryData(phQuery) == ERROR_SUCCESS) {
						if (PdhGetFormattedCounterArray(phCounterIn, PDH_FMT_LONG, &dwBufferSizeIn, &dwItemCount, pDisplayValuesIn) == PDH_MORE_DATA &&
							PdhGetFormattedCounterArray(phCounterOut, PDH_FMT_LONG, &dwBufferSizeOut, &dwItemCount, pDisplayValuesOut) == PDH_MORE_DATA) {
							pDisplayValuesIn = new PDH_FMT_COUNTERVALUE_ITEM[dwItemCount*dwBufferSizeIn];
							pDisplayValuesOut = new  PDH_FMT_COUNTERVALUE_ITEM[dwItemCount*dwBufferSizeOut];
							if (PdhGetFormattedCounterArray(phCounterIn, PDH_FMT_LONG, &dwBufferSizeIn, &dwItemCount, pDisplayValuesIn) == ERROR_SUCCESS &&
								PdhGetFormattedCounterArray(phCounterOut, PDH_FMT_LONG, &dwBufferSizeOut, &dwItemCount, pDisplayValuesOut) == ERROR_SUCCESS) {
								for (DWORD i = 0; i < dwItemCount; i++) {
									nInterface *iface = new nInterface(wstring(pDisplayValuesIn[i].szName));
									iface->BytesInSec = pDisplayValuesIn[i].FmtValue.longValue;
									iface->BytesOutSec = pDisplayValuesOut[i].FmtValue.longValue;
									vInterfaces.push_back(*iface);
								}
								return -1;
							}
						}
					}
				}
			}
		}
	}

	
die:
	die();
	if (phQuery)
		PdhCloseQuery(phQuery);
	return 3;
}
Example #30
0
bool appendComponentToPath(wstring& path, const wstring& component)
{
    WCHAR buffer[MAX_PATH];

    if (path.size() + 1 > MAX_PATH)
        return false;

    memcpy(buffer, path.data(), path.size() * sizeof(WCHAR));
    buffer[path.size()] = '\0';

    if (!PathAppendW(buffer, component.c_str()))
        return false;

    path = wstring(buffer);
    return true;
}