BOOL CCustomAutoComplete::Bind(HWND hWndEdit, DWORD dwOptions, LPCTSTR pcFormatString) { ATLASSERT(::IsWindow(hWndEdit)); if (m_bBound || m_pac != NULL) return FALSE; if (SUCCEEDED(m_pac.CoCreateInstance(CLSID_AutoComplete))) { if (dwOptions != 0) { CComQIPtr<IAutoComplete2> pAC2(m_pac); if (pAC2 != NULL) { pAC2->SetOptions(dwOptions); pAC2.Release(); } } USES_CONVERSION; if (SUCCEEDED(m_pac->Init(hWndEdit, this, NULL, CT2CW(pcFormatString)))) { m_bBound = TRUE; return TRUE; } } return FALSE; }
void TestDocProvider5::TestDemote() { CStdString sDocumentName = _T("TestDocument for DemoteToWord"); CStdString sTestDocID; m_pTestHelper->SaveDocument(sDocumentName, sTestDocID); try { BSTR sDocID = ::SysAllocString(CT2CW(sTestDocID.c_str())); m_pIDocProvider5->PromoteToSynergy(&sDocID); ::SysFreeString(sDocID); } catch(_com_error& e) { CStdString sErr(e.ErrorMessage()); assertMessage(false, _T("Promote to Synergy Failed")); } try { m_pIDocProvider5->DemoteToDocument(_bstr_t(sTestDocID)); tagWSDOCUMENT wsDoc = m_pIDocProvider5->GetDocument(_bstr_t(sTestDocID), 8 /*DF_INFO_ONLY*/); CStdString sExt = wsDoc.bstrExtension; assertMessage(sExt.CompareNoCase(_T("DOC")) == 0, _T("Failed to demote to document in powerdocs")); } catch(_com_error& e) { CStdString sErr(e.ErrorMessage()); assertMessage(false, sErr.c_str()); } }
void TestDocProvider5::TestPromote() { CStdString sDocumentName = _T("TestDocument for PromoteToSynergy"); CStdString sTestDocID; m_pTestHelper->SaveDocument(sDocumentName, sTestDocID); try { BSTR sDocID = ::SysAllocString(CT2CW(sTestDocID.c_str())); m_pIDocProvider5->PromoteToSynergy(&sDocID); ::SysFreeString(sDocID); } catch(_com_error& e) { CStdString sErr(e.ErrorMessage()); assertMessage(false, sErr.c_str()); } }
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; }
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(); }
HRESULT DownloadHelper::DownloadFile(const TCHAR* szURL, const TCHAR* szLocalFile, BOOL bResumable, BOOL bUIFeedback) { HINTERNET hOpen = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; HANDLE hFile = INVALID_HANDLE_VALUE; DWORD dwDownloadError = 0; DWORD nContentLength = 0; /* Some of error messages use drive letter. Result is something like "(C:)". NB: Parentheses are added here because in some other places we same message but can not provide disk label info */ TCHAR drivePath[5]; /* assuming szLocalFile is not NULL */ _sntprintf(drivePath, 5, "(%c:)", szLocalFile[0]); WCHAR* wName = CT2CW(drivePath); __try { m_csDownload.Lock(); time(&m_startTime); } __finally { m_csDownload.Unlock(); } __try { // block potential security hole if (strstr(szURL, TEXT("file://")) != NULL) { dwDownloadError = 1; __leave; } HWND hProgressInfo = NULL; TCHAR szStatus[BUFFER_SIZE]; if (bUIFeedback) { // init download dialg text m_dlg->initDialogText(m_pszURL, m_pszNameText); } // Open Internet Call hOpen = ::InternetOpen("deployHelper", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL); if (hOpen == NULL) { dwDownloadError = 1; __leave; } // URL components URL_COMPONENTS url_components; ::ZeroMemory(&url_components, sizeof(URL_COMPONENTS)); TCHAR szHostName[BUFFER_SIZE], szUrlPath[BUFFER_SIZE], szExtraInfo[BUFFER_SIZE]; url_components.dwStructSize = sizeof(URL_COMPONENTS); url_components.lpszHostName = szHostName; url_components.dwHostNameLength = BUFFER_SIZE; url_components.nPort = NULL; url_components.lpszUrlPath = szUrlPath; url_components.dwUrlPathLength = BUFFER_SIZE; url_components.lpszExtraInfo = szExtraInfo; url_components.dwExtraInfoLength = BUFFER_SIZE; // Crack the URL into pieces ::InternetCrackUrl(szURL, lstrlen(szURL), NULL, &url_components); // Open Internet Connection hConnect = ::InternetConnect(hOpen, url_components.lpszHostName, url_components.nPort, "", "", INTERNET_SERVICE_HTTP, NULL, NULL); if (hConnect == NULL) { dwDownloadError = 1; __leave; } // Determine the relative URL path by combining // Path and ExtraInfo char szURL[4096]; if (url_components.dwUrlPathLength != 0) lstrcpy(szURL, url_components.lpszUrlPath); else lstrcpy(szURL, "/"); if (url_components.dwExtraInfoLength != 0) lstrcat(szURL, url_components.lpszExtraInfo); BOOL bRetryHttpRequest = FALSE; int numberOfRetry = 0; long secondsToWait = 60; do { bRetryHttpRequest = FALSE; // Make a HTTP GET request hRequest = ::HttpOpenRequest(hConnect, "GET", szURL, "HTTP/1.1", "", NULL, INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_DONT_CACHE, 0); if (hRequest == NULL) { dwDownloadError = 1; __leave; } // Create or open existing destination file hFile = ::CreateFile(szLocalFile, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_ARCHIVE, NULL); if (hFile == INVALID_HANDLE_VALUE) { if (bUIFeedback) { if (IDRETRY == m_dlg->SafeMessageBox( IDS_DISK_WRITE_ERROR, IDS_DISK_WRITE_ERROR_CAPTION, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL, wName)) { bRetryHttpRequest = TRUE; continue; } } dwDownloadError = 1; __leave; } DWORD fileSize = GetFileSize(hFile, NULL); // Check if resumable download is enabled if (bResumable == FALSE) { // Start from scratch fileSize = 0; } FILETIME tWrite; BOOL rangereq = FALSE; if ((fileSize != 0) && (fileSize != 0xFFFFFFFF) && GetFileTime(hFile, NULL, NULL, &tWrite)) { char szHead[100]; SYSTEMTIME tLocal; char buf[INTERNET_RFC1123_BUFSIZE]; FileTimeToSystemTime(&tWrite, &tLocal); InternetTimeFromSystemTime(&tLocal, INTERNET_RFC1123_FORMAT, buf, INTERNET_RFC1123_BUFSIZE); sprintf(szHead, "Range: bytes=%d-\r\nIf-Range: %s\r\n", fileSize, buf); HttpAddRequestHeaders(hRequest, szHead, lstrlen(szHead), HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE); rangereq = TRUE; } // This is a loop to handle various potential error when the // connection is made BOOL bCont = TRUE; while ((FALSE == ::HttpSendRequest(hRequest, NULL, NULL, NULL, NULL)) && bCont ) { // We might have an invalid CA. DWORD dwErrorCode = GetLastError(); switch(dwErrorCode) { case E_JDHELPER_TIMEOUT: case E_JDHELPER_NAME_NOT_RESOLVED: case E_JDHELPER_CANNOT_CONNECT: { bCont = FALSE; // Display the information dialog if (bUIFeedback) { // decrement download counter to prevent progress // dialog from popping up while the message box is // up m_dlg->bundleInstallComplete(); if (dwErrorCode == E_JDHELPER_TIMEOUT) { bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_HTTP_STATUS_REQUEST_TIMEOUT, IDS_HTTP_INSTRUCTION_REQUEST_TIMEOUT, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL)); } else { bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_HTTP_STATUS_SERVER_NOT_REACHABLE, IDS_HTTP_INSTRUCTION_SERVER_NOT_REACHABLE, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL)); } // re-increment counter because it will be decremented // again upon return m_dlg->bundleInstallStart(); bCont = bRetryHttpRequest; } break; } case ERROR_INTERNET_INVALID_CA: case ERROR_INTERNET_SEC_CERT_CN_INVALID: case ERROR_INTERNET_SEC_CERT_DATE_INVALID: case ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR: case ERROR_INTERNET_INCORRECT_PASSWORD: case ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED: default: { // Unless the user agrees to continue, we just // abandon now ! bCont = FALSE; // Make sure to test the return code from // InternetErrorDlg user may click OK or Cancel. In // case of Cancel, request should not be resubmitted if (bUIFeedback) { if (ERROR_SUCCESS == ::InternetErrorDlg( NULL, hRequest, dwErrorCode, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL)) bCont = TRUE; } } } } if (bCont == FALSE) { // User has denied the request dwDownloadError = 1; __leave; } // // Read HTTP status code // DWORD dwErrorCode = GetLastError(); DWORD dwStatus=0; DWORD dwStatusSize = sizeof(DWORD); if (FALSE == ::HttpQueryInfo(hRequest, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL)) { dwErrorCode = GetLastError(); } bCont = TRUE; while ((dwStatus == HTTP_STATUS_PROXY_AUTH_REQ || dwStatus == HTTP_STATUS_DENIED) && bCont) { int result = ::InternetErrorDlg(GetDesktopWindow(), hRequest, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, NULL); if (ERROR_CANCELLED == result) { bCont = FALSE; } else { ::HttpSendRequest(hRequest, NULL, 0, NULL, 0); // Reset buffer length dwStatusSize = sizeof(DWORD); ::HttpQueryInfo(hRequest, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL); } } if (dwStatus == HTTP_STATUS_OK || dwStatus == HTTP_STATUS_PARTIAL_CONTENT) { // Determine content length, so we may show the progress bar // meaningfully // nContentLength = 0; DWORD nLengthSize = sizeof(DWORD); ::HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &nContentLength, &nLengthSize, NULL); if (nContentLength <= 0) { // If can't estimate content length, estimate it // to be 6MB nContentLength = 15000000; } else if (rangereq && (fileSize != 0) && (nContentLength == fileSize)) { // If the file is already downloaded completely and then // we send a range request, the whole file is sent instead // of nothing. So avoid downloading again. // Some times return value is 206, even when whole file // is sent. So check if "Content-range:" is present in the // reply char buffer[256]; DWORD length = sizeof(buffer); if(!HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_RANGE, buffer, &length, NULL)) { if(HttpQueryInfo(hRequest, HTTP_QUERY_LAST_MODIFIED, buffer, &length, NULL)) { SYSTEMTIME systime; FILETIME filtime; InternetTimeToSystemTime(buffer, &systime, NULL); SystemTimeToFileTime(&systime, &filtime); if ((CompareFileTime(&tWrite, &filtime)) == 1) { // no need to download dwDownloadError = 0; __leave; } } else { ::SetFilePointer(hFile, 0, 0, FILE_BEGIN); ::SetEndOfFile(hFile); // truncate the file } } } TCHAR szBuffer[8096]; DWORD dwBufferSize = 8096; // Read from HTTP connection and write into // destination file // DWORD nRead = 0; DWORD dwTotalRead = 0; BOOL bCancel = FALSE; if (dwStatus == HTTP_STATUS_PARTIAL_CONTENT) { // If we are using resumable download, fake // start time so it looks like we have begun // the download several minutes again. // m_startTime = m_startTime - 100; ::SetFilePointer(hFile, 0, 0, FILE_END); // seek to end } else { ::SetFilePointer(hFile, 0, 0, FILE_BEGIN); ::SetEndOfFile(hFile); // truncate the file } do { nRead=0; if (::InternetReadFile(hRequest, szBuffer, dwBufferSize, &nRead)) { if (nRead) { DWORD dwNumberOfBytesWritten = NULL; BOOL ret = WriteFile(hFile, szBuffer, nRead, &dwNumberOfBytesWritten, NULL); if (!ret) { // WriteFile failed if (bUIFeedback) { if (GetLastError() == ERROR_DISK_FULL) { bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_DISK_FULL_ERROR, IDS_DISK_FULL_ERROR_CAPTION, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL, wName)); } else { bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_DISK_WRITE_ERROR, IDS_DISK_WRITE_ERROR_CAPTION, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL, wName)); } if (!bRetryHttpRequest) { dwDownloadError = 1; break; } } continue; } } dwTotalRead += nRead; // update download progress dialog m_dlg->OnProgress(nRead); // Check if download has been cancelled if (m_dlg->isDownloadCancelled()) { m_dlg->decrementProgressMax(nContentLength, dwTotalRead); bCancel = TRUE; break; } } else { bCancel = TRUE; break; } } while (nRead); if (bCancel) { // User has cancelled the operation or InternetRead failed // don't do return here, we need to cleanup dwDownloadError = 1; __leave; } } else if (dwStatus == 416 && (fileSize != 0) && (fileSize != 0xFFFFFFFF)) { // This error could be returned, When the full file exists // and a range request is sent with range beyond filessize. // The best way to fix this is in future is, to send HEAD // request and get filelength before sending range request. dwDownloadError = 0; __leave; } else if (dwStatus == 403) { // Forbidden from Akamai means we need to get a new download token JNIEnv *env = m_dlg->getJNIEnv(); jclass exceptionClass = env->FindClass("java/net/HttpRetryException"); if (exceptionClass == NULL) { /* Unable to find the exception class, give up. */ __leave; } jmethodID constructor; constructor = env->GetMethodID(exceptionClass, "<init>", "(Ljava/lang/String;I)V"); if (constructor != NULL) { jobject exception = env->NewObject(exceptionClass, constructor, env->NewStringUTF("Forbidden"), 403); env->Throw((jthrowable) exception); } __leave; } else if(dwStatus >= 400 && dwStatus < 600) { /* NB: Following case seems to be never used! HTTP_STATUS_FORBIDDEN is the same as 403 and 403 was specially handled few lines above! */ if (dwStatus == HTTP_STATUS_FORBIDDEN) { if (bUIFeedback) { bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_HTTP_STATUS_FORBIDDEN, IDS_HTTP_INSTRUCTION_FORBIDDEN, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL, L"403")); } } else if (dwStatus == HTTP_STATUS_SERVER_ERROR) { if (bUIFeedback) { bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_HTTP_STATUS_SERVER_ERROR, IDS_HTTP_INSTRUCTION_UNKNOWN_ERROR, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL, L"500")); } } else if (dwStatus == HTTP_STATUS_SERVICE_UNAVAIL) { if (numberOfRetry < 5) { // If the server is busy, automatically retry // We wait couple seconds before retry to avoid // congestion for (long i = (long) secondsToWait; i >= 0; i--) { // Update status if (bUIFeedback) { char szBuffer[BUFFER_SIZE]; ::LoadString(_Module.GetResourceInstance(), IDS_DOWNLOAD_STATUS_RETRY, szStatus, BUFFER_SIZE); wsprintf(szBuffer, szStatus, i); ::SetWindowText(hProgressInfo, szBuffer); } // Sleep 1 second ::Sleep(1000); } // We use a semi-binary backoff algorithm to // determine seconds to wait numberOfRetry += 1; secondsToWait = secondsToWait + 30; bRetryHttpRequest = TRUE; continue; } else { if (bUIFeedback) { bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_HTTP_STATUS_SERVICE_UNAVAIL, IDS_HTTP_INSTRUCTION_SERVICE_UNAVAIL, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL, L"503")); if (bRetryHttpRequest) { numberOfRetry = 0; secondsToWait = 60; continue; } } } } else { if (bUIFeedback) { WCHAR szBuffer[10]; _snwprintf(szBuffer, 10, L"%d", dwStatus); bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_HTTP_STATUS_OTHER, IDS_HTTP_INSTRUCTION_UNKNOWN_ERROR, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL, szBuffer)); } } if (!bRetryHttpRequest) { dwDownloadError = 1; } } else { if (bUIFeedback) { WCHAR szBuffer[10]; _snwprintf(szBuffer, 10, L"%d", dwStatus); bRetryHttpRequest = (IDRETRY == m_dlg->SafeMessageBox( IDS_HTTP_STATUS_OTHER, IDS_HTTP_INSTRUCTION_UNKNOWN_ERROR, IDS_ERROR_CAPTION, DIALOG_ERROR_RETRYCANCEL, szBuffer)); } if (!bRetryHttpRequest) { dwDownloadError = 1; } } // Close HTTP request // // This is necessary if the HTTP request // is retried if (hRequest) ::InternetCloseHandle(hRequest); if (hFile != INVALID_HANDLE_VALUE) { ::CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } } while (bRetryHttpRequest); } __finally { if (hRequest) ::InternetCloseHandle(hRequest); if (hConnect) ::InternetCloseHandle(hConnect); if (hOpen) ::InternetCloseHandle(hOpen); if (hFile != INVALID_HANDLE_VALUE) ::CloseHandle(hFile); } // Exit dialog if (dwDownloadError == 0) { return S_OK; } else { DeleteFile(szLocalFile); return E_FAIL; } }
/** * @param strModule - module file name. * @return pointer to module processor. */ boost::shared_ptr<CBaseProcessor> CExpressModeDlg::GetModuleInfo(const CString& strModule) { boost::shared_ptr<CBaseProcessor> pBaseProcessor; if (strModule.IsEmpty()) return pBaseProcessor; CModuleMap::iterator itModule = m_mapModules.find(strModule); if (itModule == m_mapModules.end()) { if (m_pXMLNodeProcess != NULL) { CString strExpression; strExpression.Format(_T("./modules/module[name=\"%s\"]"), strModule); CComPtr<IXMLDOMNode> pXMLNodeModule; if (SelectXMLNode(m_pXMLNodeProcess, CT2CW(strExpression), pXMLNodeModule)) { CString strBaseAddress; GetXMLNodeText(pXMLNodeModule, OLESTR("./base"), strBaseAddress); PVOID ptrBaseAddress = (PVOID)_tcstoui64(strBaseAddress, NULL, 0); CString strModuleSize; GetXMLNodeText(pXMLNodeModule, OLESTR("./size"), strModuleSize); DWORD dwModuleSize = _tcstoul(strModuleSize, NULL, 0); if (ptrBaseAddress != NULL && dwModuleSize != 0) { TCHAR szModuleName[MAX_PATH]; _tcscpy_s(szModuleName, countof(szModuleName), PathFindFileName(strModule)); TCHAR szMapPdbFolder[MAX_PATH]; m_txtMapPdbFolder.GetWindowText(szMapPdbFolder, countof(szMapPdbFolder)); TCHAR szSystemFolder[MAX_PATH]; GetSystemDirectory(szSystemFolder, countof(szSystemFolder)); TCHAR szMapPdbFile[MAX_PATH]; if (! FindFileByPattern(szMapPdbFolder, szModuleName, _T(".map"), szMapPdbFile) && ! FindFileByPattern(szMapPdbFolder, szModuleName, _T(".pdb"), szMapPdbFile) && ! FindFileByPattern(szSystemFolder, szModuleName, _T(".map"), szMapPdbFile) && ! FindFileByPattern(szSystemFolder, szModuleName, _T(".pdb"), szMapPdbFile)) { return pBaseProcessor; } CBaseProcessor::PROCESSED_FILE_TYPE eProcessedFileType = CBaseProcessor::GetFileType(szMapPdbFile); switch (eProcessedFileType) { case CBaseProcessor::PFT_MAP: { CMapProcessor* pMapProcessor = STATIC_DOWNCAST(CMapProcessor, m_pMapProcessor.get()); if (pMapProcessor == NULL) { pMapProcessor = new CMapProcessor(); pBaseProcessor.reset(pMapProcessor); } pBaseProcessor = m_pMapProcessor; pMapProcessor->LoadMapText(szMapPdbFile); pMapProcessor->SetBaseAddress(ptrBaseAddress); } break; case CBaseProcessor::PFT_PDB: { CPdbProcessor* pPdbProcessor = STATIC_DOWNCAST(CPdbProcessor, m_pPdbProcessor.get()); if (pPdbProcessor == NULL) { pPdbProcessor = new CPdbProcessor(); m_pPdbProcessor.reset(pPdbProcessor); } pBaseProcessor = m_pPdbProcessor; pPdbProcessor->LoadModule(szMapPdbFile, ptrBaseAddress, dwModuleSize); } break; } if (pBaseProcessor.get() != NULL) m_mapModules.insert(CModuleMap::value_type(strModule, pBaseProcessor)); } } } } else pBaseProcessor = itModule->second; return pBaseProcessor; }
void WcDependencies::GetDependencies(void) { HRESOURCE hRes = OpenClusterResource(thePreSetup.m_hCluster, CT2CW(thePreSetup.m_ResourceName.GetBuffer())); if (hRes == NULL) return; DWORD dwResult = ERROR_SUCCESS; // Captures return values DWORD dwIndex = 0; // Enumeration index DWORD dwType = CLUSTER_RESOURCE_ENUM_DEPENDS; // Type of object to enumerate DWORD cbNameAlloc = // Allocated size of the name buffer MAXIMUM_NAMELENGTH * sizeof( WCHAR ); DWORD cchName = 0; // Size of the resulting name as a count of wchars LPWSTR lpszName = // Buffer to hold enumerated names (LPWSTR) LocalAlloc( LPTR, cbNameAlloc ); if (lpszName == NULL) { dwResult = GetLastError(); goto endf; } // Open enumeration handle. HRESENUM hResEnum = ClusterResourceOpenEnum( hRes, dwType ); if (hResEnum == NULL) { dwResult = GetLastError(); goto endf; } while(dwResult == ERROR_SUCCESS) { cchName = cbNameAlloc / sizeof( WCHAR ); dwResult = ClusterResourceEnum( hResEnum, dwIndex, &dwType, lpszName, &cchName); // Reallocate the name buffer if not big enough. if (dwResult == ERROR_MORE_DATA) { cchName++; // Leave room for terminating NULL. cbNameAlloc = cchName / sizeof( WCHAR ); LocalFree( lpszName ); lpszName = (LPWSTR) LocalAlloc( LPTR, cbNameAlloc ); if ( lpszName == NULL ) { dwResult = GetLastError(); goto endf; } dwResult = ClusterResourceEnum( hResEnum, dwIndex, &dwType, lpszName, &cchName ); } if( dwResult == ERROR_SUCCESS ) { int nItem = FindDependency(lpszName, m_ResourceListCtrl); if (nItem >= 0) MoveItem(nItem, /*from*/m_ResourceListCtrl, /*to*/m_DependencyListCtrl); } else if( dwResult == ERROR_NO_MORE_ITEMS ) { break; } else // enum failed for another reason { dwResult = GetLastError(); goto endf; } dwIndex++; } // End while. endf: CloseClusterResource(hRes); }
//加载信息 bool CUserInformation::LoadInformation() { //变量定义 IStream * pIStreamSub=NULL; IStorage * pIStorageSub=NULL; IStorage * pIStorageRoot=NULL; IEnumSTATSTG * pIEnumSTATSTG=NULL; //读取数据 try { //变量定义 STATSTG Statstg; tagCompanionInfo CompanionInfo; ZeroMemory(&Statstg,sizeof(Statstg)); ZeroMemory(&CompanionInfo,sizeof(CompanionInfo)); //工作目录 TCHAR szDirectory[MAX_PATH]=TEXT(""); CWHService::GetWorkDirectory(szDirectory,CountArray(szDirectory)); //打开文件 WCHAR szInfomationFile[MAX_PATH]=L""; _snwprintf(szInfomationFile,CountArray(szInfomationFile),L"%s\\%s",(LPCWSTR)(CT2CW(szDirectory)),INFORMATION_FILE); //打开文件 StgOpenStorage(szInfomationFile,NULL,STGM_READ|STGM_SHARE_EXCLUSIVE,0,0,&pIStorageRoot); if (pIStorageRoot==NULL) return false; //创建枚举 pIStorageRoot->EnumElements(0,NULL,0,&pIEnumSTATSTG); if (pIEnumSTATSTG==NULL) throw TEXT("EnumElements Create pIEnumSTATSTG Error"); //枚举对象 while (pIEnumSTATSTG->Next(1,&Statstg,NULL)==NOERROR) { //目录类型 if (Statstg.type==STGTY_STORAGE) { //打开存储 pIStorageRoot->OpenStorage(Statstg.pwcsName,NULL,STGM_READ|STGM_SHARE_EXCLUSIVE,0,0,&pIStorageSub); if (pIStorageSub==NULL) throw TEXT("CreateStorage Create pIStorageSub Error"); //打开数据 pIStorageSub->OpenStream(STREAM_COMPANION,NULL,STGM_READ|STGM_SHARE_EXCLUSIVE,0,&pIStreamSub); //读取数据 if (pIStreamSub!=NULL) { //读取关系 ULONG cbReadCount=0L; pIStreamSub->Read(&CompanionInfo,sizeof(CompanionInfo),&cbReadCount); //读取效验 ASSERT(cbReadCount==sizeof(CompanionInfo)); if (cbReadCount!=sizeof(CompanionInfo)) throw TEXT("Read Data CompanionInfo Error"); //创建对象 tagCompanionInfo * pCompanionInfo=CreateCompanionItem(); if (pCompanionInfo==NULL) throw TEXT("CreateCompanionItem Error"); //设置信息 CopyMemory(pCompanionInfo,&CompanionInfo,sizeof(CompanionInfo)); } //释放接口 SafeRelease(pIStreamSub); SafeRelease(pIStorageSub); } //释放内存 CoTaskMemFree(Statstg.pwcsName); } //释放接口 SafeRelease(pIEnumSTATSTG); SafeRelease(pIStreamSub); SafeRelease(pIStorageSub); SafeRelease(pIStorageRoot); return true; } catch (...) { //错误断言 ASSERT(FALSE); //释放接口 SafeRelease(pIEnumSTATSTG); SafeRelease(pIStreamSub); SafeRelease(pIStorageSub); SafeRelease(pIStorageRoot); } return false; }
//设置关系 tagCompanionInfo * CUserInformation::InsertCompanionInfo(IClientUserItem * pIClientUserItem, BYTE cbCompanion) { //效验参数 ASSERT(pIClientUserItem!=NULL); if (pIClientUserItem==NULL) return NULL; //用户搜索 DWORD dwUserID=pIClientUserItem->GetUserID(); tagCompanionInfo * pCompanionInfo=SearchCompanionInfo(dwUserID); //设置信息 if (pCompanionInfo==NULL) { //创建对象 pCompanionInfo=CreateCompanionItem(); if (pCompanionInfo==NULL) return NULL; //设置信息 pCompanionInfo->cbCompanion=cbCompanion; pCompanionInfo->dwGameID=pIClientUserItem->GetGameID(); pCompanionInfo->dwUserID=pIClientUserItem->GetUserID(); lstrcpyn(pCompanionInfo->szNickName,pIClientUserItem->GetNickName(),CountArray(pCompanionInfo->szNickName)); lstrcpyn(pCompanionInfo->szUserNote,pIClientUserItem->GetUserNoteInfo(),CountArray(pCompanionInfo->szUserNote)); //插入通知 if (m_pIUserCompanionSink!=NULL) m_pIUserCompanionSink->OnCompanionInsert(pCompanionInfo); } else { //修改判断 bool bModify=false; if (pCompanionInfo->cbCompanion!=cbCompanion) bModify=true; if ((bModify==false)&&(lstrcmp(pCompanionInfo->szNickName,pIClientUserItem->GetNickName())!=0)) bModify=true; if ((bModify==false)&&(lstrcmp(pCompanionInfo->szUserNote,pIClientUserItem->GetUserNoteInfo())!=0)) bModify=true; //修改判断 if (bModify=false) return pCompanionInfo; //设置信息 pCompanionInfo->cbCompanion=cbCompanion; pCompanionInfo->dwGameID=pIClientUserItem->GetGameID(); pCompanionInfo->dwUserID=pIClientUserItem->GetUserID(); lstrcpyn(pCompanionInfo->szNickName,pIClientUserItem->GetNickName(),CountArray(pCompanionInfo->szNickName)); lstrcpyn(pCompanionInfo->szUserNote,pIClientUserItem->GetUserNoteInfo(),CountArray(pCompanionInfo->szUserNote)); //更新通知 if (m_pIUserCompanionSink!=NULL) m_pIUserCompanionSink->OnCompanionUpdate(pCompanionInfo); } //变量定义 IStream * pIStreamSub=NULL; IStorage * pIStorageSub=NULL; IStorage * pIStorageRoot=NULL; //写入数据 try { //构造名字 WCHAR szStorageName[16]=L""; _snwprintf(szStorageName,CountArray(szStorageName),L"%ld",dwUserID); //工作目录 TCHAR szDirectory[MAX_PATH]=TEXT(""); CWHService::GetWorkDirectory(szDirectory,CountArray(szDirectory)); //打开文件 WCHAR szInfomationFile[MAX_PATH]=L""; _snwprintf(szInfomationFile,CountArray(szInfomationFile),L"%s\\%s",(LPCWSTR)(CT2CW(szDirectory)),INFORMATION_FILE); //打开文件 StgOpenStorage(szInfomationFile,NULL,STGM_READWRITE|STGM_SHARE_EXCLUSIVE,0,0,&pIStorageRoot); if (pIStorageRoot==NULL) StgCreateDocfile(szInfomationFile,STGM_CREATE|STGM_READWRITE|STGM_SHARE_EXCLUSIVE,0,&pIStorageRoot); //错误判断 if (pIStorageRoot==NULL) throw TEXT("StgCreateDocfile Create pIStorageRoot Error"); //打开存储 pIStorageRoot->CreateStorage(szStorageName,STGM_WRITE|STGM_SHARE_EXCLUSIVE,0,0,&pIStorageSub); if (pIStorageSub==NULL) pIStorageRoot->CreateStorage(szStorageName,STGM_CREATE|STGM_WRITE|STGM_SHARE_EXCLUSIVE,0,0,&pIStorageSub); //错误处理 if (pIStorageSub==NULL) throw TEXT("CreateStorage Create pIStorageSub Error"); //创建数据 pIStorageSub->CreateStream(STREAM_COMPANION,STGM_WRITE|STGM_SHARE_EXCLUSIVE,0,0,&pIStreamSub); if (pIStreamSub==NULL) pIStorageSub->CreateStream(STREAM_COMPANION,STGM_CREATE|STGM_WRITE|STGM_SHARE_EXCLUSIVE,0,0,&pIStreamSub); //错误处理 if (pIStreamSub==NULL) throw TEXT("CreateStream Create pIStreamSub Error"); //写入数据 ULONG cbWriteCount=0L; pIStreamSub->Write(pCompanionInfo,sizeof(tagCompanionInfo),&cbWriteCount); //释放接口 SafeRelease(pIStreamSub); SafeRelease(pIStorageSub); SafeRelease(pIStorageRoot); return pCompanionInfo; } catch (...) { //错误断言 ASSERT(FALSE); //释放接口 SafeRelease(pIStreamSub); SafeRelease(pIStorageSub); SafeRelease(pIStorageRoot); } return NULL; }