void CDlgSelCritDB::OnOK() { CString strCurCodeName; CString strCurDBName; CString strTmp; UpdateData(); m_ctlMaterCodeName.GetWindowText( EDIBgbl::sCur_MaterialCodeName ); int row = m_ctrlShowCODE.GetSelectionMark(); if( row == -1 ) { AfxMessageBox("请选择一个行业的规范数据库!"); return; } char c[256]; //规范数据库 m_ctrlShowCODE.GetItemText(row, 1, c, 256); strCurDBName = c; //当前规范 memset(c,'\0',256); m_ctrlShowCODE.GetItemText(row, 0, c, 256); strCurCodeName = c; //当前规范代号 memset(c,'\0',256); m_ctrlShowCODE.GetItemText(row, 2, c, 256); EDIBgbl::sCur_CodeNO = c; try { if ( !FileExists( EDIBgbl::sCritPath + strCurDBName ) ) { strTmp.Format(IDS_NOT_EXISTS_FILE, EDIBgbl::sCritPath + strCurDBName); AfxMessageBox( strTmp ); return; } CString strCon; //重新连接标准库 strCon = CONNECTSTRING + EDIBgbl::sCritPath + strCurDBName; if( theApp.m_pConnectionCODE->State == adStateOpen ) { theApp.m_pConnectionCODE->Close(); } theApp.m_pConnectionCODE->Open(_bstr_t(strCon), "", "", -1); } catch(_com_error &e) { AfxMessageBox(e.Description()+"\n\n选择的规范数据库("+strCurCodeName+")被破坏, 请重新安装 AutoIPED !"); CDialog::OnCancel(); return; } EDIBgbl::sCur_CritDbName = strCurDBName; EDIBgbl::sCur_CodeName = strCurCodeName; EDIBgbl::iCur_CodeKey=row+1; EDIBgbl::SetCurDBName(); //显示当前的工程名(加上行业标准) ((CMainFrame*)theApp.m_pMainWnd)->ShowCurrentProjectName(); CDialog::OnOK(); }
static unsigned int getclock(void) { unsigned int clock; #ifdef KONOHA_ON_MACOSX int cpu_sels[2] = { CTL_HW, HW_CPU_FREQ }; size_t len = sizeof(int); sysctl(cpu_sels, 2, &clock, &len, NULL, 0); clock = (unsigned int) clock / (1000 * 1000); #elif defined(KONOHA_ON_WINDOWS) HRESULT hres; hres = CoInitializeEx(0, COINIT_MULTITHREADED); hres = CoInitializeSecurity( NULL, -1, // COM authentication NULL, // Authentication services NULL, // Reserved RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation NULL, // Authentication info EOAC_NONE, // Additional capabilities NULL // Reserved ); IWbemLocator *pLoc = NULL; hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc); IWbemServices *pSvc = NULL; hres = pLoc->ConnectServer( _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace NULL, // User name. NULL = current user NULL, // User password. NULL = current 0, // Locale. NULL indicates current NULL, // Security flags. 0, // Authority (e.g. Kerberos) 0, // Context object &pSvc // pointer to IWbemServices proxy ); hres = CoSetProxyBlanket( pSvc, // Indicates the proxy to set RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx NULL, // Server principal name RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx NULL, // client identity EOAC_NONE // proxy capabilities ); IEnumWbemClassObject* pEnumerator = NULL; hres = pSvc->ExecQuery( bstr_t("WQL"), bstr_t("SELECT * FROM Win32_Processor"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); IWbemClassObject *pclsObj; ULONG uReturn = 0; while (pEnumerator) { HRESULT hr = pEnumerator->Next( WBEM_INFINITE, 1, &pclsObj, &uReturn ); if (uReturn == 0) { break; } VARIANT vtProp; hr = pclsObj->Get(L"MaxClockSpeed", 0, &vtProp, 0, 0); clock = (unsigned int)vtProp.bstrVal; VariantClear(&vtProp); pclsObj->Release(); } pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); #elif defined(KONOHA_ON_LINUX) char buf[64] = {'\0'}, *data = buf; const char *cpumhz = "cpu MHz"; size_t len = strlen(cpumhz); FILE *fp = fopen("/proc/cpuinfo","r"); while (fgets( buf, 64, fp ) != NULL){ if ( strncmp(buf, cpumhz, len) == 0){ data = strstr(buf, cpumhz); break; } } while (!isdigit(*data)) { data++; } clock = (unsigned int) atoi(data) / 1000; fclose(fp); #else TODO(); #endif return clock; }
void COpcAdapter::OnValueChanged(ItemList & _ignore) { #if 0 // RPM - Update spindle based on Srpm1, Srpm2 data if(_nMultiSpindle) { int srpm = 0; int srpm1 = opcitems.GetValue<int>("Srpm1", -1); int srpm2 = opcitems.GetValue<int>("Srpm2", -1); if (srpm1 > 0) srpm=srpm1; if (srpm2 >0 && srpm2 > srpm1) srpm = srpm2; if(srpm> 0) opcitems.SetItemValue("Srpm", (long) srpm); } if(_nFakeSpindle) { std::string sMode = opcitems.GetValue("controllermode", ""); std::string sExecution = opcitems.GetValue("execution", ""); // If moving and in auto mode, assume spindle on if( (sMode == "AUTOMATIC" ) && (sExecution == "EXECUTING" )&& ( lastFeed!=opcitems.GetValue("path_feedratefrt", "") || lastX!=opcitems.GetValue("Xabs", "") || lastY!= opcitems.GetValue("Yabs", "") || lastZ!=opcitems.GetValue("Zabs", "") ) ) mLag=4; // 3 cycles - 3 seconds; else mLag--; if(mLag<0) mLag=0; if(mLag>0) { opcitems.SetItemValue("Srpm","99.0"); } else { opcitems.SetItemValue("Srpm","0"); } lastFeed= opcitems.GetValue("path_feedratefrt", ""); lastX= opcitems.GetValue("Xabs", ""); lastY= opcitems.GetValue("Yabs", ""); lastZ= opcitems.GetValue("Zabs", ""); } if( _nAlarmsEnabled) { // Simpler ALARM handling std::string alarmLevel; std::string alarmSeverity; std::string sAlarmMessage; std::string sNativeCode; std::string sQualifier; long lNativeCode = opcitems.GetValue<long>(_T("alarmNative"),-1); opcitems.SetItemValue("alarm", (BSTR) _bstr_t("")); if(lNativeCode > 1000 ) { // 840D Code whether alarm pending. // 0 = no alarm in this channel // 1 = alarm without stop // 2 = alarm with stop // severity - CRITICAL, ERROR, WARNING, or INFORMATION. // state Either INSTANT, ACTIVE or CLEARED. static char * sSeverities[3] = {_T("NONE"), _T("WARNING"), _T("CRITICAL")}; static char * sLevel[3] = {_T("NORMAL"), _T("WARNING") , _T("FAULT")}; alarmLevel= (lNativeCode <3)? sLevel[lNativeCode] : _T("UNAVAILABLE"); alarmSeverity= (lNativeCode <3)? sSeverities[lNativeCode] : _T("CRITICAL"); sNativeCode = opcitems.GetValue(_T("alarmNative") , ""); sAlarmMessage = "None"; if(lNativeCode>0) sAlarmMessage = _alarmconfig.GetSymbolValue("Alarms."+sNativeCode).str(); for(int j=0; lNativeCode>0 && j<4; j++) { std::string fillText=opcitems.GetValue(StdStringFormat("alarmField%d", j+1), ""); if(fillText.empty()) continue; if(fillText[0]==_T('S') || fillText[0]==_T('K')) fillText=fillText.substr(1); sAlarmMessage=ReplaceOnce(sAlarmMessage,StdStringFormat("%d%%",j+1), fillText); } opcitems.SetItemValue("alarm", (BSTR) _bstr_t(sAlarmMessage.c_str())); } } #endif for (int i =0; i<opcitems.size(); i++) { if(opcitems[i]->_type==_T("OPC") || opcitems[i]->_type==_T("Data") ) { continue; // don't update MTConnect - opc value only } if(opcitems[i]->_value==opcitems[i]->_lastvalue) continue; std::string alias = opcitems[i]->_alias; std::string value = opcitems[i]->GetValue(); if(opcitems[i]->_subtype=="enumeration") { std::string szEnumTag="Enum." + alias + "." + value; //szEnumTag.Format(_T("Enum.%s.%s"), alias, value); value = GetSymbolValue(_sTagSectionName, szEnumTag, (LPCSTR) "UNAVAILABLE"); // Use default if available if(value == "UNAVAILABLE") { szEnumTag="Enum." + alias + ".-1"; value = GetSymbolValue(_sTagSectionName, szEnumTag, (LPCSTR) "UNAVAILABLE"); } } // Condition Doesn't work as advertised. /* HOW TO MAP ALARM TO CONDITION 1. Level – This must be normal, warning, fault, or unavailable (case is not important). If this value is not one of the previous values, unavailable will be assumed. 2. Native Code – This is the number or short name of the alarm or warning passed through from the device. 3. Native Severity – The severity of the alarm as passed through from the device. 4. Qualifier – This is a modifier which indicates which end of the range the condition applies or qualifies the condition. Examples are: HIGH, LOW, etc… 5. Text – The text describing the condition. This text is usually taken from the data source and passed through. 2010-09-29T23:59:33.460470Z|htemp|WARNING|HTEMP|1|HIGH|Oil Temperature High <DataItem category="CONDITION" id="htemp" type="TEMPERATURE"/> <Warning dataItemId="htemp" timestamp="2010-09-29T23:59:33.460470Z" sequence="399237840" type="TEMPERATURE" nativeSeverity="1" nativeCode="HTEMP" qualifier="HIGH" >Oil Temperature High</Warning> If there is no message, as is usually the case when the operation is Normal, leave all the fields blank, but still provide the pipe delimiter for proper parsing as follows: 2010-09-29T23:59:33.460470Z|htemp|NORMAL|||| Expected data to parse in SDHR format: * Time|Condition|Level|NativeCode|Native Severity|Qualifier|Description * Time|Item|Value * Time|Item1|Value1|Item2|Value2... */ /* 1. Level – This must be normal, warning, fault, or unavailable (case is not important). If this value is not one of the previous values, unavailable will be assumed. 2. Native Code – This is the number or short name of the alarm or warning passed through from the device. 3. Native Severity – The severity of the alarm as passed through from the device. 4. Qualifier – This is a modifier which indicates which end of the range the condition applies or qualifies the condition. Examples are: HIGH, LOW, etc… 5. Text – The text describing the condition. This text is usually taken from the data source and passed through. */ _CriticalSection.Lock(); #if 1 if(opcitems[i]->_type==_T("Event")) { //_mtcagent->SetEvent(this->_device, opcitems[i]->_alias, value); SetMTCTagValue( opcitems[i]->_alias, value); } else if( opcitems[i]->_type==_T("Sample")) { //_mtcagent->SetSample(this->_device, opcitems[i]->_alias, value); SetMTCTagValue( opcitems[i]->_alias, value); } else if( opcitems[i]->_type==_T("Condition")) { #ifdef ALARMS //if(lNativeCode>0) // _agentconfig->SetCondition(this->_device, opcitems[i]->_alias, // alarmLevel, // sNativeCode, // alarmSeverity, // sQualifier, // sAlarmMessage // ); #endif } #endif _CriticalSection.Unlock(); } }
void MakeCopy(_FutureRootUpdateParams & ri, FutureRootParams & vp) { ri->FuturesRootSymbol = (_bstr_t(vp.FuturesRootSymbol).copy()); }
long CDBLayoutSQL::VolaSurfaceDataSave( long nSurfaceID, long nContractID, double dBaseUnderlinePrice, double dSmileAccelerator, double dInterpolationFactor, double dStrikeMoneynessHi, double dStrikeMoneynessLo, LPCTSTR szSurfaceName, long nIsPriceOverride, long nIsDiscreteAcceleration, long nIsDefaultSurface ) { ASSERT(m_db.IsOpened()); long nNewID = nSurfaceID; CStoredProc<> sp(m_db, L"usp_VolaSurfaceData_Save"); if( nSurfaceID > 0 ) sp << nSurfaceID; else sp << &nNewID; if( nContractID != 0 ) sp << nContractID; else sp << CDBNull(); if( dBaseUnderlinePrice >= 0 ) sp << dBaseUnderlinePrice; else sp << CDBNull(); if( dSmileAccelerator >= 0 ) sp << dSmileAccelerator; else sp << CDBNull(); if( dInterpolationFactor >= 0 ) sp << dInterpolationFactor; else sp << CDBNull(); if( dStrikeMoneynessHi >= 0 ) sp << dStrikeMoneynessHi; else sp << CDBNull(); if( dStrikeMoneynessLo >= 0 ) sp << dStrikeMoneynessLo; else sp << CDBNull(); if( szSurfaceName > NULL ) sp << _bstr_t(szSurfaceName); else sp << CDBNull(); if( nIsPriceOverride >= 0 ) sp << nIsPriceOverride; else sp << CDBNull(); if( nIsDiscreteAcceleration >= 0 ) sp << nIsDiscreteAcceleration; else sp << CDBNull(); if( nIsDefaultSurface >= 0 ) sp << nIsDefaultSurface; else sp << CDBNull(); sp << CDBNull(); sp.Execute(); return nNewID; }
//----------------------------------------------------------------------------- // Purpose: extracts the list of defines and includes used for this config //----------------------------------------------------------------------------- bool CVCProjConvert::ExtractIncludes( IXMLDOMElement *pDoc, CConfiguration & config ) { config.ResetDefines(); config.ResetIncludes(); if (!pDoc) { return false; } #ifdef _WIN32 CComPtr<IXMLDOMNodeList> pTools; pDoc->getElementsByTagName( _bstr_t("Tool"), &pTools); if (pTools) { long len = 0; pTools->get_length(&len); for ( int i=0; i<len; i++ ) { CComPtr<IXMLDOMNode> pNode; pTools->get_item( i, &pNode ); if (pNode) { CComQIPtr<IXMLDOMElement> pElem( pNode ); CUtlSymbol toolName = GetXMLAttribValue( pElem, "Name" ); if ( toolName == "VCCLCompilerTool" ) { CUtlSymbol defines = GetXMLAttribValue( pElem, "PreprocessorDefinitions" ); char *str = (char *)_alloca( Q_strlen( defines.String() ) + 1 ); Assert( str ); Q_strcpy( str, defines.String() ); // now tokenize the string on the ";" char char *delim = strchr( str, ';' ); char *curpos = str; while ( delim ) { *delim = 0; delim++; if ( Q_stricmp( curpos, "WIN32" ) && Q_stricmp( curpos, "_WIN32" ) && Q_stricmp( curpos, "_WINDOWS") && Q_stricmp( curpos, "WINDOWS")) // don't add WIN32 defines { config.AddDefine( curpos ); } curpos = delim; delim = strchr( delim, ';' ); } if ( Q_stricmp( curpos, "WIN32" ) && Q_stricmp( curpos, "_WIN32" ) && Q_stricmp( curpos, "_WINDOWS") && Q_stricmp( curpos, "WINDOWS")) // don't add WIN32 defines { config.AddDefine( curpos ); } CUtlSymbol includes = GetXMLAttribValue( pElem, "AdditionalIncludeDirectories" ); char *str2 = (char *)_alloca( Q_strlen( includes.String() ) + 1 ); Assert( str2 ); Q_strcpy( str2, includes.String() ); // now tokenize the string on the ";" char delim = strchr( str2, ',' ); curpos = str2; while ( delim ) { *delim = 0; delim++; config.AddInclude( curpos ); curpos = delim; delim = strchr( delim, ',' ); } config.AddInclude( curpos ); } } } } #elif _LINUX DOMNodeList *nodes= pDoc->getElementsByTagName( _bstr_t("Tool")); if (nodes) { int len = nodes->getLength(); for ( int i=0; i<len; i++ ) { DOMNode *node = nodes->item(i); if (node) { CUtlSymbol toolName = GetXMLAttribValue( node, "Name" ); if ( toolName == "VCCLCompilerTool" ) { CUtlSymbol defines = GetXMLAttribValue( node, "PreprocessorDefinitions" ); char *str = (char *)_alloca( Q_strlen( defines.String() ) + 1 ); Assert( str ); Q_strcpy( str, defines.String() ); // now tokenize the string on the ";" char char *delim = strchr( str, ';' ); char *curpos = str; while ( delim ) { *delim = 0; delim++; if ( Q_stricmp( curpos, "WIN32" ) && Q_stricmp( curpos, "_WIN32" ) && Q_stricmp( curpos, "_WINDOWS") && Q_stricmp( curpos, "WINDOWS")) // don't add WIN32 defines { config.AddDefine( curpos ); } curpos = delim; delim = strchr( delim, ';' ); } if ( Q_stricmp( curpos, "WIN32" ) && Q_stricmp( curpos, "_WIN32" ) && Q_stricmp( curpos, "_WINDOWS") && Q_stricmp( curpos, "WINDOWS")) // don't add WIN32 defines { config.AddDefine( curpos ); } CUtlSymbol includes = GetXMLAttribValue( node, "AdditionalIncludeDirectories" ); char *str2 = (char *)_alloca( Q_strlen( includes.String() ) + 1 ); Assert( str2 ); Q_strcpy( str2, includes.String() ); // now tokenize the string on the ";" char char token = ','; delim = strchr( str2, token ); if ( !delim ) { token = ';'; delim = strchr( str2, token ); } curpos = str2; while ( delim ) { *delim = 0; delim++; Q_FixSlashes( curpos ); Q_strlower( curpos ); char fullPath[ MAX_PATH ]; Q_snprintf( fullPath, sizeof(fullPath), "%s/%s", m_BaseDir.String(), curpos ); Q_StripTrailingSlash( fullPath ); config.AddInclude( fullPath ); curpos = delim; delim = strchr( delim, token ); } Q_FixSlashes( curpos ); Q_strlower( curpos ); char fullPath[ MAX_PATH ]; Q_snprintf( fullPath, sizeof(fullPath), "%s/%s", m_BaseDir.String(), curpos ); Q_StripTrailingSlash( fullPath ); config.AddInclude( fullPath ); } } } } #endif return true; }
void MakeCopy(_OptionUpdateParams & rp, OptionParams & vp) { rp->Exchange = _bstr_t("").copy(); rp->UnderlyingSymbol = (_bstr_t(vp.UnderlyingSymbol).copy()); }
Artifact DominoDocArtifact::CreateRelatedItem(const std::wstring& filenameToRelate, const std::wstring& type,const std::wstring& AvailableFileFormats,bool ShowUI) { // HACKETY UNREFERENCED_PARAMETER(AvailableFileFormats); UNREFERENCED_PARAMETER(ShowUI); if(0 != lstrcmpiW(type.c_str(), L"W3")) throw Workshare::ArgumentException(_T("type"), _T("We only support the W3 type")); if(filenameToRelate.empty()) throw Workshare::ArgumentException(_T("filenameToRelate"), _T("We need a file name to create a related item.")); if(!PathFileExistsW(filenameToRelate.c_str())) throw Workshare::System::IO::FileNotFoundException(_bstr_t(filenameToRelate.c_str()), _T("Only files that exist can be uploaded to a Lotus Domino Repository")); DominoDoc::IDocumentPtr spDocument = GetDocument(); wchar_t tempPath[MAX_PATH] = {0}; if(0 == ::GetTempPathW(MAX_PATH, tempPath)) { DWORD lastError = ::GetLastError(); std::tostringstream msg; msg << _T("Failed to get the temporary path while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends; throw Workshare::System::SystemException(msg.str().c_str(), lastError); } wchar_t tempFileName[_MAX_PATH] = {0}; if(0 == GetTempFileNameW(tempPath, L"WC", 0, tempFileName)) { DWORD lastError = ::GetLastError(); std::tostringstream msg; msg << _T("Failed to get the temporary filename while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends; throw Workshare::System::SystemException(msg.str().c_str(), lastError); } DeleteFileW(tempFileName); PathRemoveExtensionW(tempFileName); if(!::CreateDirectoryW(tempFileName, NULL)) { DWORD lastError = ::GetLastError(); std::tostringstream msg; msg << "Failed to create a temporary directory [" << tempFileName << ", to upload [" << filenameToRelate << "] for uploading artifact, " << m_documentId << ", version, " << m_versionLabel << " which came from repository, " << m_libraryUrl << std::ends; throw Workshare::System::SystemException(msg.str().c_str(), lastError); } wchar_t fileName[MAX_PATH] = {0}; lstrcpyW(fileName, tempFileName); if(spDocument->FileName.length() > 0) PathAppendW(fileName,spDocument->FileName); else PathAppendW(fileName, PathFindFileNameW(filenameToRelate.c_str())); PathRemoveExtensionW(fileName); lstrcatW(fileName, L"."); lstrcatW(fileName, type.c_str()); if(!CopyFileW(filenameToRelate.c_str(), fileName, TRUE)) { DWORD lastError = ::GetLastError(); std::tostringstream msg; msg << _T("Failed to copy [") << filenameToRelate << _T("] to [") << fileName << _T("] while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends; throw Workshare::System::SystemException(msg.str().c_str(), lastError); } try { DominoDoc::IBinderPtr spBinder = spDocument->Binder; DominoDoc::IDocumentsPtr spDocuments = spBinder->Documents; DominoDoc::IDocumentPtr spRelatedDocument = spDocuments->Add(); std::wstring title = this->Name + L".W3"; spRelatedDocument->Title = title.c_str(); spRelatedDocument->Description = L"File Used by workshare during the collaboration process"; spRelatedDocument->SetContents(fileName); spRelatedDocument->Save(); spRelatedDocument->CheckIn(c_revisiontypeVersion, c_actionReplace, VARIANT_TRUE, _T("Workshare Collaboration Document")); DeleteFileW(fileName); RemoveDirectoryW(tempFileName); return new DominoDocArtifact(spRelatedDocument); } catch(...) { DeleteFileW(fileName); RemoveDirectoryW(tempFileName); throw; } }
void DominoDocArtifact::Upload(const std::wstring& fileToUpload) { if(!PathFileExistsW(fileToUpload.c_str())) throw Workshare::System::IO::FileNotFoundException(_bstr_t(fileToUpload.c_str()), _T("Only files that exist can be uploaded to a Lotus Domino Repository")); DominoDoc::IDocumentPtr spDocument = GetDocument(); wchar_t tempPath[MAX_PATH] = {0}; if(0 == ::GetTempPathW(MAX_PATH, tempPath)) { DWORD lastError = ::GetLastError(); std::tostringstream msg; msg << _T("Failed to get the temporary path while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends; throw Workshare::System::SystemException(msg.str().c_str(), lastError); } wchar_t tempFileName[_MAX_PATH] = {0}; if(0 == GetTempFileNameW(tempPath, L"WC", 0, tempFileName)) { DWORD lastError = ::GetLastError(); std::tostringstream msg; msg << _T("Failed to get the temporary filename while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends; throw Workshare::System::SystemException(msg.str().c_str(), lastError); } DeleteFileW(tempFileName); PathRemoveExtensionW(tempFileName); if(!::CreateDirectoryW(tempFileName, NULL)) { DWORD lastError = ::GetLastError(); std::tostringstream msg; msg << _T("Failed to create a temporary directory [") << tempFileName << _T(", to upload [") << fileToUpload << _T("] for uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends; throw Workshare::System::SystemException(msg.str().c_str(), lastError); } wchar_t fileName[MAX_PATH] = {0}; lstrcpyW(fileName, tempFileName); if(spDocument->FileName.length() > 0) PathAppendW(fileName,spDocument->FileName); else PathAppendW(fileName, PathFindFileNameW(fileToUpload.c_str())); if(!CopyFileW(fileToUpload.c_str(), fileName, TRUE)) { DWORD lastError = ::GetLastError(); std::tostringstream msg; msg << _T("Failed to copy [") << fileToUpload << _T("] to [") << fileName << _T("] while uploading artifact, ") << m_documentId << _T(", version, ") << m_versionLabel << _T(" which came from repository, ") << m_libraryUrl << std::ends; throw Workshare::System::SystemException(msg.str().c_str(), lastError); } try { spDocument->SetToWorkingCopy(); spDocument->SetContents(fileName); spDocument->Save(); spDocument->CheckIn(c_revisiontypeDraft, 1, VARIANT_FALSE, "Created By Workshare"); wchar_t versionLabel[32] = {0}; _snwprintf(versionLabel, 32, L"%d.%d", spDocument->VersionNumber, spDocument->DraftNumber); m_versionLabel = versionLabel; Log(_T("The file [%S] was uploaded to the Domino.Doc library [%S] as document [%S]"), fileToUpload.c_str(), m_libraryUrl.c_str(), m_documentId.c_str()); DeleteFileW(fileName); RemoveDirectoryW(tempFileName); } catch(...) { DeleteFileW(fileName); RemoveDirectoryW(tempFileName); throw; } }
void CTransformationsDialog::AddOptionToPropetryEditor( MSXML2::IXMLDOMElementPtr & option_element, MSXML2::IXMLDOMElementPtr & transformation_element, CPropertyEditor & property_editor) { CString option_type = (LPCTSTR) option_element->nodeName; CString variable_name = (LPCTSTR) (_bstr_t) option_element->getAttribute("variable_name"); CString value_query_str; //dotaz na default value value_query_str.Format("visualization_values/variable[@name=\"%s\"]/@value", (LPCTSTR) variable_name); CString value; try { value = (LPCTSTR) transformation_element->selectSingleNode((LPCTSTR) value_query_str)->text; } catch (_com_error &) { CString err_msg; err_msg.Format("Value of variable \"%s\" is missing.", variable_name); throw err_msg; } if (option_type == "enum_option") { //enum property_editor.AddProperty( CreateEnumProperty(option_element, value)); } else if (option_type == "string_option") { //string property_editor.AddProperty(new CStringProperty( (_bstr_t) option_element->getAttribute("title"), //label value)); //default value } else if (option_type == "color_option") { //color property_editor.AddProperty(new CColorProperty( (_bstr_t) option_element->getAttribute("title"), //label value)); //default value } else if (option_type == "number_option") { if ((_bstr_t) option_element->getAttribute("num_type") == _bstr_t("float")) { //float property_editor.AddProperty( CreateDoubleProperty(option_element, value)); } else if ((_bstr_t) option_element->getAttribute("num_type") == _bstr_t("integer")) { //integer property_editor.AddProperty( CreateIntProperty(option_element, value)); } } }
void CTransformationsDialog::ConfigureTransformation(int transform_index) { ASSERT(transform_index >= 0); ASSERT(transform_index < m_SelectedList.GetCount()); CElementManager & m = ((CReportAsistentApp *) AfxGetApp())->m_pGeneralManager->ElementManager; //element info int element_id = m.IdentifyElement(m_active_element); CAElInfo * element_info = m.getActiveElementInfo(element_id); //tranformation CString query_str; query_str.Format("transformation[%d]", transform_index); MSXML2::IXMLDOMElementPtr transformation_element = m_cloned_output_element->selectSingleNode((LPCTSTR) query_str); //options definition MSXML2::IXMLDOMNodePtr options_node = element_info->getTranformationOptionsDoc( element_info->FindTransformationByName((_bstr_t) transformation_element->getAttribute("name"))); //single options MSXML2::IXMLDOMNodeListPtr option_nodes = options_node->selectNodes("/visualization/visualization_options/*"); //napln property editor //label CString label; label.Format("%s (%s) properties", (LPCTSTR) options_node->selectSingleNode("/visualization/visualization_options/@visualization_label")->text, (LPCTSTR) (_bstr_t) m_active_element->getAttribute("id")); CPropertyEditor property_editor(label, this); //pridej jednotlive properties for (int a=0; a < option_nodes->length; a++) { MSXML2::IXMLDOMElementPtr option_element = option_nodes->item[a]; AddOptionToPropetryEditor(option_element, transformation_element, property_editor); option_element.Release(); } //vytvor modalni dialog if (IDOK == property_editor.DoModal()) { //uloz hodnoty z property editoru for (int a=0; a < option_nodes->length; a++) { MSXML2::IXMLDOMElementPtr option_element = option_nodes->item[a]; CString variable_name = (LPCTSTR) (_bstr_t) option_element->getAttribute("variable_name"); CString value_query_str; value_query_str.Format("visualization_values/variable[@name=\"%s\"]/@value", (LPCTSTR) variable_name); //nastav hodnotu parametru value if (option_element->nodeName == _bstr_t("enum_option")) { transformation_element->selectSingleNode((LPCTSTR) value_query_str)->text = (LPCTSTR) FindOptionEnumItemValueFromLabel( options_node, variable_name, property_editor.GetValueOfProperty(a)->GetValue()); } else { transformation_element->selectSingleNode((LPCTSTR) value_query_str)->text = property_editor.GetValueOfProperty(a)->GetValue(); } option_element.Release(); } } option_nodes.Release(); }
void WMICOL::ReadColumn(PGLOBAL g) { // Get the value of the Name property Res = Tdbp->ClsObj->Get(_bstr_t(Name), 0, &Prop, &Ctype, 0); switch (Prop.vt) { case VT_EMPTY: case VT_NULL: case VT_VOID: Value->Reset(); break; case VT_BSTR: Value->SetValue_psz(_com_util::ConvertBSTRToString(Prop.bstrVal)); break; case VT_I4: case VT_UI4: Value->SetValue(Prop.lVal); break; case VT_I2: case VT_UI2: Value->SetValue(Prop.iVal); break; case VT_INT: case VT_UINT: Value->SetValue((int)Prop.intVal); break; case VT_BOOL: Value->SetValue(((int)Prop.boolVal) ? 1 : 0); break; case VT_R8: Value->SetValue(Prop.dblVal); break; case VT_R4: Value->SetValue((double)Prop.fltVal); break; case VT_DATE: switch (Value->GetType()) { case TYPE_DATE: {SYSTEMTIME stm; struct tm ptm; int rc = VariantTimeToSystemTime(Prop.date, &stm); ptm.tm_year = stm.wYear; ptm.tm_mon = stm.wMonth; ptm.tm_mday = stm.wDay; ptm.tm_hour = stm.wHour; ptm.tm_min = stm.wMinute; ptm.tm_sec = stm.wSecond; ((DTVAL*)Value)->MakeTime(&ptm); }break; case TYPE_STRING: {SYSTEMTIME stm; char buf[24]; int rc = VariantTimeToSystemTime(Prop.date, &stm); sprintf(buf, "%02d/%02d/%d %02d:%02d:%02d", stm.wDay, stm.wMonth, stm.wYear, stm.wHour, stm.wMinute, stm.wSecond); Value->SetValue_psz(buf); }break; default: Value->SetValue((double)Prop.fltVal); } // endswitch Type break; default: // This will reset numeric column value Value->SetValue_psz("Type not supported"); break; } // endswitch vt VariantClear(&Prop); } // end of ReadColumn
PWMIUT InitWMI(PGLOBAL g, char *nsp, char *classname) { IWbemLocator *loc; char *p; HRESULT res; PWMIUT wp = (PWMIUT)PlugSubAlloc(g, NULL, sizeof(WMIUTIL)); if (trace) htrc("WMIColumns class %s space %s\n", SVP(classname), SVP(nsp)); /*********************************************************************/ /* Set default values for the namespace and class name. */ /*********************************************************************/ if (!nsp) nsp = "root\\cimv2"; if (!classname) { if (!stricmp(nsp, "root\\cimv2")) classname = "ComputerSystemProduct"; else if (!stricmp(nsp, "root\\cli")) classname = "Msft_CliAlias"; else { strcpy(g->Message, "Missing class name"); return NULL; } // endif classname } // endif classname /*********************************************************************/ /* Initialize WMI. */ /*********************************************************************/ //res = CoInitializeEx(NULL, COINIT_MULTITHREADED); res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if (FAILED(res)) { sprintf(g->Message, "Failed to initialize COM library. " "Error code = %p", res); return NULL; } // endif res #if 0 // irrelevant for a DLL res = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); if (res != RPC_E_TOO_LATE && FAILED(res)) { sprintf(g->Message, "Failed to initialize security. " "Error code = %p", res); CoUninitialize(); return NULL; } // endif Res #endif // 0 res = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void**) &loc); if (FAILED(res)) { sprintf(g->Message, "Failed to create Locator. " "Error code = %p", res); CoUninitialize(); return NULL; } // endif res res = loc->ConnectServer(_bstr_t(nsp), NULL, NULL, NULL, 0, NULL, NULL, &wp->Svc); if (FAILED(res)) { sprintf(g->Message, "Could not connect. Error code = %p", res); loc->Release(); CoUninitialize(); return NULL; } // endif res loc->Release(); if (trace) htrc("Successfully connected to namespace.\n"); /*********************************************************************/ /* Perform a full class object retrieval. */ /*********************************************************************/ p = (char*)PlugSubAlloc(g, NULL, strlen(classname) + 7); if (strchr(classname, '_')) strcpy(p, classname); else strcat(strcpy(p, "Win32_"), classname); res = wp->Svc->GetObject(bstr_t(p), 0, 0, &wp->Cobj, 0); if (FAILED(res)) { sprintf(g->Message, "failed GetObject %s in %s\n", classname, nsp); wp->Svc->Release(); wp->Svc = NULL; // MUST be set to NULL (why?) return NULL; } // endif res return wp; } // end of InitWMI
///////////////////////////////////////////////////////////////////////////// // CDlgSelCritDB message handlers BOOL CDlgSelCritDB::OnInitDialog() { CDialog::OnInitDialog(); int nFCount, pos; CString strCritDBName[20], strMaterialDBName[20]; struct KeyToCalling sutKeyCalling[20]; // 行业名称和标示符 int nKeyCount = GetCallingFromDB( sutKeyCalling ); if ( nKeyCount <= 0 ) { return FALSE; } //初始化标准数据库列表 // nFCount = this->GetCriterionDBName( strCritDBName ); //标准规范 CMapStringToString mapCode_Mdb; CString strValue; short nIndex = 0; //初始的选择规范的索引号 CRect rc; m_ctrlShowCODE.GetWindowRect(&rc); m_ctrlShowCODE.InsertColumn(0, _T("行业名称"), LVCFMT_LEFT, rc.Width()/3); m_ctrlShowCODE.InsertColumn(1, _T("数据库"), LVCFMT_LEFT, rc.Width()/3); m_ctrlShowCODE.InsertColumn(2, _T("标准名称"), LVCFMT_LEFT, rc.Width()/3); m_ctrlShowCODE.SetExtendedStyle( m_ctrlShowCODE.GetExtendedStyle()|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES ); try { _RecordsetPtr pRsDBRef; pRsDBRef.CreateInstance( __uuidof( Recordset ) ); CString strSQL; CString strTmp; strSQL = "SELECT * FROM [DataBaseRef]"; pRsDBRef->Open( _variant_t(strSQL), theApp.m_pConRefInfo.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText ); for( int j=0, row=0; j < nKeyCount; j++ ) { m_ctrlShowCODE.InsertItem( row, sutKeyCalling[j].strCallingName ); if ( !pRsDBRef->adoEOF || !pRsDBRef->BOF) { strSQL.Format( "CallingKey='%d'",sutKeyCalling[j].strKey); pRsDBRef->MoveFirst(); pRsDBRef->Find( _bstr_t(strSQL), 0, adSearchForward); if ( !pRsDBRef->adoEOF ) { // 行业的标准数据库名 strTmp = vtos( pRsDBRef->GetCollect( _variant_t("CodeDBName") ) ); m_ctrlShowCODE.SetItemText( row, 1, strTmp ); // 行业中材料的规范号 m_ctrlShowCODE.SetItemText( row, 2, sutKeyCalling[j].strCodeName ); // } if( sutKeyCalling[j].strKey==EDIBgbl::iCur_CodeKey) { //记住上一次选择的规范的索引号 nIndex = row; } } row++; } if ( m_ctrlShowCODE.GetItemCount() > 0 ) { m_ctrlShowCODE.SetHotItem( nIndex ); m_ctrlShowCODE.SetSelectionMark( nIndex ); } } catch (_com_error& e) { AfxMessageBox( e.Description() ); return FALSE; } //初始化规范列表 CArray<CString,CString> mCodeNameArray; GetPropertyofMaterial mGetPropertyofMaterial; mGetPropertyofMaterial.GetAllCodeName( theApp.m_pConMaterial,mCodeNameArray ); int iCount = mCodeNameArray.GetSize(); for ( int i=0; i<iCount; i++ ) { m_ctlMaterCodeName.AddString( mCodeNameArray.GetAt(i) ); } int iCurSel = m_ctlMaterCodeName.FindString(-1,EDIBgbl::sCur_MaterialCodeName ); if ( iCurSel == -1 ) iCurSel = 0; m_ctlMaterCodeName.SetCurSel( iCurSel ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
void CH_DbDataSet::get_string_field(const string &name, string &value) { _variant_t value_t = m_pdataset->GetCollect(name.c_str()); value = (const char *)_bstr_t(value_t); }
BOOL CEnumerateSerial::UsingWMI(CSimpleArray<UINT>& ports, CSimpleArray<CString>& friendlyNames) #endif { //Make sure we clear out any elements which may already be in the array(s) #if defined CENUMERATESERIAL_USE_STL ports.clear(); friendlyNames.clear(); #else ports.RemoveAll(); friendlyNames.RemoveAll(); #endif //What will be the return value BOOL bSuccess = FALSE; //Create the WBEM locator IWbemLocator* pLocator = NULL; HRESULT hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&pLocator)); if (SUCCEEDED(hr)) { IWbemServices* pServices = NULL; hr = pLocator->ConnectServer(_bstr_t("\\\\.\\root\\cimv2"), NULL, NULL, NULL, 0, NULL, NULL, &pServices); if (SUCCEEDED(hr)) { //Execute the query IEnumWbemClassObject* pClassObject = NULL; hr = pServices->CreateInstanceEnum(_bstr_t("Win32_SerialPort"), WBEM_FLAG_RETURN_WBEM_COMPLETE, NULL, &pClassObject); if (SUCCEEDED(hr)) { bSuccess = TRUE; //Now enumerate all the ports hr = WBEM_S_NO_ERROR; //Final Next will return WBEM_S_FALSE while (hr == WBEM_S_NO_ERROR) { ULONG uReturned = 0; IWbemClassObject* apObj[10]; memset(apObj, 0, sizeof(apObj)); hr = pClassObject->Next(WBEM_INFINITE, 10, reinterpret_cast<IWbemClassObject**>(apObj), &uReturned); if (SUCCEEDED(hr)) { for (ULONG n=0; n<uReturned; n++) { VARIANT varProperty1; VariantInit(&varProperty1); HRESULT hrGet = apObj[n]->Get(L"DeviceID", 0, &varProperty1, NULL, NULL); if (SUCCEEDED(hrGet) && (varProperty1.vt == VT_BSTR) && (wcslen(varProperty1.bstrVal) > 3)) { //If it looks like "COMX" then add it to the array which will be returned if ((_wcsnicmp(varProperty1.bstrVal, L"COM", 3) == 0) && IsNumeric(&(varProperty1.bstrVal[3]), TRUE)) { //Work out the port number int nPort = _wtoi(&(varProperty1.bstrVal[3])); #if defined CENUMERATESERIAL_USE_STL ports.push_back(nPort); #else ports.Add(nPort); #endif //Also get the friendly name of the port VARIANT varProperty2; VariantInit(&varProperty2); if (SUCCEEDED(apObj[n]->Get(L"Name", 0, &varProperty2, NULL, NULL)) && (varProperty2.vt == VT_BSTR)) { #if defined CENUMERATESERIAL_USE_STL #if defined _UNICODE std::wstring szName(varProperty2.bstrVal); #else CAutoHeapAlloc szAsciiValue; int nLengthA = WideCharToMultiByte(CP_ACP, 0, varProperty2.bstrVal, -1, NULL, 0, NULL, NULL); if (nLengthA) { if (szAsciiValue.Allocate(nLengthA)) WideCharToMultiByte(CP_ACP, 0, varProperty2.bstrVal, -1, static_cast<LPSTR>(szAsciiValue.m_pData), nLengthA, NULL, NULL); } std::string szName(static_cast<LPSTR>(szAsciiValue.m_pData)); #endif friendlyNames.push_back(szName); #else friendlyNames.Add(CString(varProperty2.bstrVal)); #endif } else { #if defined CENUMERATESERIAL_USE_STL friendlyNames.push_back(_T("")); #else friendlyNames.Add(_T("")); #endif } //Free up the variant; VariantClear(&varProperty2); } } //Free up the variant; VariantClear(&varProperty1); //Free up each COM interface apObj[n]->Release(); } } } //Free up the COM interface pClassObject->Release(); } //Free up the COM interface pServices->Release(); } //Free up the COM interface pLocator->Release(); } return bSuccess; }
DWORD HTTPDownload::DownloadFile() { HANDLE hLocalFile = ::CreateFile(m_FileName.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hLocalFile) { HINTERNET hRemoteFile = ::InternetConnect(m_hInternet, m_Address.c_str(), m_Port, L"", L"", INTERNET_SERVICE_HTTP, 0, NULL); if(hRemoteFile) { HINTERNET hRequest = ::HttpOpenRequest(hRemoteFile, NULL, m_URI.c_str(), NULL, NULL, NULL, INTERNET_FLAG_RELOAD, NULL); if(hRequest) { wchar_t contentLength[32]; DWORD contentLengthSize = sizeof(contentLength), index = 0; BOOL success = ::HttpSendRequest(hRequest, NULL, 0, NULL, 0); success = ::HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH, &contentLength, &contentLengthSize, &index); m_Length = ::_wtoi(contentLength); if(success) { m_EventRouter->OnConnected(m_SessionID, _bstr_t(m_Address.c_str()), m_Port, 0); DWORD bytesRead = 0, bytesWritten = 0; BYTE buffer[4096]; while(!m_Abort) { success = ::InternetReadFile(hRequest, buffer, sizeof(buffer), &bytesRead); if(!success) { m_EventRouter->OnSockErr(m_SessionID, ::GetLastError()); m_Abort = true; break; } else if(bytesRead == 0) { break; } else { ::WriteFile(hLocalFile, buffer, bytesRead, &bytesWritten, NULL); m_Progress += bytesWritten; } } } ::InternetCloseHandle(hRequest); } ::InternetCloseHandle(hRemoteFile); } ::CloseHandle(hLocalFile); } if(m_Abort) { m_EventRouter->OnTransferAborted(m_SessionID); } else { m_EventRouter->OnTransferComplete(m_SessionID); } delete this; return 0; }
BOOL CEnumerateSerial::UsingWMI(CSimpleArray<UINT>& ports, CSimpleArray<CString>& friendlyNames) #endif { //Make sure we clear out any elements which may already be in the array(s) #if defined CENUMERATESERIAL_USE_STL ports.clear(); friendlyNames.clear(); #else ports.RemoveAll(); friendlyNames.RemoveAll(); #endif //What will be the return value BOOL bSuccess = FALSE; //Create the WBEM locator ATL::CComPtr<IWbemLocator> locator; HRESULT hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&locator)); if (SUCCEEDED(hr)) { ATL::CComPtr<IWbemServices> services; hr = locator->ConnectServer(_bstr_t("\\\\.\\root\\cimv2"), NULL, NULL, NULL, 0, NULL, NULL, &services); if (SUCCEEDED(hr)) { //Execute the query ATL::CComPtr<IEnumWbemClassObject> classObject; hr = services->CreateInstanceEnum(_bstr_t("Win32_SerialPort"), WBEM_FLAG_RETURN_WBEM_COMPLETE, NULL, &classObject); if (SUCCEEDED(hr)) { bSuccess = TRUE; //Now enumerate all the ports hr = WBEM_S_NO_ERROR; //Final Next will return WBEM_S_FALSE while (hr == WBEM_S_NO_ERROR) { ULONG uReturned = 0; ATL::CComPtr<IWbemClassObject> apObj[10]; hr = classObject->Next(WBEM_INFINITE, 10, reinterpret_cast<IWbemClassObject**>(apObj), &uReturned); if (SUCCEEDED(hr)) { for (ULONG n=0; n<uReturned; n++) { ATL::CComVariant varProperty1; HRESULT hrGet = apObj[n]->Get(L"DeviceID", 0, &varProperty1, NULL, NULL); if (SUCCEEDED(hrGet) && (varProperty1.vt == VT_BSTR) && (wcslen(varProperty1.bstrVal) > 3)) { //If it looks like "COMX" then add it to the array which will be returned if ((_wcsnicmp(varProperty1.bstrVal, L"COM", 3) == 0) && IsNumeric(&(varProperty1.bstrVal[3]), TRUE)) { //Work out the port number int nPort = _wtoi(&(varProperty1.bstrVal[3])); #if defined CENUMERATESERIAL_USE_STL ports.push_back(nPort); #else ports.Add(nPort); #endif //Also get the friendly name of the port ATL::CComVariant varProperty2; if (SUCCEEDED(apObj[n]->Get(L"Name", 0, &varProperty2, NULL, NULL)) && (varProperty2.vt == VT_BSTR)) { #if defined CENUMERATESERIAL_USE_STL #if defined _UNICODE std::wstring szName(varProperty2.bstrVal); #else std::string szName(ATL::CW2A(varProperty2.bstrVal)); #endif friendlyNames.push_back(szName); #else friendlyNames.Add(CString(varProperty2.bstrVal)); #endif } else { #if defined CENUMERATESERIAL_USE_STL friendlyNames.push_back(_T("")); #else friendlyNames.Add(_T("")); #endif } } } } } } } } } return bSuccess; }
//----------------------------------------------------------------------------- // Purpose: walks the file elements in the vcproj and inserts them into configs //----------------------------------------------------------------------------- bool CVCProjConvert::ExtractFiles( IXMLDOMDocument *pDoc ) { if (!pDoc) { return false; } Assert( m_Configurations.Count() ); // some configs must be loaded first #ifdef _WIN32 CComPtr<IXMLDOMNodeList> pFiles; pDoc->getElementsByTagName( _bstr_t("File"), &pFiles); if (pFiles) { long len = 0; pFiles->get_length(&len); for ( int i=0; i<len; i++ ) { CComPtr<IXMLDOMNode> pNode; pFiles->get_item( i, &pNode); if (pNode) { CComQIPtr<IXMLDOMElement> pElem( pNode ); CUtlSymbol fileName = GetXMLAttribValue(pElem,"RelativePath"); if ( fileName.IsValid() ) { CConfiguration::FileType_e type = GetFileType( fileName.String() ); CConfiguration::CFileEntry fileEntry( fileName.String(), type ); for ( int i = 0; i < m_Configurations.Count(); i++ ) // add the file to all configs { CConfiguration & config = m_Configurations[i]; config.InsertFile( fileEntry ); } IterateFileConfigurations( pElem, fileName ); // now remove the excluded ones } } }//for } #elif _LINUX DOMNodeList *nodes = pDoc->getElementsByTagName( _bstr_t("File") ); if (nodes) { int len = nodes->getLength(); for ( int i=0; i<len; i++ ) { DOMNode *node = nodes->item(i); if (node) { CUtlSymbol fileName = GetXMLAttribValue(node,"RelativePath"); if ( fileName.IsValid() ) { char fixedFileName[ MAX_PATH ]; Q_strncpy( fixedFileName, fileName.String(), sizeof(fixedFileName) ); if ( fixedFileName[0] == '.' && fixedFileName[1] == '\\' ) { Q_memmove( fixedFileName, fixedFileName+2, sizeof(fixedFileName)-2 ); } Q_FixSlashes( fixedFileName ); FindFileCaseInsensitive( fixedFileName, sizeof(fixedFileName) ); CConfiguration::FileType_e type = GetFileType( fileName.String() ); CConfiguration::CFileEntry fileEntry( fixedFileName, type ); for ( int i = 0; i < m_Configurations.Count(); i++ ) // add the file to all configs { CConfiguration & config = m_Configurations[i]; config.InsertFile( fileEntry ); } IterateFileConfigurations( node, fixedFileName ); // now remove the excluded ones } } }//for } #endif return true; }
void CXTaskDlg::Init_CtrlList() { CXsvrDlg *pDlg = (CXsvrDlg*)AfxGetMainWnd(); m_ctrlList.InsertColumn(0, "任务 ID", LVCFMT_LEFT, 66); m_ctrlList.InsertColumn(1, "发送内容", LVCFMT_LEFT, 88); m_ctrlList.InsertColumn(2, "任务时间", LVCFMT_LEFT, 128); m_ctrlList.InsertColumn(3, "重复次数", LVCFMT_LEFT, 98); // ***************************************************************** // 读取数据库并显示用户信息 // ***************************************************************** _RecordsetPtr pRs; pRs.CreateInstance(__uuidof(Recordset)); char * szSQL = "SELECT * FROM task_query"; variant_t var[4]; CString str; int nIdx = 0; LVITEM lvi; try { pRs->Open(szSQL, pDlg->m_pConn.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText); // 如果数据库是空白的 if (pRs->adoEOF) { pDlg->AddErrorInfo("暂无用户记录!"); pRs->Close(); pRs.Release(); return; } else { // 读取并显示数据库里的用户信息 while (!pRs->adoEOF) { XTask *pTask = new XTask; var[0] = pRs->GetCollect(_variant_t("x_task_id")); if (var[0].vt != VT_NULL) { str = (LPCTSTR)_bstr_t(var[0]); lvi.mask = LVIF_IMAGE | LVIF_TEXT; lvi.iItem = 0xff; lvi.iSubItem = 0; lvi.pszText = (LPTSTR)(LPCTSTR)(str); lvi.iImage = I_IMAGECALLBACK; nIdx = m_ctrlList.InsertItem(&lvi); pTask->nID = atoi((LPCTSTR)str); if ((int)m_nUniqueID < pTask->nID) { m_nUniqueID = pTask->nID; } } var[1] = pRs->GetCollect(_variant_t("x_content")); if (var[1].vt != VT_NULL) { str = (LPCTSTR)_bstr_t(var[1]); m_ctrlList.SetItemText(nIdx, 1, str); pTask->szContent = new char[str.GetLength()+1]; strcpy(pTask->szContent, (LPCTSTR)str); } var[2] = pRs->GetCollect(_variant_t("x_activate_time")); if (var[2].vt != VT_NULL) { str = (LPCTSTR)_bstr_t(var[2]); m_ctrlList.SetItemText(nIdx, 2, str); pTask->SetDate(str); pTask->SetTime(str); } // 获取用户所在分组 var[3] = pRs->GetCollect(_variant_t("x_frequency")); if (var[3].vt != VT_NULL) { str = (LPCTSTR)_bstr_t(var[3]); pTask->nFrequency = atoi((LPCTSTR)str); if (pTask->nFrequency == 0) { m_ctrlList.SetItemText(nIdx, 3, "每天"); } else { m_ctrlList.SetItemText(nIdx, 3, "1次"); } } m_listTask.push_back(pTask); pRs->MoveNext(); } } } catch (_com_error e) { pDlg->AddErrorInfo(e.ErrorMessage()); } pRs->Close(); pRs.Release(); }
void MakeCopy(_StockUpdateParams & rp, StockParams & vp) { rp->Exchange = _bstr_t("").copy(); rp->Stock = (_bstr_t(vp.Stock).copy()); }
CA_API UINT __stdcall TemplateFiles_Immediate(MSIHANDLE hInstall) { MSI_EXCEPTION_HANDLER_PROLOG; MsiInstall msiInstall(hInstall); // combined xml document AppSecInc::Xml::XmlDocument combined_xml_document; combined_xml_document.Create(); MSXML2::IXMLDOMNodePtr combined_xml_root = combined_xml_document.AppendChild(L"TemplateFiles"); std::wstring xml = msiInstall.GetViewData(L"SELECT * FROM `TemplateFiles`"); AppSecInc::Xml::XmlDocument xmlDocument; xmlDocument.LoadXml(xml); { MSXML2::IXMLDOMNodeListPtr rows = xmlDocument.SelectNodes(L"//Row"); MSXML2::IXMLDOMNodePtr row = NULL; while (NULL != (row = rows->nextNode())) { // id std::wstring templatefile_id = xmlDocument.GetNodeValue(L"Data[@Column=\"Id\"]", row, L""); // component id std::wstring component_id = xmlDocument.GetNodeValue(L"Data[@Column=\"ComponentId\"]", row, L""); // node condition std::wstring condition = xmlDocument.GetNodeValue(L"Data[@Column=\"Condition\"]", row); // operational attributes long attributes = AppSecInc::StringUtils::stringToLong(xmlDocument.GetNodeValue(L"Data[@Column=\"Attributes\"]", row)); // no condition (executes by default) or condition evaluates to true bool execute_per_condition = condition.empty() || msiInstall.EvaluateCondition(condition); if (! condition.empty()) { // set the evaluated value for debugging purposes xmlDocument.SelectNode(L"Data[@Column=\"Condition\"]", row)->text = _bstr_t(execute_per_condition ? L"1" : L"0"); } // execute on install bool execute_per_component_install = (component_id.empty() || msiInstall.IsComponentInstalling(component_id)); // execute on uninstall bool execute_per_component_uninstall = (component_id.empty() || msiInstall.IsComponentUnInstalling(component_id)); // execute on reinstall bool execute_per_component_reinstall = (component_id.empty() || msiInstall.IsComponentReInstalling(component_id)); bool execute = execute_per_condition && ( (execute_per_component_install && (attributes & ExecuteOnInstall) && msiInstall.IsInstalling()) || (execute_per_component_uninstall && (attributes & ExecuteOnUnInstall) && msiInstall.IsUnInstalling()) || (execute_per_component_reinstall && (attributes & ExecuteOnReInstall) && msiInstall.IsReInstalling()) ); MSXML2::IXMLDOMNodePtr templatefile_node = combined_xml_document.AppendChild(L"TemplateFile", combined_xml_root); combined_xml_document.SetAttribute(L"id", templatefile_id, templatefile_node); std::wstring source = xmlDocument.GetNodeValue(L"Data[@Column=\"Source\"]", row); std::wstring target = xmlDocument.GetNodeValue(L"Data[@Column=\"Target\"]", row, source); combined_xml_document.AppendChild(L"Source", templatefile_node)->text = _bstr_t(source.c_str()); combined_xml_document.AppendChild(L"Target", templatefile_node)->text = _bstr_t(target.c_str()); combined_xml_document.SetAttribute(L"execute", execute ? L"true" : L"false", templatefile_node); MSXML2::IXMLDOMNodePtr properties_node = combined_xml_document.AppendChild(L"Properties", templatefile_node); // append built-in properties { AppSecInc::Xml::XmlDocument xmlPropertiesDocument; xmlPropertiesDocument.LoadXml(msiInstall.GetViewData(L"SELECT * FROM `Property`")); MSXML2::IXMLDOMNodeListPtr property_rows = xmlPropertiesDocument.SelectNodes(L"//Row"); MSXML2::IXMLDOMNodePtr property_row = NULL; while (NULL != (property_row = property_rows->nextNode())) { std::wstring name = xmlPropertiesDocument.GetNodeValue(L"Data[@Column=\"Property\"]", property_row); std::wstring value = xmlPropertiesDocument.GetNodeValue(L"Data[@Column=\"Value\"]", property_row); MSXML2::IXMLDOMNodePtr property_node = combined_xml_document.AppendChild(L"Property", properties_node); combined_xml_document.SetAttribute(L"name", name, property_node); combined_xml_document.SetAttribute(L"value", value, property_node); } } // append properties from this TemplateFile { AppSecInc::Xml::XmlDocument xmlPropertiesDocument; xmlPropertiesDocument.LoadXml(msiInstall.GetViewData(L"SELECT * FROM `TemplateFileProperties`")); MSXML2::IXMLDOMNodeListPtr property_rows = xmlPropertiesDocument.SelectNodes(L"//Row"); MSXML2::IXMLDOMNodePtr property_row = NULL; while (NULL != (property_row = property_rows->nextNode())) { // \todo Change XPATH to fetch only rows that match ID std::wstring id = xmlPropertiesDocument.GetNodeValue(L"Data[@Column=\"TemplateFileId\"]", property_row); if (id != templatefile_id) continue; std::wstring name = xmlPropertiesDocument.GetNodeValue(L"Data[@Column=\"Name\"]", property_row); std::wstring value = xmlPropertiesDocument.GetNodeValue(L"Data[@Column=\"Value\"]", property_row); std::wstring escape = xmlPropertiesDocument.GetNodeValue(L"Data[@Column=\"Escape\"]", property_row); MSXML2::IXMLDOMNodePtr property_node = combined_xml_document.AppendChild(L"Property", properties_node); combined_xml_document.SetAttribute(L"name", name, property_node); combined_xml_document.SetAttribute(L"value", value, property_node); combined_xml_document.SetAttribute(L"escape", escape, property_node); } } } } msiInstall.SetActionData(L"TemplateFiles_Deferred", combined_xml_document.GetXml()); MSI_EXCEPTION_HANDLER_EPILOG; return ERROR_SUCCESS; }
void MakeCopy(_FutureOptionUpdateParams & ri, FuturesOptionParams & vp) { ri->Exchange = (_bstr_t(vp.Exchange).copy()); ri->FutureSymbol = (_bstr_t(vp.FutureSymbol).copy()); }
STDMETHODIMP CXMLDOMDocument::load(VARIANT xmlSource, VARIANT_BOOL *isSuccessful) { ATLTRACE(_T("CXMLDOMDocument::load\n")); if (NULL == isSuccessful) return E_POINTER; *isSuccessful = VARIANT_FALSE; if (V_VT(&xmlSource) != VT_BSTR && V_VT(&xmlSource) != VT_DISPATCH && V_VT(&xmlSource) != (VT_ARRAY | VT_VARIANT) && V_VT(&xmlSource) != (VT_ARRAY | VT_UI1) && V_VT(&xmlSource) != VT_UNKNOWN) return E_INVALIDARG; // do not start another thread if there is another active if (NULL != m_hParseThread) { DWORD exitCode = 0; BOOL rc = ::GetExitCodeThread(m_hParseThread, &exitCode); if (!rc || STILL_ACTIVE == exitCode) return S_OK; ::CloseHandle(m_hParseThread); m_hParseThread = NULL; } HRESULT hr = S_OK; m_bAbort = false; m_FileName = _T(""); m_xml = _T(""); m_TmpDocument = 0; m_bThreadValidate = m_bValidate; if (V_VT(&xmlSource) == VT_BSTR) { m_FileName = V_BSTR(&xmlSource); if (0 == m_FileName.length()) return E_INVALIDARG; // see if the file is relative path if (!PathIsURL(m_FileName) && PathIsRelative(m_FileName)) { // try appending baseurl if exists _bstr_t baseURL; if (S_OK == GetBaseURL(baseURL)) { // change any backslashes to slashes LPTSTR loc = _tcschr(m_FileName,_T('\\')); while (loc != NULL) { *loc = _T('/'); loc = _tcschr(m_FileName,_T('\\')); } m_FileName = baseURL + _T("/") + m_FileName; } else { TCHAR szCurDir[MAX_PATH]; GetCurrentDirectory(MAX_PATH,szCurDir); m_FileName=_bstr_t(szCurDir) + _T("\\") + m_FileName; } } } else if (V_VT(&xmlSource) == VT_UNKNOWN) { CComQIPtr<IStream,&IID_IStream> pS(V_UNKNOWN(&xmlSource)); if (!pS) return E_INVALIDARG; CComBSTR b; hr = b.ReadFromStream(pS); if (S_OK != hr) return hr; m_xml = b; if (0 == m_xml.length()) return E_INVALIDARG; } else if (V_VT(&xmlSource) == VT_DISPATCH) { CComQIPtr<IXMLDOMDocument,&IID_IXMLDOMDocument> pDoc(V_DISPATCH(&xmlSource)); if (!pDoc) return E_INVALIDARG; BSTR b = NULL; hr = pDoc->get_xml(&b); if (S_OK != hr) return hr; m_xml = b; ::SysFreeString(b); if (0 == m_xml.length()) return E_INVALIDARG; } else if (V_VT(&xmlSource) == (VT_ARRAY | VT_VARIANT)) { SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (xmlSource.byref); if (NULL == pArray) return E_INVALIDARG; long lLBoundVar = 0; long lUBoundVar = 0; UINT dims = ::SafeArrayGetDim(pArray); if (dims == 0) return E_INVALIDARG; hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar); if (S_OK != hr) return hr; hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar); if (S_OK != hr) return hr; if (lUBoundVar >= lLBoundVar) { VARIANT *pIndex = NULL; hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex)); if (S_OK != hr) return hr; int length = lUBoundVar-lLBoundVar+2; BYTE *body = new BYTE[length]; for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i) { VARIANT var = pIndex[i]; if (V_VT(&var) != VT_UI1) { hr = E_INVALIDARG; break; } body[i] = V_UI1(&var); } body[length-1] = 0; ::SafeArrayUnaccessData(pArray); if (S_OK != hr) { delete [] body; return hr; } m_xml = reinterpret_cast<char*> (body); delete [] body; if (0 == m_xml.length()) return E_INVALIDARG; } } else if (V_VT(&xmlSource) == (VT_ARRAY | VT_UI1)) { SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (xmlSource.byref); if (NULL == pArray) return E_INVALIDARG; long lLBoundVar = 0; long lUBoundVar = 0; UINT dims = ::SafeArrayGetDim(pArray); if (dims == 0) return E_INVALIDARG; hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar); if (S_OK != hr) return hr; hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar); if (S_OK != hr) return hr; if (lUBoundVar >= lLBoundVar) { BYTE *pIndex = NULL; hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex)); if (S_OK != hr) return hr; int length = lUBoundVar-lLBoundVar+2; BYTE *body = new BYTE[length]; for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i) body[i] = pIndex[i]; body[length-1] = 0; ::SafeArrayUnaccessData(pArray); m_xml = reinterpret_cast<char*> (body); delete [] body; if (0 == m_xml.length()) return E_INVALIDARG; } } UINT nthreadID = 0; m_hParseThread = reinterpret_cast<HANDLE> (_beginthreadex(NULL, 0, CXMLDOMDocument::ParseThread, (void *) this, 0, &nthreadID)); if (NULL == m_hParseThread) return S_OK; if (m_bAsync) { *isSuccessful = VARIANT_TRUE; return S_OK; } bool bWait = true; while (bWait) { DWORD dwEvt = MsgWaitForMultipleObjects(1,&m_hParseThread,FALSE,INFINITE,QS_ALLINPUT); switch(dwEvt) { case WAIT_OBJECT_0: bWait = false; break; case WAIT_OBJECT_0 + 1: { MSG msg; while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (WM_CLOSE == msg.message || WM_QUIT == msg.message) { bWait = false; m_bAbort = true; break; } else { PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); TranslateMessage(&msg); DispatchMessage(&msg); } } break; } default: m_bAbort = true; bWait = false; break; } } if (m_bAbort) return S_OK; if (m_bParseError) return hr; if(m_Document) delete m_Document; m_Document = m_TmpDocument; m_TmpDocument = 0; m_url = m_FileName; *isSuccessful = VARIANT_TRUE; return hr; }
void CPDTestHelper::SaveDocument(const CStdString& sDocumentName, const CStdString& sAppID, CStdString& sTestDocID) { USES_CONVERSION; DOCSObjects::IApplicationPtr pApp( __uuidof( DOCSObjects::Application )); pApp->PutDefParentWindow( 0 ); DOCSObjects::ILibrariesPtr pLibs = pApp->GetLibraries(); DOCSObjects::ILibraryPtr pLib = pApp->GetCurrentLibrary(); DOCSObjects::IDOCSFormsPtr pForms = pLib->GetForms(); DOCSObjects::IProfilePtr pBaseProf = NULL; DOCSObjects::IDOCSFormPtr pForm = NULL; int iCount = pForms->GetCount(); bool bFoundProf = FALSE; _variant_t vtIndex; vtIndex.vt = VT_I4; for (vtIndex.lVal = 1; (vtIndex.lVal <= iCount) && (!bFoundProf); vtIndex.lVal++) { pForm = pForms->GetItem(vtIndex); if (pForm->GetType() & DOCSObjects::FT_DEFAULT_PROFILE) { // ATLTRACE("Found default form,\n"); // ATLTRACE("Form %2.2d, Type = 0x%02x, Name = %s\n", vtIndex.lVal, pForm->GetType(), (LPCTSTR) pForm->GetName()); pBaseProf = pLib->CreateProfile(pForm->GetName()); bFoundProf = TRUE; } } // TT - I assume that there should always be a default profile // but lets protect ourselves anyway. if (pBaseProf == NULL) { // ATLTRACE("No default form, Default form type = 0x%02X\n", FT_DEFAULT_PROFILE); pBaseProf = pLib->CreateProfile( _bstr_t( _T("LAWPROF") )); } DOCSObjects::IColumnsPtr pCols = pBaseProf->GetColumns(); DOCSObjects::IColumnPtr pCol = pCols->GetItem( _variant_t( _T("APP_ID") )); pCol->PutValue( _variant_t( T2CW(sAppID.c_str()) ) ); pCol = pCols->GetItem( _variant_t( _T("DOCNAME") )); pCol->PutValue( _variant_t( sDocumentName.c_str() ) ); pCol = pCols->GetItem( _variant_t( _T("TYPE_ID") )); pCol->PutValue( _variant_t( L"MEMO")); pCol = pCols->GetItem( L"AUTHOR_ID"); pCol->PutValue(L"pair"); pCol = pCols->GetItem(L"TYPIST_ID"); pCol->PutValue(L"pair"); pCol = pCols->GetItem(L"CLIENT_ID"); pCol->PutValue(L"TEST"); pCol = pCols->GetItem(L"MATTER_ID"); pCol->PutValue(L"TEST"); VARIANT_BOOL vb = pBaseProf->Save( DOCSObjects::OF_NORMAL ); assertTest(vb); DOCSObjects::IVersionPtr pVer = pBaseProf->GetCurrentVersion(); BSTR sFilePath = pVer->GetFilePath(); CStdString sDest(sFilePath); SysFreeString(sFilePath); bool bSuccess = false; if (sAppID.CompareNoCase(_T("ACROBAT")) == 0) { bSuccess = (CopyFile(TEST_PDF_FILE,sDest.c_str(),false)!=0); } else { bSuccess = (CopyFile(TEST_DOC_FILE,sDest.c_str(),false)!=0); } assertTest(bSuccess); LONG lDocID = pBaseProf->GetDocNumber(); BSTR bsLibName = pLib->GetName(); CStdString sLibName(bsLibName); SysFreeString(bsLibName); sTestDocID.Format(_T("PowerDocs://%s/%d/1"),sLibName.c_str(),lDocID); pVer->UploadFile( NULL ); pVer->UnlockVersion( DOCSObjects::OF_NORMAL ); pBaseProf->ReleaseDoc(); }
/** * Download and install from a remote location using HTTP. * @param url the url indicating the location of the widget. * @param widget receives the constructed widget on success. */ STDMETHODIMP CBondiWidgetLibrary::RemoteInstall(BSTR url, IBondiWidget** widget) { HRESULT hRes = S_OK; try { TCHAR appDataPath[MAX_PATH]; WidgetUtils::GetAppFolder(NULL,appDataPath); TCHAR canonicalURL[1024]; DWORD nSize = 1024; InternetCanonicalizeUrl(url, canonicalURL, &nSize, ICU_BROWSER_MODE); // Check for an internet connection. if (InternetAttemptConnect(0) != ERROR_SUCCESS) BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("no internet connection found")); // Open a connection. HINTERNET hINet = InternetOpen(agentName,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE); if (hINet != 0) { HANDLE hConnection = ConnectToNetwork(25); if (hConnection != NULL) { // Attempt to access the resource at the url. DWORD options = INTERNET_FLAG_NEED_FILE|INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_RESYNCHRONIZE|INTERNET_FLAG_RELOAD; HINTERNET hFile = InternetOpenUrl( hINet, canonicalURL, NULL, 0, options, 0 ); if (hFile != 0) { // Determine the file name to store the downloaded widget resource. TCHAR fName[MAX_PATH]; _tsplitpath_s(url, NULL, 0, NULL, 0, fName, _MAX_FNAME, NULL, 0); // Create the target local file. _bstr_t downloadPath = appDataPath + _bstr_t("\\") + _bstr_t(fName) + _bstr_t(".wgt"); HANDLE target = ::CreateFile(downloadPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); // Read chunks. BYTE buffer[1024]; DWORD dwRead; while (::InternetReadFile( hFile, buffer, 1024, &dwRead ) ) { if ( dwRead == 0 ) break; ::WriteFile(target,buffer,dwRead,&dwRead,NULL); } ::CloseHandle(target); InternetCloseHandle(hFile); CComObject<CBondiWidget>* newWidget; BONDI_CHECK_ERROR(CComObject<CBondiWidget>::CreateInstance(&newWidget),(IBondiWidgetLibrary*)this); newWidget->AddRef(); // Do the installation. _bstr_t locale("en"); hRes = newWidget->Install(downloadPath,locale,VARIANT_FALSE,VARIANT_FALSE); BONDI_CHECK_ERROR(hRes,(IBondiWidget*)newWidget); if (hRes == S_OK) { // Set the install URL. CComPtr<IBondiWidgetAppConfig> appConfig; BONDI_CHECK_ERROR(newWidget->get_AppSettings(&appConfig),(IBondiWidget*)newWidget); if (appConfig != NULL) BONDI_CHECK_ERROR(appConfig->PutBondiSetting(_T("bondi.installUri"),canonicalURL,VARIANT_TRUE),appConfig); newWidget->InitialiseAppSettings(); // We've finished with the temporary downloaded resource. ::DeleteFile(downloadPath); *widget = (IBondiWidget*)newWidget; } else { // Didn't install (probably because of an existing widget). *widget = NULL; } } else { DWORD err = GetLastError(); BONDI_RAISE_ERROR(E_BONDI_WIDGET_URL_OPEN_FAILED,_T("couldn't open url: ") + CString(canonicalURL)); } #ifdef UNDER_CE ConnMgrReleaseConnection(hConnection,1); CloseHandle(hConnection); #endif } InternetCloseHandle(hINet); } else { BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("error opening internet connection")); } } catch (_com_error& err) { hRes = BONDI_SET_ERROR(err,"CBondiWidgetLibrary::RemoteInstall - COM exception"); } catch (...) { hRes = BONDI_SET_ERROR(E_FAIL,"CBondiWidgetLibrary::RemoteInstall - C++ exception"); } return hRes; }
int COpcAdapter::ReadOPCSettings() { try { // Read OPC Server details COPCBaseClass::ReadOPCSettings(""); _nFakeSpindle= _config.GetSymbolValue("OPCSERVER.FakeSpindle", "0").toNumber<long>(); _nAlarmsEnabled= _config.GetSymbolValue("OPCSERVER.AlarmsEnabled", "0").toNumber<long>(); _nMultiSpindle= _config.GetSymbolValue("OPCSERVER.MultiSpindle", "0").toNumber<long>(); if(_sTagSectionName.empty()) throw std::exception(_T("Error: OPCSERVER Tag name Undefined\n")); if(_opcservermachine.empty()) throw std::exception(_T("Error: [OPCSERVER] Opc Server Machine (IP) Undefined\n")); _sClsid= GetSymbolValue(_sTagSectionName, "CLSID", ""); _sClsid = "{" +_sClsid + "}"; if(FAILED(CLSIDFromString(_bstr_t(_sClsid.c_str()) , &_gOpcServerClsid))) throw std::exception("Misformed or mistyped OPC Server Class ID\n"); _gszOPCServerName= GetSymbolValue(_sTagSectionName, "SERVERNAME", ""); _gszCncControllerProcessName= GetSymbolValue(_sTagSectionName, "CNCProcessName", ""); _CNCTaskListCmd = GetSymbolValue(_sTagSectionName, "CNCTaskListCmd", ""); // assume no remote task list command // Now parse the tag information into MTConnect information std::vector<std::string> tags = GetSectionKeys(_sTagSectionName); if(tags.size() < 1) throw std::exception(StdStringFormat("Error: No [%s] Section\n", _sTagSectionName.c_str()).c_str()); for(int i=0; i<tags.size(); i++) { VarTypes vt; // make sure its is an OPC Tag if(tags[i].find(_T("Tag.")) == 0) { OpcItem * item = new OpcItem(); item->_alias=tags[i]; item->_alias=ReplaceOnce(item->_alias, _T("Tag."), _T("")); item->vt=VT_BSTR; if(item->_alias.find(_T("Enum."))==0) { item->_alias=ReplaceOnce(item->_alias, _T("Enum."), _T("")); item->_subtype="enumeration"; } else if(item->_alias.find(_T("Const."))==0) { item->_alias=ReplaceOnce(item->_alias,_T("Const."), _T("")); item->vt= VT_USERDEFINED; } else if(item->_alias.find(_T("Prog."))==0) { item->_alias=ReplaceOnce(item->_alias,_T("Prog."), _T("")); item->vt= VT_USERDEFINED; item->_subtype="program"; } if(item->_alias.find(_T("Sample."))==0) { item->_alias=ReplaceOnce(item->_alias,_T("Sample."), _T("")); item->_type=_T("Sample"); //_mtcagent->AddSample(this->_device, item->_alias); } else if(item->_alias.find(_T("Event."))==0) { item->_alias=ReplaceOnce(item->_alias,_T("Event."), _T("")); item->_type=_T("Event"); //_mtcagent->AddEvent(this->_device, item->_alias); } else if(item->_alias.find(_T("OPC."))==0) // reads opc values does not send to MT Connect { item->_alias=ReplaceOnce(item->_alias, _T("OPC."), _T("")); // OPC value for scripting item->_type=_T("OPC"); } else if(item->_alias.find(_T("Condition."))==0) { item->_alias=ReplaceOnce(item->_alias,_T("Condition."), _T("")); item->_type="Condition"; //_mtcagent->AddCondition(this->_device, item->_alias); } std::string tmp= GetSymbolValue(_sTagSectionName, tags[i],""); item->_tagname=tmp; opcitems.push_back(item); } } // Test to see if we have a power, if not add one. //if(opcitems.FindItem("power")==NULL) // _mtcagent->AddEvent(this->_device, "power"); #ifdef ALARMS //Alarm Management _alarmconfig.load(ExeDirectory() + "English\\Alarms.cfg"); #endif } catch(std::string errmsg) { _gszStartupErrors+=errmsg; ErrorMessage( errmsg + "\n"); return E_FAIL; } catch(std::exception e) { ErrorMessage( e.what()); return E_FAIL; } catch(...) { ErrorMessage( "ReadOPCSettings() OPC Items Ini error \n"); return E_FAIL; } GLogger.LogMessage(StdStringFormat("COpcAdapter::ReadOPCSettings() Done for IP = %s \n",_device.c_str())); return S_OK; }
DWORD CPublisher::StoreInDatabase(CTrade& Trade) { USES_CONVERSION; DWORD dwTries = MAX_DBRECONNECTION_TRIES; bool bOk = false; DWORD dwRes = ERROR_SUCCESS; long lMaxSeqNum; long lMinSeqNum; long lStructureMissed; TDBFailsStore::iterator it; do { try { switch(Trade.siStatus) { case NEW_FLAG: case UPD_FLAG: { CClientRecordset rs; CStoredProc<> sp(m_ConnectionDest, L"usp_TradeFeed_1_New"); sp << Trade.vcAcronym; sp << _bstr_t(_variant_t((long)Trade.nTradeID)); sp << (int)( Trade.vcAction == ACTION_BUY ? 1 : 0 ); sp << (int)Trade.fUnits; sp << Trade.fPrice; sp << Trade.dtTradeDate; sp << Trade.vcSymbol; sp << int(0); // Contract Type s Stock sp << CDBNull(); sp << CDBNull(); sp << CDBNull(); sp << CDBNull(); sp << CDBNull(); sp << (int)1; //update enabled sp << CDBNull(); rs.Open (sp); if (rs.IsEOF()) { rs.Close(); _com_issue_error(E_FAIL); } lMaxSeqNum = rs[L"iMaxSeqNum"]; lMinSeqNum = rs[L"iMinSeqNum"]; lStructureMissed = rs[L"iStructureMissed"]; rs.Close(); if ( lMaxSeqNum == -1 && lStructureMissed == -1 ) { if (lMinSeqNum == -1) // unknown error { _com_issue_error( E_FAIL ); } else { dwRes = ERROR_ALREADY_EXISTS; if ( ReProcessTrade(Trade, lMinSeqNum) == ERROR_SUCCESS ) dwRes = ERROR_SUCCESS; break; } } CTracer::Trace(CTracer::enMtInformation, _T("Trade '%d' stored in database."), Trade.nTradeID); InterlockedIncrement((LPLONG)&m_dwDBStored); CStoredProc<> sp_get(m_ConnectionDest, L"usp_TradeSeq_Get"); sp_get << (int)lMinSeqNum; sp_get << (int)lMaxSeqNum; sp_get << CDBNull(); sp_get << (UCHAR)1; rs.Open (sp_get); if(rs.IsEOF()) { CTracer::Trace(CTracer::enMtError, _T("Failed to retrieve trade from database - trade with ExecID '%d' does not exist."), Trade.nTradeID); dwRes = ERROR_NO_DATA_DETECTED; } else { HRESULT hRes; while (!rs.IsEOF() && GetMode() == MODE_INTRADAY) { if ( FAILED(hRes = FillTradeUpdate(rs, Trade)) ) { CTracer::Trace(CTracer::enMtError, _T("Failed to fill TradeUpdate message.")); dwRes = ERROR_INVALID_PARAMETER; } else if(hRes == S_FALSE) { CTracer::Trace(CTracer::enMtError, _T("Failed to retrieve trade from database - trade with ExecID '%d' does not exist."), Trade.nTradeID); dwRes = ERROR_NO_DATA_DETECTED; } Publish(Trade); if (::WaitForSingleObject(GetStopEventHandle(), CSettings::m_nPublishDelayTime) == WAIT_OBJECT_0) { return _ERROR_NEED_TO_STOP; } rs.MoveNext(); } } } break; case DEL_FLAG: { CClientRecordset rs; CStoredProc<> sp(m_ConnectionDest, L"usp_TradeFeed_1_Del"); sp << _bstr_t(_variant_t((long)Trade.nTradeID)); sp << Trade.dtTradeDate; rs.Open (sp); if(rs.IsEOF()) { rs.Close(); _com_issue_error(E_FAIL); } lMaxSeqNum = rs[L"iMaxSeqNum"]; lMinSeqNum = rs[L"iMinSeqNum"]; rs.Close(); if (lMaxSeqNum == -1 && lMinSeqNum == -1) // unknown error _com_issue_error(E_FAIL); if (lMinSeqNum == -1) // already exists { dwRes = ERROR_ALREADY_EXISTS; if ( ReProcessTrade(Trade, lMaxSeqNum) == ERROR_SUCCESS ) dwRes = ERROR_SUCCESS; break; } if (lMaxSeqNum == -1) { CTracer::Trace(CTracer::enMtWarning, _T("Failed to delete trade in database - trade with the same ExecID '%d' either does not exist or was already deleted."), Trade.nTradeID); dwRes = ERROR_NOT_FOUND; break; } CTracer::Trace(CTracer::enMtInformation, _T("Trade '%d' deleted from database."), Trade.nTradeID); InterlockedIncrement((LPLONG)&m_dwDBDeleted); CStoredProc<> sp_get(m_ConnectionDest, L"usp_TradeSeq_Get"); sp_get << (int)lMaxSeqNum; sp_get << (int)lMaxSeqNum; sp_get << CDBNull(); sp_get << (unsigned char)1; rs.Open (sp_get); if(rs.IsEOF()) { CTracer::Trace(CTracer::enMtError, _T("Failed to retrieve trade from database - trade with ExecID '%d' does not exist."), Trade.nTradeID); dwRes = ERROR_NO_DATA_DETECTED; } else if (GetMode() == MODE_INTRADAY) { HRESULT hRes; if(FAILED(hRes = FillTradeUpdate(rs, Trade))) { CTracer::Trace(CTracer::enMtError, _T("Failed to fill TradeUpdate message.")); dwRes = ERROR_INVALID_PARAMETER; } else if(hRes == S_FALSE) { CTracer::Trace(CTracer::enMtError, _T("Failed to retrieve trade from database - trade with the same ExecID '%d' does not exist."), Trade.nTradeID); dwRes = ERROR_NO_DATA_DETECTED; } Publish(Trade); if (::WaitForSingleObject(GetStopEventHandle(), CSettings::m_nPublishDelayTime) == WAIT_OBJECT_0) { return _ERROR_NEED_TO_STOP; } } break; } default: dwRes = ERROR_INVALID_PARAMETER; break; } bOk = true; } catch(_com_error& e) { _bstr_t bsError = "Failed to store trade in database : " + m_ConnectionDest.GetErrorMessage(); CTracer::Trace(CTracer::enMtError, bsError); pair<TDBFailsStore::iterator, bool> pairResult = m_DBFails.insert(Trade.nTradeID); if (--dwTries) { Reconnect(); } else { CTracer::Trace(CTracer::enMtError, _T("CRITICAL ERROR : FAILED TO STORE TRADE IN DATABASE.")); if(false)//Uncomment this Oleg StoreInFile(Trade) != 0 { CTracer::Trace(CTracer::enMtError, _T("CRITICAL ERROR : FAILED TO STORE TRADE IN FILE.")); CTracer::Trace(CTracer::enMtError, _T("MANUAL INTERVENTION IS REQUIRED. THE APPLICATION IS STOPPED.")); ExitProcess(-1); } else { BroadcastError(e.Error(), bsError); dwRes = ERROR_REMOTE_STORAGE_NOT_ACTIVE; bOk = true; } } } } while(!bOk); return dwRes; };
BOOL CDLsyn::upClassFileToLocal(CString cid){ CConndb db; CString gsql; gsql.Format(_T("select distancecid from class where id=%s"),cid); db.search(gsql); if(db.m_query->eof()) return false; int i=0; _variant_t var; CString rid; while(!db.m_query->eof()) { var=db.m_query->getStringField(_T("distancecid")); if(var.vt!=VT_NULL) rid=(LPCSTR)_bstr_t(var); db.m_query->nextRow(); } CString strFormData=_T("ac=upclasstoloc&cid="); strFormData+=rid; char *tmpdata=unicodeToUtf8(strFormData.GetBuffer()); BOOL result = m_pFile->SendRequest(m_strHeaders,(LPVOID)tmpdata,strlen(tmpdata)); if(result == FALSE) return false; free(tmpdata); DWORD dwRet; m_pFile->QueryInfoStatusCode(dwRet); //返回错误没处理! 哈哈 CStringA m_strHtml=""; char szBuff[1024]; UINT nRead; while ((nRead = m_pFile->Read(szBuff,1024))>0) { m_strHtml+=CStringA(szBuff,nRead); memset(szBuff,'\0',1024); } char *retdata=m_strHtml.GetBuffer();//UTF8ToUnicode(m_strHtml.GetBuffer());//"[{\"term_id\":\"1\",\"name\":\"\u672a\u5206\u7c7b\"},{\"term_id\":\"4\",\"name\":\"\u7f51\u7edc\u5b89\u5168\"}]";//unicodeToUtf8(m_strHtml.GetBuffer()); Json::Reader reader; Json::Value value; //reader.parse(m_strHtml.GetBuffer(), value); if(reader.parse(retdata, value)) { CString sql; std::string tmpvalue; for(int i=0; i<value.size(); i++) { tmpvalue = value[i]["post_title"].asString(); wstring titlename=UTF8ToUnicode(tmpvalue); tmpvalue = value[i]["post_content"].asString(); CString contenttext=UTF8ToUnicode(tmpvalue).c_str(); //tmpvalue = value[i]["name"].asString(); //wstring rclassid=UTF8ToUnicode(tmpvalue); //tmpvalue = value[i]["name"].asString(); //wstring data=UTF8ToUnicode(tmpvalue); tmpvalue = value[i]["uniquetag"].asString(); wstring uniquetag=UTF8ToUnicode(tmpvalue); tmpvalue = value[i]["post_date"].asString(); wstring post_date=UTF8ToUnicode(tmpvalue); //tmpvalue = value[i]["name"].asString(); //wstring artype=UTF8ToUnicode(tmpvalue); //tmpvalue = value[i]["name"].asString(); //wstring m_keyword=UTF8ToUnicode(tmpvalue); contenttext.Replace(_T("'"),_T("''")); if(uniquetag.empty()){ SYSTEMTIME sysTime; GetLocalTime(&sysTime); CTime m_tTime(sysTime); time_t unixTime = m_tTime.GetTime(); CString utag; utag.Format(_T("%d"),unixTime); sql.Format(_T("insert into articles (title,content,addtime,classid,artitletype,uniquetag) values ('%s','%s','%s','%s','txt','%s')"), titlename.c_str(),contenttext.GetBuffer(),post_date.c_str(),cid,utag); //db.excuteSql(sql); db.insert(sql); }else{ sql.Format(_T("update articles set title='%s',content='%s',addtime='%s' where uniquetag=%s"), titlename.c_str(),contenttext.GetBuffer(),post_date.c_str(),uniquetag.c_str()); db.excuteSql(sql); } } } if (dwRet == HTTP_STATUS_OK) { return true; } return true; }
CXMiLFilesControl::CSiteItem * CXMiLFilesControl::FromElement(CSiteDir* pParentDir, ILDOMElement* recordset) { CSiteItem* pItem; BSTR b; recordset->getAttribute(L"type", &b); BYTE type = (long)_variant_t(_bstr_t(b, false)); recordset->getAttribute(L"filename", &b); _bstr_t filename = _bstr_t(b, false); if (type == 1) // Directory { CSiteDir* pDir = new CSiteDir; pItem = pDir; } else if (type == 2) // File { CSiteFile* pFile = new CSiteFile; pItem = pFile; } else ATLASSERT(0); if (pItem) { pItem->m_parent = pParentDir; //pItem->m_pWebSite = m_pWebSite; strcpy(pItem->m_wfd.cFileName, filename); // recordset->getAttribute(L"file_id", &b); // pItem->m_dbid = (long)_variant_t(_bstr_t(b, false)); recordset->getAttribute(L"file_size", &b); pItem->m_wfd.nFileSizeLow = (long)_variant_t(_bstr_t(b, false)); // lastWriteDate recordset->getAttribute(L"file_date", &b); double lastWriteTime = _variant_t(_bstr_t(b, false)); SYSTEMTIME systime; VariantTimeToSystemTime(lastWriteTime, &systime); SystemTimeToFileTime(&systime, &pItem->m_wfd.ftLastWriteTime); SHFILEINFO sfi; ::SHGetFileInfo( pItem->m_wfd.cFileName, (pItem->m_type == 1)? FILE_ATTRIBUTE_DIRECTORY: FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(SHFILEINFO), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES); pItem->m_iIcon = sfi.iIcon; if (pItem->m_type == 1) { CSiteDir* pDir = (CSiteDir*)pItem; pItem->m_cChildren = _variant_t(_bstr_t(b, false)); } } return pItem; }