// static void XPCThrower::ThrowCOMError(JSContext* cx, unsigned long COMErrorCode, nsresult rv, const EXCEPINFO * exception) { nsCAutoString msg; IErrorInfo * pError; const char * format; if(!nsXPCException::NameAndFormatForNSResult(rv, nsnull, &format)) format = ""; msg = format; #ifndef WINCE if(exception) { msg += static_cast<const char *> (_bstr_t(exception->bstrSource, false)); msg += " : "; msg.AppendInt(static_cast<PRUint32>(COMErrorCode)); msg += " - "; msg += static_cast<const char *> (_bstr_t(exception->bstrDescription, false)); } else { // Get the current COM error object unsigned long result = GetErrorInfo(0, &pError); if(SUCCEEDED(result) && pError) { // Build an error message from the COM error object BSTR bstrSource = NULL; if(SUCCEEDED(pError->GetSource(&bstrSource)) && bstrSource) { _bstr_t src(bstrSource, false); msg += static_cast<const char *>(src); msg += " : "; } msg.AppendInt(static_cast<PRUint32>(COMErrorCode), 16); BSTR bstrDesc = NULL; if(SUCCEEDED(pError->GetDescription(&bstrDesc)) && bstrDesc) { msg += " - "; _bstr_t desc(bstrDesc, false); msg += static_cast<const char *>(desc); } } else { // No error object, so just report the result msg += "COM Error Result = "; msg.AppendInt(static_cast<PRUint32>(COMErrorCode), 16); } } #else // No error object, so just report the result msg += "COM Error Result = "; msg.AppendInt(static_cast<PRUint32>(COMErrorCode), 16); #endif XPCThrower::BuildAndThrowException(cx, rv, msg.get()); }
/*---------------------------------------------------------------------------------------------- Static method to find a class factory (from the given CLSID) from all the class factories that are in the linked list. If the requested class factory is not found, *ppv is set to NULL and CLASS_E_CLASSNOTAVAILABLE is returned. ----------------------------------------------------------------------------------------------*/ HRESULT ModuleEntry::ModuleGetClassObject(REFCLSID clsid, REFIID iid, void ** ppv) { AssertPtrN(ppv); if (!ppv) return WarnHr(E_POINTER); *ppv = NULL; // This block of code is largely copied from the AssertNoErrorInfo method in throwable.h. // Here, however, we don't assert, but just dump a warning to the output window and // discard the spurious error info. This prevents asserts if Windows.Forms calls // a class factory (as it has been known to do) with spurious error info registered. #ifdef DEBUG IErrorInfo * pIErrorInfo = NULL; HRESULT hr = GetErrorInfo(0, &pIErrorInfo); Assert(SUCCEEDED(hr)); if(pIErrorInfo != NULL) { BSTR bstr; hr = pIErrorInfo->GetDescription(&bstr); Assert(SUCCEEDED(hr)); ::OutputDebugString(bstr); ::SysFreeString(bstr); hr = pIErrorInfo->GetSource(&bstr); Assert(SUCCEEDED(hr)); ::OutputDebugString(bstr); ::SysFreeString(bstr); pIErrorInfo->Release(); } #endif ModuleEntry * pme; try { for (pme = s_pmeFirst; pme; pme = pme->m_pobjNext) { AssertPtr(pme); pme->GetClassFactory(clsid, iid, ppv); if (*ppv) return S_OK; } } catch (const Throwable & thr) { return thr.Error(); } catch (...) { return WarnHr(E_FAIL); } return CLASS_E_CLASSNOTAVAILABLE; }
// The CreateExternalException function uses GetErrorInfo function to get // COM error information and then creates Exception with the error description. ExternalException* CreateExternalException() { IErrorInfo* errInfo; BSTR descriptionBStr; std::string descriptionStr; if (GetErrorInfo(0, &errInfo) == S_OK) { errInfo->GetDescription(&descriptionBStr); descriptionStr = MultiByteStringFromWideString(descriptionBStr); ::SysFreeString(descriptionBStr); } return new ExternalException(descriptionStr); }
//////////////////////////////////////////////////////////////////////// // HRESULT DisplayErrorRecords // ///////////////////////////////////////////////////////////////////////////// HRESULT DisplayErrorRecords(HWND hWnd, ULONG cRecords, IErrorRecords* pIErrorRecords, WCHAR* pwszFile, ULONG ulLine) { HRESULT hr = S_OK; IErrorInfo* pIErrorInfo = NULL; BSTR bstrErrorInfo = NULL; BSTR bstrSQLInfo = NULL; LCID lcid = GetSystemDefaultLCID(); //Get the Error Records if(cRecords && pIErrorRecords) { LONG lNativeError = 0; ERRORINFO ErrorInfo; //Loop through the records for(ULONG i=0; i<cRecords; i++) { //GetErrorInfo XTESTC(hr = pIErrorRecords->GetErrorInfo(i,lcid,&pIErrorInfo)); //Get the Description XTESTC(hr = pIErrorInfo->GetDescription(&bstrErrorInfo)); //Get the Basic ErrorInfo XTESTC(hr = pIErrorRecords->GetBasicErrorInfo(i,&ErrorInfo)); //Get the SQL Info GetSqlErrorInfo(i, pIErrorRecords, &bstrSQLInfo); //Display the Error if(bstrSQLInfo) wMessageBox(hWnd, (hWnd ? MB_APPLMODAL : MB_TASKMODAL) | MB_ICONEXCLAMATION | MB_OK, wsz_ERRORINFO, L"Interface: %s\nResult: %x = %s\n\nIErrorInfo: [%s] %s\n\nFile: %s\nLine: %d", GetInterfaceName(ErrorInfo.iid), ErrorInfo.hrError, GetErrorName(ErrorInfo.hrError), bstrSQLInfo, bstrErrorInfo, pwszFile, ulLine); else wMessageBox(hWnd, (hWnd ? MB_APPLMODAL : MB_TASKMODAL) | MB_ICONEXCLAMATION | MB_OK, wsz_ERRORINFO, L"Interface: %s\nResult: %x = %s\n\nIErrorInfo: %s\n\nFile: %s\nLine: %d", GetInterfaceName(ErrorInfo.iid), ErrorInfo.hrError, GetErrorName(ErrorInfo.hrError), bstrErrorInfo, pwszFile, ulLine); SAFE_RELEASE(pIErrorInfo); SAFE_SYSFREE(bstrErrorInfo); SAFE_SYSFREE(bstrSQLInfo); } } CLEANUP: SAFE_RELEASE(pIErrorInfo); SAFE_SYSFREE(bstrErrorInfo); SAFE_SYSFREE(bstrSQLInfo); return hr; }
void OutErrorInfo(IUnknown *pUnk) { IErrorInfo *pErr; HRESULT hr = pUnk->QueryInterface(IID_IErrorInfo, (void **)&pErr); if(SUCCEEDED(hr)) { BSTR desc; pErr->GetDescription(&desc); OutputDebugString(desc); OutputDebugString(_T("\n")); SysFreeString(desc); } else { OutputDebugString(_T("Error is Unknown...\n")); } }
tscrypto::tsCryptoString COMMessage(HRESULT hr) { tscrypto::tsCryptoString sHr; switch (hr) { case S_OK: sHr = "OK"; break; case S_FALSE: sHr = "FALSE"; break; case E_NOTIMPL: sHr = "Not Implemented"; break; case E_UNEXPECTED: sHr = "Unexpected operation"; break; case E_OUTOFMEMORY: sHr = "Out Of Memory"; break; case E_INVALIDARG: sHr = "Invalid Argument"; break; case E_NOINTERFACE: sHr = "No Interface"; break; case E_POINTER: sHr = "Invalid Pointer"; break; case E_HANDLE: sHr = "Invalid Handle"; break; case E_ABORT: sHr = "Aborted"; break; case E_FAIL: sHr = "General Failure"; break; case E_ACCESSDENIED: sHr = "Access Denied"; break; case E_PENDING: sHr = ""; break; default: sHr.Format("0x%08X", hr); break; } #ifndef NO_IDISPATCH if (FAILED(hr)) { IErrorInfo* pErrInfo = nullptr; if (::GetErrorInfo(0, &pErrInfo) == S_OK) { BSTR tmp = nullptr; if (SUCCEEDED(pErrInfo->GetDescription(&tmp))) sHr << " - " << CryptoUtf16(tmp).toUtf8(); SysFreeString(tmp); pErrInfo->Release(); } } #endif // NO_IDISPATCH return sHr; }
int die (char const * szError, HRESULT hr) { fprintf (stderr, "\nDIE: %s\n", szError); fflush (stderr); if (hr != S_OK) { IErrorInfo * pIErr = NULL; BSTR bstrDesc = NULL; fprintf (stderr, "HRESULT = 0x%08x\n", hr); if (GetErrorInfo (0, &pIErr) == S_OK && pIErr->GetDescription (&bstrDesc) == S_OK) { fprintf (stderr, "%ls", bstrDesc); fflush (stderr); SysFreeString (bstrDesc); } if (pIErr) pIErr->Release(); } CoUninitialize(); exit (hr); }
int _tmain(int argc, _TCHAR* argv[]) { HRESULT hr; // COM 戻り値用変数 IClassTest* pClassTest; // COMインターフェイスポインタ // COMの初期化 ◆◆追加 hr = ::CoInitialize(NULL); if(FAILED(hr)){ printf("CoInitialize 失敗\n"); return 0; } // ---------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------- // <以下のコードは、アーリーバインディング方式での呼び出し> // インスタンスの作成(CLSID:[CLSID_ClassTest]とIID:[IID_IClassTest]を指定して、ポインタを取得) hr = ::CoCreateInstance((REFCLSID) CLSID_ClassTest, 0, CLSCTX_INPROC_SERVER, (REFIID) IID_IClassTest, (LPVOID*)&pClassTest); if(FAILED(hr)){ printf("CoCreateInstance 失敗\n"); return 0; } // BSTRを処理する場合は、_bstr_tが楽(解放など) // http://mzs184.blogspot.com/2008/04/bstrbstrt.html // _bstr_t Class // http://msdn.microsoft.com/ja-jp/library/zthfhkd6.aspx // _bstr_t::operator = // http://msdn.microsoft.com/ja-jp/library/7bh2f8sk.aspx _bstr_t bstrText = L"だいすけ"; _bstr_t bstrCaption = L"にしの"; _bstr_t bstrRetVal; // メソッド呼び出し // _bstr_t::wchar_t*, _bstr_t::char* // BSTRはOLECHAR(= WCHAR)のポインタなので適用可能。 // http://msdn.microsoft.com/ja-jp/library/btdzb8eb.aspx // _bstr_t::GetAddress // http://msdn.microsoft.com/ja-jp/library/t2x13207.aspx hr = pClassTest->MethodTest(bstrText, bstrCaption, bstrRetVal.GetAddress()); if(FAILED(hr)){ printf("MethodTest 失敗\n"); return 0; } MessageBox(NULL, bstrRetVal, L"戻り値", MB_OK); // bstrRetValをクリア(DetachしてSysFreeString) // _bstr_t::Detach // http://msdn.microsoft.com/en-us/library/3c73x1sf.aspx // SysFreeString // http://msdn.microsoft.com/ja-jp/site/ms221481 BSTR bstr = bstrRetVal.Detach(); if(bstr != NULL) { SysFreeString(bstr); } // bstrCaptionの再設定 bstrCaption = L""; // メソッド呼び出し(同上) hr = pClassTest->MethodTest(bstrText, bstrCaption, bstrRetVal.GetAddress()); // Dr.GUI Online // Dr.GUI と COM オートメーション、 // 第 3 部:続 COM のすばらしきデータ型 // http://msdn.microsoft.com/ja-jp/library/cc482694.aspx // ISupportErrorInfo、IErrorInfoでエラー情報を取得 if(FAILED(hr)) { // IID_ISupportErrorInfoインターフェイスを取得 ISupportErrorInfo *pSupport; hr = pClassTest->QueryInterface(IID_ISupportErrorInfo, (void**)&pSupport); if (SUCCEEDED(hr)) { hr = pSupport->InterfaceSupportsErrorInfo(IID_IClassTest); if (hr == S_OK) { // can't use SUCCEEDED here! S_FALSE succeeds! IErrorInfo *pErrorInfo; hr = GetErrorInfo(0, &pErrorInfo); if (SUCCEEDED(hr)) { // FINALLY can call methods on pErrorInfo! ...and handle the error! _bstr_t bstrErrorDescription; pErrorInfo->GetDescription(bstrErrorDescription.GetAddress()); // エラー情報 MessageBox(NULL, bstrErrorDescription, L"ErrorDescription", MB_OK); // don't forget to release! pErrorInfo->Release(); } } // don't forget to release! pSupport->Release(); } } // don't forget to release! pClassTest->Release(); // ---------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------- // <以下のコードは、レイトバインディング方式での呼び出し> // CLSID の取得 CLSID clsid; hr = CLSIDFromProgID(L"VC_COM.ClassTest", &clsid); if(FAILED(hr)){ printf("CLSIDFromProgID 失敗\n"); return 0; } // インスタンスの作成(CLSIDとIID:[IID_IDispatch]を指定して、ポインタを取得) IDispatch* pDisp = NULL; hr = ::CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IDispatch, (void**)&pDisp); if(FAILED(hr)){ printf("CoCreateInstance 失敗\n"); return 0; } // COMディスパッチ識別子の取得 DISPID dispID; OLECHAR* wszName = L"MethodTest"; hr = pDisp->GetIDsOfNames(IID_NULL, &wszName, 1, LOCALE_USER_DEFAULT, &dispID); if(FAILED(hr)){ printf("GetIDsOfNames 失敗\n"); exit(1); } // CComVariant クラス(CComVariant は VARIANT 型から派生) // http://msdn.microsoft.com/ja-jp/library/ac97df2h.aspx // 引数を VARIANT 配列に設定 CComVariant pvArgs[2]; pvArgs[0] = L"だいすけ"; pvArgs[1] = L"にしの"; // 戻り値を VARIANT変数 CComVariant pvResult; // DISPPARAMS の設定 DISPPARAMS dispParams; dispParams.rgvarg = pvArgs; dispParams.rgdispidNamedArgs = NULL; dispParams.cArgs = 2; dispParams.cNamedArgs = 0; // メソッドにレイトバインド(Invoke) hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispParams, &pvResult, NULL, NULL); if(FAILED(hr)){ printf("MethodTest 失敗\n"); return 0; } // BSTRで格納されている時、tagVARIANTのメンバ、bstrValで取得可能。 // BSTRはOLECHAR(= WCHAR)のポインタなのでLPWSTRにキャスト可能。 MessageBox(NULL, (LPWSTR)pvResult.bstrVal, L"戻り値", MB_OK); // don't forget to release! pDisp->Release(); // ---------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------- // COMの終了処理 ◆◆追加 ::CoUninitialize(); return 0; }
// Info: Gets both unrestricted and restricted error info // Parameters: scriptContext - the script context // pexcepinfo - the exception info of the error (unrestricted) // proerrstr - the winrt specific error strings (restricted) // pperrinfo - the IErrorInfo object // Returns: Failed HRESULT - if GetErrorInfo or QI fail // Success - otherwise HRESULT JavascriptErrorDebug::GetExcepAndErrorInfo(ScriptContext* scriptContext, HRESULT hrReturned, EXCEPINFO *pexcepinfo, RestrictedErrorStrings * proerrstr, IErrorInfo ** pperrinfo) { HRESULT hr; HRESULT hrResult; bool errorInfoMatch = false; memset(pexcepinfo, 0, sizeof(*pexcepinfo)); memset(proerrstr, 0, sizeof(*proerrstr)); *pperrinfo = nullptr; // GetErrorInfo returns S_FALSE if there is no rich error info // and S_OK if there is. IErrorInfo * perrinfo; if(NOERROR != (hr = GetErrorInfo(0L, &perrinfo))) { return hr; } // Fill Exception info perrinfo->GetSource(&pexcepinfo->bstrSource); perrinfo->GetDescription(&pexcepinfo->bstrDescription); perrinfo->GetHelpFile(&pexcepinfo->bstrHelpFile); perrinfo->GetHelpContext(&pexcepinfo->dwHelpContext); // Initialize restricted strings proerrstr->restrictedErrStr = nullptr; proerrstr->referenceStr = nullptr; proerrstr->capabilitySid = nullptr; BSTR bstrErr = nullptr; BSTR bstrRestrictedErr = nullptr; BSTR bstrCapabilitySid = nullptr; BSTR bstrReference = nullptr; IRestrictedErrorInfo * pROErrorInfo = nullptr; _Exception * pCLRException = nullptr; hr = perrinfo->QueryInterface(__uuidof(IRestrictedErrorInfo), reinterpret_cast<void**>(&pROErrorInfo)); if (SUCCEEDED(hr)) { // Get restricted error strings from IRestrictedErrorInfo HRESULT hrErr = S_OK; hrResult = pROErrorInfo->GetErrorDetails(&bstrErr, &hrErr, &bstrRestrictedErr, &bstrCapabilitySid); if (SUCCEEDED(hrResult)) { errorInfoMatch = (hrErr == hrReturned); if (errorInfoMatch) { if (nullptr != bstrRestrictedErr) { proerrstr->restrictedErrStr = bstrRestrictedErr; bstrRestrictedErr = nullptr; } if (nullptr != bstrCapabilitySid) { proerrstr->capabilitySid = bstrCapabilitySid; bstrCapabilitySid = nullptr; } } } hrResult = pROErrorInfo->GetReference(&bstrReference); if (SUCCEEDED(hrResult) && errorInfoMatch) { if (nullptr != bstrReference) { proerrstr->referenceStr = bstrReference; bstrReference = nullptr; } } } else { hr = perrinfo->QueryInterface(__uuidof(_Exception), reinterpret_cast<void**>(&pCLRException)); if(FAILED(hr)) { perrinfo->Release(); return hr; } hrResult = pCLRException->get_Message(&bstrRestrictedErr); if (SUCCEEDED(hrResult)) { errorInfoMatch = true; if (nullptr != bstrRestrictedErr) { proerrstr->restrictedErrStr = bstrRestrictedErr; bstrRestrictedErr = nullptr; } } } if (nullptr != bstrErr) { SysFreeString(bstrErr); bstrErr = nullptr; } if (nullptr != bstrRestrictedErr) { SysFreeString(bstrRestrictedErr); bstrRestrictedErr = nullptr; } if (nullptr != bstrCapabilitySid) { SysFreeString(bstrCapabilitySid); bstrCapabilitySid = nullptr; } if (nullptr != bstrReference) { SysFreeString(bstrReference); bstrReference = nullptr; } if (!errorInfoMatch) { if (nullptr != pexcepinfo->bstrSource) { SysFreeString(pexcepinfo->bstrSource); pexcepinfo->bstrSource = nullptr; } if (nullptr != pexcepinfo->bstrDescription) { SysFreeString(pexcepinfo->bstrDescription); pexcepinfo->bstrDescription = nullptr; } if (nullptr != pexcepinfo->bstrHelpFile) { SysFreeString(pexcepinfo->bstrHelpFile); pexcepinfo->bstrHelpFile = nullptr; } perrinfo->Release(); perrinfo = nullptr; hr = S_FALSE; } if (nullptr != pROErrorInfo) { pROErrorInfo->Release(); } if (nullptr != pCLRException) { pCLRException->Release(); } *pperrinfo = perrinfo; return hr; }
/* * Generic COM error reporting function. */ static void comReportError(bpContext *ctx, HRESULT hrErr) { IErrorInfo *pErrorInfo; BSTR pSource = NULL; BSTR pDescription = NULL; HRESULT hr; char *source, *description; /* * See if there is anything to report. */ hr = GetErrorInfo(0, &pErrorInfo); if (hr == S_FALSE) { return; } /* * Get the description of the COM error. */ hr = pErrorInfo->GetDescription(&pDescription); if (!SUCCEEDED (hr)) { pErrorInfo->Release(); return; } /* * Get the source of the COM error. */ hr = pErrorInfo->GetSource(&pSource); if (!SUCCEEDED (hr)) { SysFreeString(pDescription); pErrorInfo->Release(); return; } /* * Convert windows BSTR to normal strings. */ source = BSTR_2_str(pSource); description = BSTR_2_str(pDescription); if (source && description) { Jmsg(ctx, M_FATAL, "%s(x%X): %s\n", source, hrErr, description); Dmsg(ctx, dbglvl, "%s(x%X): %s\n", source, hrErr, description); } if (source) { free(source); } if (description) { free(description); } /* * Generic cleanup (free the description and source as those are returned in * dynamically allocated memory by the COM routines.) */ SysFreeString(pSource); SysFreeString(pDescription); pErrorInfo->Release(); }
//Changed from //ms-help://MS.SSC.v35/MS.SSC.v35.EN/ssctechref/html/a25fafe1-e90a-4545-8836-749dd44135c0.htm CString SqlCeHelper::GetErrorsMessage() { static CString sErrIErrorInfo = L"IErrorInfo interface"; static CString sErrIErrorRecords = L"IErrorRecords interface"; static CString sErrRecordCount = L"error record count"; static CString sErrInfo = L"ERRORINFO structure"; static CString sErrStandardInfo = L"standard error info"; static CString sErrDescription = L"standard error description"; static CString sErrNoSource = L"error source"; HRESULT hr = S_OK; IErrorInfo *pIErrorInfo = NULL; IErrorRecords *pIErrorRecords = NULL; ERRORINFO errorInfo = { 0 }; IErrorInfo *pIErrorInfoRecord = NULL; CString message = L""; char str[255]; try { // This interface supports returning error information. // Get the error object from the system for the current // thread. hr = GetErrorInfo(0, &pIErrorInfo); if ( hr == S_FALSE ) { message = "No error occured."; return message; } if(FAILED(hr) || NULL == pIErrorInfo) throw sErrIErrorInfo; // The error records are retrieved from the IIErrorRecords // interface, which can be obtained from the IErrorInfo // interface. hr = pIErrorInfo->QueryInterface(IID_IErrorRecords, (void **) &pIErrorRecords); if ( FAILED(hr) || NULL == pIErrorRecords ) throw sErrIErrorRecords; // The IErrorInfo interface is no longer required because // we have the IErrorRecords interface, relase it. pIErrorInfo->Release(); pIErrorInfo = NULL; ULONG ulNumErrorRecs = 0; // Determine the number of records in this error object hr = pIErrorRecords->GetRecordCount(&ulNumErrorRecs); if ( FAILED(hr) ) throw sErrRecordCount; // Loop over each error record in the error object to display // information about each error. Errors are returned. for (DWORD dwErrorIndex = 0; dwErrorIndex < ulNumErrorRecs; dwErrorIndex++) { // Retrieve basic error information for this error. hr = pIErrorRecords->GetBasicErrorInfo(dwErrorIndex, &errorInfo); if ( FAILED(hr) ) throw sErrInfo; TCHAR szCLSID[64] = { 0 }; TCHAR szIID[64] = { 0 }; TCHAR szDISPID[64] = { 0 }; StringFromGUID2(errorInfo.clsid, (LPOLESTR)szCLSID, sizeof(szCLSID)); StringFromGUID2(errorInfo.iid, (LPOLESTR)szIID, sizeof(szIID)); sprintf(str, "HRESULT = %lx\n", errorInfo.hrError); message += str; sprintf(str, "clsid = %S\n", szCLSID); message += str; sprintf(str, "iid = %S\n", szIID); message += str; sprintf(str, "dispid = %ld\n", errorInfo.dispid); message += str; sprintf(str, "Native Error Code = %lx\n", errorInfo.dwMinor); message += str; // Retrieve standard error information for this error. hr = pIErrorRecords->GetErrorInfo(dwErrorIndex, NULL, &pIErrorInfoRecord); if ( FAILED(hr) ) throw sErrStandardInfo; BSTR bstrDescriptionOfError; BSTR bstrSourceOfError; // Get the description of the error. hr = pIErrorInfoRecord->GetDescription( &bstrDescriptionOfError); if ( FAILED(hr) ) throw sErrDescription; sprintf(str, "Description = %S\n", bstrDescriptionOfError); message += str; // Get the source of the error. hr = pIErrorInfoRecord->GetSource(&bstrSourceOfError); if ( FAILED(hr) ) throw sErrNoSource; sprintf(str, "Description = %S\n", bstrSourceOfError); message += str; // This interface variable will be used the next time // though this loop. In the last error case this interface // is no longer needed so we must release it. if(NULL != pIErrorInfoRecord) pIErrorInfoRecord->Release(); pIErrorInfoRecord = NULL; } } catch( CString& szMsg ) { message = L"Failed to retrieve " + szMsg; } if( pIErrorInfoRecord ) pIErrorInfoRecord->Release(); if ( pIErrorInfo ) pIErrorInfo->Release(); if ( pIErrorRecords ) pIErrorRecords->Release(); return message; }
//////////////////////////////////////////////////////////////////////// // myDisplayErrorRecord // // This function displays the error information for a single error // record, including information from ISQLErrorInfo, if supported // //////////////////////////////////////////////////////////////////////// HRESULT myDisplayErrorRecord ( HRESULT hrReturned, ULONG iRecord, IErrorRecords * pIErrorRecords, LPCWSTR pwszFile, ULONG ulLine ) { HRESULT hr; IErrorInfo * pIErrorInfo = NULL; BSTR bstrDescription = NULL; BSTR bstrSource = NULL; BSTR bstrSQLInfo = NULL; static LCID lcid = GetUserDefaultLCID(); LONG lNativeError = 0; ERRORINFO ErrorInfo; // Get the IErrorInfo interface pointer for this error record CHECK_HR(hr = pIErrorRecords->GetErrorInfo(iRecord, lcid, &pIErrorInfo)); // Get the description of this error CHECK_HR(hr = pIErrorInfo->GetDescription(&bstrDescription)); // Get the source of this error CHECK_HR(hr = pIErrorInfo->GetSource(&bstrSource)); // Get the basic error information for this record CHECK_HR(hr = pIErrorRecords->GetBasicErrorInfo(iRecord, &ErrorInfo)); // If the error object supports ISQLErrorInfo, get this information myGetSqlErrorInfo(iRecord, pIErrorRecords, &bstrSQLInfo, &lNativeError); // Display the error information to the user if( bstrSQLInfo ) { wprintf(L"\nErrorRecord: HResult: 0x%08x\nDescription: %s\n" L"SQLErrorInfo: %s\nSource: %s\nFile: %s, Line: %d\n", ErrorInfo.hrError, bstrDescription, bstrSQLInfo, bstrSource, pwszFile, ulLine); } else { wprintf(L"\nErrorRecord: HResult: 0x%08x\nDescription: %s\n" L"Source: %s\nFile: %s, Line: %d\n", ErrorInfo.hrError, bstrDescription, bstrSource, pwszFile, ulLine); } CLEANUP: if( pIErrorInfo ) pIErrorInfo->Release(); SysFreeString(bstrDescription); SysFreeString(bstrSource); SysFreeString(bstrSQLInfo); return hr; }
int ipmi_cmdraw_ms(uchar cmd, uchar netfn, uchar lun, uchar sa, uchar bus, uchar *pdata, int sdata, uchar *presp, int *sresp, uchar *pcc, char fdebugcmd) { int bRet; HRESULT hres; IWbemClassObject* pInParams = NULL; /*class definition*/ IWbemClassObject* pInReq = NULL; /*instance*/ IWbemClassObject* pOutResp = NULL; VARIANT varCmd, varNetfn, varLun, varSa, varSize, varData; SAFEARRAY* psa = NULL; long i; uchar *p; fdebugms = fdebugcmd; if (!fmsopen) { bRet = ipmi_open_ms(fdebugcmd); if (bRet != 0) return(bRet); } bRet = -1; hres = pClass->GetMethod(L"RequestResponse",0,&pInParams,NULL); if (FAILED(hres)) { if (fdebugcmd) printf("ipmi_cmdraw_ms: Cannot get RequestResponse method\n"); return (bRet); } #ifdef WDM_FIXED /* see http://support.microsoft.com/kb/951242 for WDM bug info */ hres = pInParams->SpawnInstance(0,&pInReq); if (FAILED(hres)) { if (fdebugcmd) printf("ipmi_cmdraw_ms: Cannot get RequestResponse instance\n"); return (bRet); } // also substitute pInReq for pInParams below if this gets fixed. #endif VariantInit(&varCmd); varCmd.vt = VT_UI1; varCmd.bVal = cmd; hres = pInParams->Put(_bstr_t(L"Command"), 0, &varCmd, 0); // VariantClear(&varCmd); if (FAILED(hres)) goto MSRET; VariantInit(&varNetfn); varNetfn.vt = VT_UI1; varNetfn.bVal = netfn; hres = pInParams->Put(_bstr_t(L"NetworkFunction"), 0, &varNetfn, 0); // VariantClear(&varNetfn); if (FAILED(hres)) goto MSRET; VariantInit(&varLun); varLun.vt = VT_UI1; varLun.bVal = lun; hres = pInParams->Put(_bstr_t(L"Lun"), 0, &varLun, 0); // VariantClear(&varLun); if (FAILED(hres)) goto MSRET; VariantInit(&varSa); varSa.vt = VT_UI1; varSa.bVal = sa; hres = pInParams->Put(_bstr_t(L"ResponderAddress"), 0, &varSa, 0); // VariantClear(&varSa); if (FAILED(hres)) goto MSRET; VariantInit(&varSize); varSize.vt = VT_I4; varSize.lVal = sdata; hres = pInParams->Put(_bstr_t(L"RequestDataSize"), 0, &varSize, 0); // VariantClear(&varSize); if (FAILED(hres)) goto MSRET; SAFEARRAYBOUND rgsabound[1]; rgsabound[0].cElements = sdata; rgsabound[0].lLbound = 0; psa = SafeArrayCreate(VT_UI1,1,rgsabound); if(!psa) { printf("ipmi_cmdraw_ms: SafeArrayCreate failed\n"); goto MSRET; } #ifdef SHOULD_WORK_BUT_NO /* The SafeArrayPutElement does not put the data in the right * place, so skip this and copy the raw data below. */ VARIANT tvar; if (fdebugcmd && sdata > 0) { printf("psa1(%p):",psa); dumpbuf((uchar *)psa,42,1); } for(i =0; i< sdata; i++) { VariantInit(&tvar); tvar.vt = VT_UI1; tvar.bVal = pdata[i]; hres = SafeArrayPutElement(psa, &i, &tvar); // VariantClear(&tvar); if (FAILED(hres)) { printf("ipmi_cmdraw_ms: SafeArrayPutElement(%d) failed\n",i); goto MSRET; } } /*end for*/ if (fdebugcmd && sdata > 0) { printf("psa2(%p):",psa); dumpbuf((uchar *)psa,42,1); } #endif /* Copy the real RequestData into psa */ memcpy(psa->pvData,pdata,sdata); VariantInit(&varData); varData.vt = VT_ARRAY | VT_UI1; varData.parray = psa; hres = pInParams->Put(_bstr_t(L"RequestData"), 0, &varData, 0); // VariantClear(&varData); if (FAILED(hres)) { printf("Put(RequestData) error %x\n",hres); goto MSRET; } #ifdef TEST_METHODS IWbemClassObject* pOutSms = NULL; if (fdebugcmd) printf("ipmi_cmdraw_ms: calling SMS_Attention(%ls)\n", V_BSTR(&varPath)); hres = pSvc->ExecMethod( V_BSTR(&varPath), _bstr_t(L"SMS_Attention"), 0, NULL, NULL, &pOutSms, NULL); if (FAILED(hres)) { printf("ipmi_cmdraw_ms: SMS_Attention method error %x\n",hres); goto MSRET; } if (fdebugcmd) printf("ipmi_cmdraw_ms: SMS_Attention method ok\n"); /* This does work, without input parameters */ pOutSms->Release(); #endif hres = pSvc->ExecMethod( V_BSTR(&varPath), _bstr_t(L"RequestResponse"), 0, NULL, pInParams, &pOutResp, NULL); if (fdebugcmd) { printf("ipmi_cmdraw_ms(cmd=%x,netfn=%x,lun=%x,sa=%x,sdata=%d)" " RequestResponse ret=%x\n", cmd,netfn,lun,sa,sdata,hres); if (sdata > 0) { printf("ipmi_cmdraw_ms: req data(%d):",sdata); dumpbuf(pdata,sdata,0); } } if (FAILED(hres)) { printf("ipmi_cmdraw_ms: RequestResponse error %x %s\n", hres,res_str(hres)); #ifdef EXTRA_DESC /* This does not usually add any meaning for IPMI. */ BSTR desc; IErrorInfo *pIErrorInfo; GetErrorInfo(0,&pIErrorInfo); pIErrorInfo->GetDescription(&desc); printf("ipmi_cmdraw_ms: ErrorInfoDescr: %ls\n",desc); SysFreeString(desc); #endif bRet = -1; /*fall through for cleanup and return*/ } else { /*successful, get ccode and response data */ VARIANT varByte, varRSz, varRData; VariantInit(&varByte); VariantInit(&varRSz); VariantInit(&varRData); long rlen; hres = pOutResp->Get(_bstr_t(L"CompletionCode"),0, &varByte, NULL, 0); if (FAILED(hres)) goto MSRET; if (fdebugcmd) printf("ipmi_cmdraw_ms: CompletionCode %x returned\n", V_UI1(&varByte) ); *pcc = V_UI1(&varByte); hres = pOutResp->Get(_bstr_t(L"ResponseDataSize"),0, &varRSz, NULL, 0); if (FAILED(hres)) goto MSRET; rlen = V_I4(&varRSz); if (rlen > 1) rlen--; /*skip cc*/ if (rlen > *sresp) { if (fdebugcmd) printf("ResponseData truncated from %d to %d\n", rlen,*sresp); rlen = *sresp; /*truncate*/ } *sresp = (int)rlen; hres = pOutResp->Get(_bstr_t(L"ResponseData"),0, &varRData, NULL,0); if (FAILED(hres)) { /*ignore failure */ if (fdebugcmd) printf("Get ResponseData error %x\n",hres); } else { /* success */ #ifdef SHOULD_WORK_BUT_NO uchar *pa; p = (uchar*)varRData.parray->pvData; pa = (uchar*)varRData.parray; printf("pa=%p, pa+12=%p p=%p\n",pa,(pa+12),p); if (fdebugcmd) { printf("Data.vt = %04x, Data.parray(%p):", varRData.vt, varRData.parray); // 0x2011 means VT_ARRAY | VT_UI1 dumpbuf((uchar *)varRData.parray,40,1); } /* The SafeArrayGetElement does not get the data from the right * place, so skip this and copy the raw data below. */ VARIANT rgvar[NVAR]; if (rlen > NVAR) *pcc = 0xEE; for (i = 0; i <= rlen; i++) VariantInit(&rgvar[i]); /* copy the response data from varRData to presp */ for( i = 0; i <= rlen; i++) { hres = SafeArrayGetElement(varRData.parray, &i, &rgvar[i]); if (FAILED(hres)) { if (fdebugcmd) printf("ipmi_cmdraw_ms: SafeArrayGetElement(%d) failed\n",i); break; } if (fdebugcmd) { printf("Data[%d] vt=%02x val=%02x, rgvar(%p):",i, rgvar[i].vt, V_UI1(&rgvar[i]),&rgvar[i]); dumpbuf((uchar *)&rgvar[i],12,0); } /* skip the completion code */ // if (i > 0) presp[i-1] = V_UI1(&rgvar[i]); } /*end for*/ #endif /* * parray from a GetDeviceId response: * 0015CEE0: 01 00 80 00 01 00 00 00 00 00 00 00 00 cf 15 00 * 0015CEF0: 10 00 00 00 00 00 00 00 03 00 06 00 95 01 08 00 * ^- datalen=0x10 * 0015CF00: 00 20 01 00 19 02 9f 57 01 ... * ^- start of data (cc=00, ...) */ /* Copy the real ResponseData into presp. */ p = (uchar*)varRData.parray->pvData; for( i = 0; i <= rlen; i++) { /* skip the completion code */ if (i > 0) presp[i-1] = p[i]; } if (fdebugcmd) { printf("ipmi_cmdraw_ms: resp data(%d):",rlen+1); dumpbuf(p,rlen+1,0); } } bRet = 0; } MSRET: #define CLEAN_OK 1 #ifdef CLEAN_OK /* VariantClear(&var*) should be done by pInParams->Release() */ if (psa != NULL) SafeArrayDestroy(psa); if (pInParams != NULL) pInParams->Release(); if (pOutResp != NULL) pOutResp->Release(); #endif return(bRet); }
BOOL MySqlMem(const char * strParas, char * szReturn, int& nSize) { CString strReturn = "", strHost = _T(""), strUser = _T(""), //UserName strPwd = _T("");// Password CStringList paramList; MakeStringListByChar(paramList,strParas); POSITION pos = paramList.GetHeadPosition(); while(pos) { CString strTemp = paramList.GetNext(pos); if(strTemp.Find(__MACHINENAME__, 0) == 0) {//Get Host strHost = strTemp.Right(strTemp.GetLength() - (int)strlen(__MACHINENAME__)); } else if(strTemp.Find(__WINUSERACCOUNT__, 0) == 0) {//Get Username strUser = strTemp.Right(strTemp.GetLength() - (int)strlen(__WINUSERACCOUNT__)); } else if(strTemp.Find(__WINPASSWORD__, 0) == 0) {//Get password strPwd = strTemp.Right(strTemp.GetLength() - (int)strlen(__WINPASSWORD__)); } } //ofstream fout("mysqltest.txt",ios::app); //fout << strHost<< ","<<strUser<< ","<<strPwd<< ","<<"\r\n"; //fout << flush; //fout.close(); CoInitialize(NULL); try { WbemScripting::ISWbemLocatorPtr locator; locator.CreateInstance(WbemScripting::CLSID_SWbemLocator); if (locator != NULL) { WbemScripting::ISWbemServicesPtr services; if(IsLocalHost(strHost)) services = locator->ConnectServer(".","root\\cimv2","","","","",0,NULL); else services = locator->ConnectServer((_bstr_t)strHost,"root\\cimv2",(_bstr_t)strUser,(_bstr_t)strPwd,"","",0,NULL); WbemScripting::ISWbemObjectSetPtr objects = services->InstancesOf("Win32_LogicalMemoryConfiguration", 0x10, NULL); IEnumVARIANTPtr obj_enum = objects->Get_NewEnum(); ULONG fetched; VARIANT var; int nTotalPhyMem, nTotalVirMem; while (obj_enum->Next(1,&var,&fetched) == S_OK) { WbemScripting::ISWbemObjectPtr object = var; WbemScripting::ISWbemPropertySetPtr properties = object->Properties_; WbemScripting::ISWbemPropertyPtr prop = properties->Item("TotalPhysicalMemory",0); _variant_t value = prop->GetValue(); nTotalPhyMem = (int)value; prop = properties->Item("TotalVirtualMemory",0); value = prop->GetValue(); nTotalVirMem = (int)value; } _bstr_t com; com="SELECT * FROM Win32_PerfRawData_PerfProc_Process WHERE NAME='mysqld-nt' or NAME='mysqld'"; objects = services->ExecQuery(com,"WQL",0x10,NULL); obj_enum = objects->Get_NewEnum(); while (obj_enum->Next(1,&var,&fetched) == S_OK) { WbemScripting::ISWbemObjectPtr object = var; WbemScripting::ISWbemPropertySetPtr properties = object->Properties_; WbemScripting::ISWbemPropertyPtr prop = properties->Item("WorkingSet",0); _variant_t value = prop->GetValue(); int nPhyMem = (int)value/1024; prop = properties->Item("PrivateBytes",0); value = prop->GetValue(); int nVirMem = (int)value/1024; float fMySqlPhyMemUsage, fMySqlVirMemUsage; fMySqlPhyMemUsage = (float)nPhyMem/(float)nTotalPhyMem*100; fMySqlVirMemUsage = (float)nVirMem/(float)nTotalVirMem*100; strReturn.Format("MySqlPhyMem=%d$MySqlVirMem=%d$MySqlPhyMemUsage=%.2f$MySqlVirMemUsage=%.2f$TotalPhyMem=%d$TotalVirMem=%d$", nPhyMem, nVirMem, fMySqlPhyMemUsage, fMySqlVirMemUsage, nTotalPhyMem, nTotalVirMem); } if(strReturn == "") { sprintf(szReturn, "error=MySql is not run on this server!"); return FALSE; } } } catch (_com_error err) { char buf[200] = {0}; IErrorInfo * ei = err.ErrorInfo(); BSTR strDesEI; ei->GetDescription(&strDesEI); sprintf(szReturn, "error=Error ocured:%x: %s", (unsigned)err.Error(),_com_util::ConvertBSTRToString(strDesEI)); return FALSE; } catch(...) { sprintf(szReturn, "error=Error ocured: %d",::GetLastError()); return FALSE; } strcpy(szReturn,strReturn); CString strOutRet; strOutRet =szReturn; nSize = 2048; MakeCharByString(szReturn,nSize,strOutRet); CoUninitialize(); return TRUE; }
/******************************************************************** SqlGetErrorInfo - gets error information from the last SQL function call NOTE: pbstrErrorSource and pbstrErrorDescription are optional ********************************************************************/ extern "C" HRESULT DAPI SqlGetErrorInfo( __in IUnknown* pObjectWithError, __in REFIID IID_InterfaceWithError, __in DWORD dwLocaleId, __out_opt BSTR* pbstrErrorSource, __out_opt BSTR* pbstrErrorDescription ) { HRESULT hr = S_OK; Assert(pObjectWithError); // interfaces needed to extract error information out ISupportErrorInfo* pISupportErrorInfo = NULL; IErrorInfo* pIErrorInfoAll = NULL; IErrorRecords* pIErrorRecords = NULL; IErrorInfo* pIErrorInfoRecord = NULL; // only ask for error information if the interface supports it. hr = pObjectWithError->QueryInterface(IID_ISupportErrorInfo,(void**)&pISupportErrorInfo); ExitOnFailure(hr, "No error information was found for object."); hr = pISupportErrorInfo->InterfaceSupportsErrorInfo(IID_InterfaceWithError); ExitOnFailure(hr, "InterfaceWithError is not supported for object with error"); // ignore the return of GetErrorInfo it can succeed and return a NULL pointer in pIErrorInfoAll anyway hr = ::GetErrorInfo(0, &pIErrorInfoAll); ExitOnFailure(hr, "failed to get error info"); if (S_OK == hr && pIErrorInfoAll) { // see if it's a valid OLE DB IErrorInfo interface that exposes a list of records hr = pIErrorInfoAll->QueryInterface(IID_IErrorRecords, (void**)&pIErrorRecords); if (SUCCEEDED(hr)) { ULONG cErrors = 0; pIErrorRecords->GetRecordCount(&cErrors); // get the error information for each record for (ULONG i = 0; i < cErrors; ++i) { hr = pIErrorRecords->GetErrorInfo(i, dwLocaleId, &pIErrorInfoRecord); if (SUCCEEDED(hr)) { if (pbstrErrorSource) { pIErrorInfoRecord->GetSource(pbstrErrorSource); } if (pbstrErrorDescription) { pIErrorInfoRecord->GetDescription(pbstrErrorDescription); } ReleaseNullObject(pIErrorInfoRecord); break; // TODO: return more than one error in the future! } } ReleaseNullObject(pIErrorRecords); } else // we have a simple error record { if (pbstrErrorSource) { pIErrorInfoAll->GetSource(pbstrErrorSource); } if (pbstrErrorDescription) { pIErrorInfoAll->GetDescription(pbstrErrorDescription); } } } else { hr = E_NOMOREITEMS; } LExit: ReleaseObject(pIErrorInfoRecord); ReleaseObject(pIErrorRecords); ReleaseObject(pIErrorInfoAll); ReleaseObject(pISupportErrorInfo); return hr; }
/* Determines whether we can use the error information from the source object and if so, throws that as an error. If serr is non-NULL, then the error is not thrown in R but a COMSErrorInfo object is returned with the information in it. */ HRESULT checkErrorInfo(IUnknown *obj, HRESULT status, SEXP *serr) { HRESULT hr; ISupportErrorInfo *info; fprintf(stderr, "<checkErrorInfo> %X \n", (unsigned int) status); if(serr) *serr = NULL; hr = obj->QueryInterface(IID_ISupportErrorInfo, (void **)&info); if(hr != S_OK) { fprintf(stderr, "No support for ISupportErrorInfo\n");fflush(stderr); return(hr); } info->AddRef(); hr = info->InterfaceSupportsErrorInfo(IID_IDispatch); info->Release(); if(hr != S_OK) { fprintf(stderr, "No support for InterfaceSupportsErrorInfo\n");fflush(stderr); return(hr); } IErrorInfo *errorInfo; hr = GetErrorInfo(0L, &errorInfo); if(hr != S_OK) { /* fprintf(stderr, "GetErrorInfo failed\n");fflush(stderr); */ COMError(status); return(hr); } /* So there is some information for us. Use it. */ SEXP klass, ans, tmp; BSTR ostr; char *str; errorInfo->AddRef(); if(serr) { PROTECT(klass = MAKE_CLASS("SCOMErrorInfo")); PROTECT(ans = NEW(klass)); PROTECT(tmp = NEW_CHARACTER(1)); errorInfo->GetSource(&ostr); SET_STRING_ELT(tmp, 0, COPY_TO_USER_STRING(FromBstr(ostr))); SET_SLOT(ans, Rf_install("source"), tmp); UNPROTECT(1); PROTECT(tmp = NEW_CHARACTER(1)); errorInfo->GetDescription(&ostr); SET_STRING_ELT(tmp, 0, COPY_TO_USER_STRING(str = FromBstr(ostr))); SET_SLOT(ans, Rf_install("description"), tmp); UNPROTECT(1); PROTECT(tmp = NEW_NUMERIC(1)); NUMERIC_DATA(tmp)[0] = status; SET_SLOT(ans, Rf_install("status"), tmp); *serr = ans; UNPROTECT(3); errorInfo->Release(); PROBLEM "%s", str WARN; } else { errorInfo->GetDescription(&ostr); str = FromBstr(ostr); errorInfo->GetSource(&ostr); errorInfo->Release(); PROBLEM "%s (%s)", str, FromBstr(ostr) ERROR; } return(hr); }
int _tmain(int argc, _TCHAR* argv[]) { try { require( argc == 3, USAGE ); require( fileExists( argv[1] ), "File not found" ); require( fileExists( argv[2] ), "File not found" ); TCOMIXMLDOMDocument3 xml = Msxml2_tlb::CoDOMDocument60::Create(); TCOMIXMLDOMDocument3 xsl = Msxml2_tlb::CoDOMDocument60::Create(); xsl->resolveExternals = VARIANT_TRUE; load( xml, argv[1] ); load( xsl, argv[2] ); BSTR result = NULL; Msxml2_tlb::IXMLDOMNodePtr pXSLDOM = xsl->documentElement; HRESULT hr = xml->transformNode( pXSLDOM, &result ); if (FAILED(hr)) { WideString errMsg = L"Failure code obtained from transformNode. "; // Try to get extended error info... IErrorInfo* errorInfo = NULL; if ( SUCCEEDED( GetErrorInfo( 0, &errorInfo ) ) ) { boost::shared_ptr<void> releaseOnExit( errorInfo, release ); BSTR reason = NULL; if ( SUCCEEDED( errorInfo->GetDescription( &reason ) ) ) { boost::shared_ptr<void> freeStringOnExit( reason, freeString ); if ( reason ) { errMsg += WideString(reason); } } } throw Exception( UnicodeString( errMsg ) ); } boost::shared_ptr<void> freeStringOnExit( result, freeString ); WideString ws(result); std::wcout << (wchar_t*)ws; return 0; } catch( Exception& e ) { printError( e.Message ); } catch( const std::exception& e ) { printError( e.what() ); } catch( ... ) { printError( "Unspecified exception" ); } return 1; }