Esempio n. 1
0
HRESULT CbRoot::SetBaseHwInfo()
{
    CComPtr<IProp> prop;        

    char tmpString[512];
    
    // we expect the ini file to be in the same directory as the application,
    // namely, this DLL. It's the only way to find the file if it's not
    // in the windows subdirectory

    if (GetModuleFileName(_Module.GetModuleInstance(), tmpString, 512)==0)
        return E_FAIL;
    // replace .dll with .ini
    strrchr(tmpString, '.' )[1]='\0';
    strcat(tmpString,"ini"); 
    _iniFileName=tmpString;


    cbGetBoardName(_BoardNum,tmpString);
    ATLTRACE2(MCC_UL_CALL,3,"cbGetBoardName(_BoardNum = %i, tmpString); result tmpString = %s\n",_BoardNum,tmpString);
    _boardName=tmpString;
    _iniSection=_boardName;  

    CBI_CHECK(cbGetConfig(BOARDINFO, _BoardNum, 0, BIBOARDTYPE, &_BoardType));
    ATLTRACE2(MCC_UL_CALL,3,"cbGetConfig (BOARDINFO,_BoardNum = %d,0,BIBOARDTYPE, &_BoardType); result: _BoardType=%d\n",_BoardNum,_BoardType);
    long id=GetFromIni(_T("ID"),0L);
    if (id==0)
    {
        _engine->WarningMessage(CComBSTR("Board not found in mwmcc.ini file.  Board is not supported but may work.")); 
    }
    // Check to see if this is a DEMO-BOARD (code 45)
    else if (_BoardType == 45)
    {
        // Geck 224706:  When people create a DEMO-BOARD device, they probably didn't mean to.
        // Give them a warning to indicate that they might want to recosider this.
        _engine->WarningMessage(CComBSTR("The ID value selected is associated with Measurement Computing's virtual DEMO-BOARD. This virtual software device provides simulated data for demo purposes. Use a different ID if this was not your intent."));
    }
    else if (id!=_BoardType)
    {
        _engine->WarningMessage(CComBSTR("BoardType from Ini file does not match that returned from universal libray."));
        _RPT2(_CRT_WARN,"BoardType from ini file is %d board type from unilib is %d\n",id,_BoardType);
    }
    

    // device Id
    wchar_t Str[80];
    swprintf(Str, L"%d", _BoardNum);
    DEBUG_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"id"), CComVariant(Str)));		
    DEBUG_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"adaptorname"), CComVariant(L"mcc")));

    DEBUG_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"vendordriverdescription"),
	CComVariant(L"Measurement Computing Universal Library")));
    
    
    // Get the UL Revision numbers
    float DllRevNum, DriverRevNum;
    
	cbGetRevision (&DllRevNum, &DriverRevNum);
    ATLTRACE2(MCC_UL_CALL,3,"cbGetRevision (&DllRevNum,&DriverRevNum); result: DllRevNum=%d,DriverRevNum=%d\n",DllRevNum,DriverRevNum);

	// Make a call to get the decimal (.xxx) value of the minor revision number.
	// Add this to the major revision number (y.xxx)
	DllRevNum += GetDriverMinorRevision();

	CComVariant var = DllRevNum;
	var.ChangeType(VT_BSTR);

    DEBUG_HRESULT( _DaqHwInfo->put_MemberValue(CComBSTR(L"vendordriverversion"), var));

    DEBUG_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"devicename"),variant_t(_boardName)));
    
    return S_OK;
}
Esempio n. 2
0
/////////////////////////////////////////////////////////////////////////////
// AdaptorInfo()
//
// The function is used to elicit relevant info about the current HW..
//..configuration from the HW API.
//  The info to extract is:
//..1)number of boards installed
//..2)board names
//..3)supported subsystems (AnalogInput, AnalogOutput, DigitalIO)
// The function is called by the engine in response to the ML user..
//..command DAQHWINFO 
/////////////////////////////////////////////////////////////////////////////
HRESULT Cadvantechadapt::AdaptorInfo(IPropContainer * Container)
{
	LONG lDriverHandle = (LONG)NULL;          // driver handle
	PT_DeviceGetFeatures ptDevFeatures;		// Devfeatures table
	DEVFEATURES DevFeatures;					// structure for device features
	
	int i = 0;          // Index variable
	
	// Get the name of the adaptor module
	TCHAR name[256];
	GetModuleFileName(_Module.GetModuleInstance(),name,256); // null returns MATLAB version (non existant)
	RETURN_HRESULT(Container->put_MemberValue(L"adaptordllname",CComVariant(name)));
	
	// Place the adaptor name in the appropriate struct in the engine.
	RETURN_HRESULT(Container->put_MemberValue(L"adaptorname",variant_t(ConstructorName)));
	
	// Find board IDs
	// Start by obtaining the DeviceList. Not stored.
	short numDevices;			// Number of devices
	DEVLIST deviceList[MaxDev]; // Space to store device information.
	CComVariant var;			// General CComVariant to return info to adaptor engine.
	RETURN_ADVANTECH(DRV_DeviceGetList((DEVLIST far *)&deviceList[0], MaxDev, &numDevices));
	
	// Create storage for board IDs, bord names and constructors.
	TSafeArrayVector<CComBSTR> IDs;			// Create A SafeArrayVector to store the IDs in
	IDs.Allocate(numDevices);				// Allocate the memory for the number of devices
	TSafeArrayVector<CComBSTR> Names;		// Create A SafeArrayVector to store the Names in
	Names.Allocate(numDevices);				// Allocate the memory for the number of devices
	SAFEARRAY *ps;							// SafeArray for the subsystem support [nDx3 CComBStrs]
	CComBSTR *subsystems;
	SAFEARRAYBOUND arrayBounds[2]; 
	arrayBounds[0].lLbound = 0;
	arrayBounds[0].cElements = numDevices;    
	arrayBounds[1].lLbound = 0;
	arrayBounds[1].cElements = 3;			// AnalogInput, AnalogOutput, DigitalIO subsystems.
	ps = SafeArrayCreate(VT_BSTR, 2, arrayBounds);
	if (ps==NULL)
		return E_FAIL;      
	
	// Set up the variant to contain subsystem constructor SafeArray
	var.parray = ps;
	var.vt = VT_ARRAY | VT_BSTR;
	HRESULT hRes = SafeArrayAccessData(ps, (void **)&subsystems);
	if (FAILED (hRes)) 
	{
		SafeArrayDestroy (ps);
		return hRes;
	}
	
	// Now loop through each device, getting the ID, BoardName and subsystem support.
	wchar_t str[40];
	for (i=0; i < numDevices; i++)
	{
		// Allocate the ID
		char* string;
		string = new char[20];
		_ltoa(deviceList[i].dwDeviceNum, string, 10);
		IDs[i] = CComBSTR(string);
		
		// Open Device
		RETURN_ADVANTECH(DRV_DeviceOpen(deviceList[i].dwDeviceNum,(LONG far *)&lDriverHandle));
		
		// Get BoardNames info
		Names[i] = CComBSTR(deviceList[i].szDeviceName);
		
		// Check to see which subsystems the current board supports.
		// Get device features
		ptDevFeatures.buffer = (LPDEVFEATURES)&DevFeatures;
		ptDevFeatures.size = sizeof(DEVFEATURES);
		RETURN_ADVANTECH(DRV_DeviceGetFeatures(lDriverHandle, (LPT_DeviceGetFeatures)&ptDevFeatures));
		if ((DevFeatures.usMaxAIDiffChl + DevFeatures.usMaxAISiglChl) > 0) 
		{
			swprintf(str, L"analoginput('%s',%s)", (wchar_t*)ConstructorName, (wchar_t*)IDs[i]);
			subsystems[i]=str;
		}
		if (DevFeatures.usMaxAOChl > 0)
		{
			swprintf(str, L"analogoutput('%s',%s)", (wchar_t*)ConstructorName, (wchar_t*)IDs[i]);
			subsystems[i + numDevices]=str;
		}
		if ((DevFeatures.usMaxDIChl + DevFeatures.usMaxDOChl) > 0)
		{
			swprintf(str, L"digitalio('%s',%s)",(wchar_t*) ConstructorName, (wchar_t*)IDs[i]);
			subsystems[i + 2*numDevices] = str;
		}  
		// Close device
		RETURN_ADVANTECH(DRV_DeviceClose((LONG far *)&lDriverHandle));
	}
	
	// Return Object Constructor Names since they're in var already.
	SafeArrayUnaccessData (ps);    
	RETURN_HRESULT(Container->put_MemberValue(L"objectconstructorname",var));
	
	// Return the board names
	var.Clear();			// resuse the same 'var' variable for the boardnames.
	Names.Detach(&var);
	RETURN_HRESULT(Container->put_MemberValue(L"boardnames",var));
	
	// Return the board numbers
	var.Clear();			//reuse the same 'var' variable for the IDs[]
	IDs.Detach(&var);
	RETURN_HRESULT(Container->put_MemberValue(L"installedboardids",var));   
	
	return S_OK;
} // end of AdaptorInfo()
Esempio n. 3
0
WMIMethod::WMIMethod(const BSTR & name, 
                     const CComPtr<IWbemClassObject>& inParameters,
                     const CComPtr<IWbemClassObject>& outParameters,
                     IWbemQualifierSet * pQualifierSet,
                     Boolean includeQualifiers)
{
    CIMQualifierList    qualifierList;
    CComBSTR            bsName = name;
    CComVariant            vValue = NULL;
    CIMTYPE                returnValueType;
    HRESULT            hr;
    
    WMIQualifierSet(pQualifierSet).cloneTo(qualifierList);

    // Get method return value
    String referenceClass = String::EMPTY;

    CComBSTR propertyName = L"ReturnValue";

// modified to correct bug JAGaf25827  
// JAGaf25827 - new code begin
    if (outParameters)
    {
        hr = outParameters->Get(
            propertyName,  
            0, 
            &vValue, 
            &returnValueType, 
            NULL);
    }
    else
    {
        hr = WBEM_E_NOT_FOUND;
    }

    //    not found. Maybe it is a 'void' return value
    if (hr == WBEM_E_NOT_FOUND) {
        vValue = NULL;
        returnValueType = CIM_UINT32; 
    }
    else if (hr != WBEM_S_NO_ERROR) {
        // Error: throw?
        throw Exception("WMIMethod::WMIMethod Get ReturnValue Failed.");
    }
    vValue.Clear();

    // the WMI 'CIMTYPE' qualifier stores a string that contains the reference
    // class name cimtype_qualifier ::= ["ref:" + <reference_class_name>]
    // NOTE: CIMMethod does not seem to store the reference class anywhere, 
    // but it seems like it should, so this code is here in case a reference 
    // class member is ever added to the CIMMethod class in the future:
    if (CIM_REFERENCE == returnValueType)
    {
        // strip "ref:"
        Uint32 pos = qualifierList.find(CIMName("CIMTYPE"));

        if (PEG_NOT_FOUND != pos)
        {
            qualifierList.getQualifier(pos).getValue().get(referenceClass);

            //strip off "ref:" or, if not found, erase the whole string
            if ((pos = referenceClass.find(qString(Q_COLON))) != PEG_NOT_FOUND)
            {
                referenceClass.remove(0, pos + 1);
            }
        }
    }

    String classOrigin = String::EMPTY;

    // the 'Propagated" qualifier stores a string containing the class origin
    // propagated qualifier ::= [<class_origin>"."]<method_name>
    {
        Uint32 pos = qualifierList.find(CIMName("Propagated"));

        if (PEG_NOT_FOUND != pos)
        {
            qualifierList.getQualifier(pos).getValue().get(classOrigin);

            // strip on the ".<method_name> portion if there...
            if ((pos = classOrigin.find(".")) != PEG_NOT_FOUND)
            {
                classOrigin.remove(pos);
            }
        }
    }

    // NOTE: Currently no mapping of WMI "object" types, so this could 
    // throw if the param is of type "object" or other un-supported
    // WMI type:
    CIMType cimType;
    try
    {
        cimType = WMITypeToCIMType(returnValueType);
    }
    catch (TypeMismatchException tme)
    {
        // Don't want method enumeration to fail, just because
        // we don't handle the type, so making this type "reference" 
        // for now and making the reference class name "UNKNOWN_TYPE":
        cimType = CIMTYPE_REFERENCE;
        referenceClass = "UNKNOWN_TYPE";
    }

    // Build the method
    CIMName cimRef;
    CIMName cimClsOrigin;
    BSTR tmpBstr = (BSTR)bsName.Copy();
    String s(_bstr_t(tmpBstr, FALSE));
    SysFreeString(tmpBstr);
    bsName.Empty();

    if (0 != referenceClass.size())
    {
        cimRef = referenceClass;
    }

    if (0 != classOrigin.size())
    {
        cimClsOrigin = classOrigin;
    }

    *this = CIMMethod(
        CIMName(s), 
        cimType,
        cimClsOrigin, 
        (classOrigin.size() != 0));


    // Add the qualifiers
    if (includeQualifiers)
    {
        Uint32 i, n;

        for (i = 0, n = qualifierList.getCount(); i < n; i++)
        {
            addQualifier(qualifierList.getQualifier(i));
        }
    }

    // Enumerate the parameters of the WMI method in and out classes here, 
    // adding them to the CIMMethos as appropriate.
    // NOTE: In WMI parameters method parameters are defined as in, out, or 
    // both, meaning that they cold show up in both the inParameters and 
    // outParameters lists. The addWMIParametersToCIMMethod() function will 
    // check for the existing parameters by name, and will not attempt to 
    // re-add any existing params (there is no need, since the "in" and "out"
    // versions of an in/out param are simply identical copies)
    addWMIParametersToCIMMethod(outParameters, *this, includeQualifiers);
    addWMIParametersToCIMMethod(inParameters, *this, includeQualifiers);
}
void CPageEvents::OnOK() 
{
  // Save any changes made to the currently-selected node's attributes
  UpdateNodeFromItem(m_lParamSelected);

  // Inspect the <Event> nodes of the document
  if (NULL != m_spXMLDoc)
  {
    // Get all of the <Event> nodes in the document
    IXMLDOMNodeListPtr spNodeList;
    VERIFY(SUCCEEDED(m_spXMLDoc->getElementsByTagName(m_bstrEvent,
      &spNodeList)));

    // Process each node
    IXMLDOMNodePtr spNode;
    do  
    {
      // Get the next node of the child list
      VERIFY(SUCCEEDED(spNodeList->nextNode(&spNode)));
      if (NULL != spNode)
      {
        // Query for the IXMLDOMElement interface
        IXMLDOMElementPtr spElement(spNode);
        ASSERT(NULL != spElement);

        // Get the event id attribute
        CComVariant varEventID;
        spElement->getAttribute(m_bstrID, &varEventID);
        VERIFY(SUCCEEDED(varEventID.ChangeType(VT_I4)));
        AGCEventID idEventBegin = (AGCEventID)(V_UI4(&varEventID));
        AGCEventID idEventEnd = (AGCEventID)(idEventBegin + 1);

        // Get the LogAsNTEvent attribute
        IXMLDOMAttributePtr spAttrNT;
        if (S_OK == spElement->getAttributeNode(m_bstrLogAsNTEvent, &spAttrNT))
        {
          CComVariant varLog2NT;
          spAttrNT->get_value(&varLog2NT);
          VERIFY(SUCCEEDED(varLog2NT.ChangeType(VT_BOOL)));

          // Add this event id to the range, if it should be logged
          if (V_BOOL(&varLog2NT))
            m_spRangesNT->AddByValues(idEventBegin, idEventEnd);
        }

        // Get the LogAsDBEvent attribute
        IXMLDOMAttributePtr spAttrDB;
        if (S_OK == spElement->getAttributeNode(m_bstrLogAsDBEvent, &spAttrDB))
        {
          CComVariant varLog2DB;
          spAttrDB->get_value(&varLog2DB);
          VERIFY(SUCCEEDED(varLog2DB.ChangeType(VT_BOOL)));

          // Add this event id to the range, if it should be logged
          if (V_BOOL(&varLog2DB))
            m_spRangesDB->AddByValues(idEventBegin, idEventEnd);
        }
      }
    } while (NULL != spNode);

    // Set the enabled ranges of the event logger object
    VERIFY(SUCCEEDED(m_spEventLogger->put_EnabledNTEvents(m_spRangesNT)));
    VERIFY(SUCCEEDED(m_spEventLogger->put_EnabledDBEvents(m_spRangesDB)));
  }

  // Perform default processing
  CPropertyPage::OnOK();
}
HRESULT CAzApplication::CreateScopes(CAzApplication &pApp){

    CAzLogging::Entering(_TEXT("CAzApplication::CreateScopes"));

    CComPtr<IAzScopes> spAzScopes;

    CComVariant cVappl;

    long lCount=0;

    HRESULT hr=pApp.m_native->get_Scopes(&spAzScopes);

    CAzLogging::Log(hr,_TEXT("Getting scopes for IAzApplication"),COLE2T(getName()));

    if (FAILED(hr))
        goto lError1;

    hr=spAzScopes->get_Count(&lCount);

    CAzLogging::Log(hr,_TEXT("Getting operation count for IAzApplication from IAzOperations"),COLE2T(getName()));

    if (FAILED(hr))
        goto lError1;

    if (lCount==0)	
        goto lError1;
    for (long i = 1 ; i <= lCount ; i++) {

        CComPtr<IAzScope> spSrcScope,spNewScope;

        hr = spAzScopes->get_Item(i,&cVappl);

        CAzLogging::Log(hr,_TEXT("Getting scope object"),COLE2T(getName()));

        if (FAILED(hr))
            goto lError1;

        CComPtr<IDispatch> spDispatchtmp(cVappl.pdispVal);

        cVappl.Clear();

        hr = spDispatchtmp.QueryInterface(&spSrcScope);		

        if (FAILED(hr))
            goto lError1;

        CAzScope srcScope=CAzScope(spSrcScope,false);

        hr=m_native->CreateScope(srcScope.getName(),CComVariant(),&spNewScope);

        CAzLogging::Log(hr,_TEXT("Creating scope for IAzApplication"),COLE2T(getName()));

        if (FAILED(hr))
            goto lError1;

        CAzScope newScope=CAzScope(spNewScope,true);

        hr = newScope.Copy(srcScope);

        CAzLogging::Log(hr,_TEXT("Copying IAzScope properties for IAzApplication"),COLE2T(getName()));

        if (FAILED(hr))
            goto lError1;
    }
lError1:
    CAzLogging::Exiting(_TEXT("CAzApplication::CreateScopes"));

    return hr;
}
Esempio n. 6
0
/////////////////////////////////////////////////////////////////////////////
// WMIClassProvider::createProperties creates all properties including keys 
//									  add the qualifiers too
// ///////////////////////////////////////////////////////////////////////////
void WMIClassProvider::createProperties(const CIMClass& newClass,
									    IWbemServices *pServices,
										IWbemClassObject *pNewClass)
{
	HRESULT hr;
	
	PEG_METHOD_ENTER(TRC_WMIPROVIDER, "WmiClassProvider::createProperties()");

	// create the properties but don't create the keys again
	CIMProperty prop;

	for (Uint32 i = 0; i < newClass.getPropertyCount(); i++)
	{
		prop = newClass.getProperty(i).clone();

		// create the properties
		try 
		{
			createProperty(prop, pNewClass);
		}
		catch (CIMException&)
		{
			throw;
		}
		
		// get a pointer to work with qualifiers 
		CComPtr<IWbemQualifierSet> pQual;
		CComBSTR bs = prop.getName().getString().getCString();
		
		hr = pNewClass->GetPropertyQualifierSet(bs, &pQual);
		bs.Empty();

		if (FAILED(hr))
		{
			CMyString msg;
			msg.Format("Failed get Qualifier set of [%s]. Error: 0x%X", 255, 
				prop.getName().getString().getCString(), hr);
		
			Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3, 
						  "WMIClassProvider::createProperties() - %s", (LPCTSTR)msg);

			if (pQual)
				pQual.Release();
			
			throw CIMException(CIM_ERR_FAILED, (LPCTSTR)msg); 
		}

		// set the qualifiers to the property
		for (Uint32 j = 0; j < prop.getQualifierCount(); j++)
		{
			WMIQualifier qualifier(prop.getQualifier(j));
			try 
			{
				createQualifier(qualifier, pQual);
			}
			catch (CIMException&)
			{
				if (pQual)
					pQual.Release();

				throw;
			}
		}

		// set the CLASSORIGIN qualifier if it wasn't set yet
		String strClassorigin = prop.getClassOrigin().getString();
		
		if (strClassorigin.size() == 0)
		{
			strClassorigin = newClass.getClassName().getString();
		}

		WMIFlavor flavor(CIMFlavor::DEFAULTS);
		
		/*
		v.vt = VT_BSTR;
		v.bstrVal = strClassorigin.getCString();
		*/
		CComVariant v;
		v = strClassorigin.getCString();
		
		hr = pQual->Put(L"CLASSORIGIN", &v, flavor.getAsWMIValue());
		v.Clear();

		if (pQual)
			pQual.Release();

		if (FAILED(hr))
		{
			CMyString msg;
			msg.Format("Failed to add CLASSORIGIN qualifier in [%s]. Error: 0x%X", 255, 
				prop.getName().getString().getCString(), hr);

			Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3, 
						  "WMIClassProvider::createProperties () - %s", (LPCTSTR)msg);
			
			throw CIMException(CIM_ERR_FAILED, (LPCTSTR)msg);
		}
	}

	PEG_METHOD_EXIT();

	return;
}
Esempio n. 7
0
int Script::ExecuteAsync(int timeout_in_milliseconds) {
  LOG(TRACE) << "Entering Script::ExecuteAsync";
  int return_code = WD_SUCCESS;

  CComVariant result = L"";
  CComBSTR error_description = L"";

  AsyncScriptExecutorThreadContext thread_context;
  thread_context.script_source = this->source_code_.c_str();
  thread_context.script_argument_count = this->argument_count_;

  // We need exclusive access to this event. If it's already created,
  // OpenEvent returns non-NULL, so we need to wait a bit and retry
  // until OpenEvent returns NULL.
  int retry_counter = 50;
  HANDLE event_handle = ::OpenEvent(SYNCHRONIZE, FALSE, ASYNC_SCRIPT_EVENT_NAME);
  while (event_handle != NULL && --retry_counter > 0) {
    ::CloseHandle(event_handle);
    ::Sleep(50);
    event_handle = ::OpenEvent(SYNCHRONIZE, FALSE, ASYNC_SCRIPT_EVENT_NAME);
  }

  // Failure condition here.
  if (event_handle != NULL) {
    ::CloseHandle(event_handle);
    LOG(WARN) << "OpenEvent() returned non-NULL, event already exists.";
    result.Clear();
    result.vt = VT_BSTR;
    error_description = L"Couldn't create an event for synchronizing the creation of the thread. This generally means that you were trying to click on an option in two different instances.";
    result.bstrVal = error_description;
    this->result_.Copy(&result);
    return EUNEXPECTEDJSERROR;
  }

  LOG(DEBUG) << "Creating synchronization event for new thread";
  event_handle = ::CreateEvent(NULL, TRUE, FALSE, ASYNC_SCRIPT_EVENT_NAME);
  if (event_handle == NULL || ::GetLastError() == ERROR_ALREADY_EXISTS) {
    if (event_handle == NULL) {
      LOG(WARN) << "CreateEvent() failed.";
      error_description = L"Couldn't create an event for synchronizing the creation of the thread. This is an internal failure at the Windows OS level, and is generally not due to an error in the IE driver.";
    } else {
      ::CloseHandle(event_handle);
      LOG(WARN) << "Synchronization event is already created in another instance.";
      error_description = L"Couldn't create an event for synchronizing the creation of the thread. This generally means that you were trying to click on an option in multiple different instances.";
    }
    result.Clear();
    result.vt = VT_BSTR;
    result.bstrVal = error_description;
    this->result_.Copy(&result);
    return EUNEXPECTEDJSERROR;
  }

  // Start the thread and wait up to 1 second to be signaled that it is ready
  // to receive messages, then close the event handle.
  LOG(DEBUG) << "Starting new thread";
  unsigned int thread_id = 0;
  HANDLE thread_handle = reinterpret_cast<HANDLE>(_beginthreadex(NULL,
                                                  0,
                                                  AsyncScriptExecutor::ThreadProc,
                                                  reinterpret_cast<void*>(&thread_context),
                                                  0,
                                                  &thread_id));

  LOG(DEBUG) << "Waiting for new thread to be ready for messages";
  DWORD event_wait_result = ::WaitForSingleObject(event_handle, 5000);
  if (event_wait_result != WAIT_OBJECT_0) {
    LOG(WARN) << "Waiting for event to be signaled returned unexpected value: " << event_wait_result;
  }
  ::CloseHandle(event_handle);

  if (thread_handle == NULL) {
    LOG(WARN) << "_beginthreadex() failed.";
    result.Clear();
    result.vt = VT_BSTR;
    error_description = L"Couldn't create the thread for executing JavaScript asynchronously.";
    result.bstrVal = error_description;
    this->result_.Copy(&result);
    return EUNEXPECTEDJSERROR;
  }

  HWND executor_handle = thread_context.hwnd;

  // Marshal the document and the element to click to streams for use in another thread.
  LOG(DEBUG) << "Marshaling document to stream to send to new thread";
  LPSTREAM document_stream;
  HRESULT hr = ::CoMarshalInterThreadInterfaceInStream(IID_IHTMLDocument2, this->script_engine_host_, &document_stream);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "CoMarshalInterfaceThreadInStream() for document failed";
    result.Clear();
    result.vt = VT_BSTR;
    error_description = L"Couldn't marshal the IHTMLDocument2 interface to a stream. This is an internal COM error.";
    result.bstrVal = error_description;
    this->result_.Copy(&result);
    return EUNEXPECTEDJSERROR;
  }

  ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_SET_DOCUMENT, NULL, reinterpret_cast<LPARAM>(document_stream));
  for (size_t index = 0; index < this->argument_array_.size(); ++index) {
    CComVariant arg = this->argument_array_[index];
    WPARAM wparam = static_cast<WPARAM>(arg.vt);
    LPARAM lparam = NULL;
    switch (arg.vt) {
      case VT_DISPATCH: {
        LPSTREAM dispatch_stream;
        hr = ::CoMarshalInterThreadInterfaceInStream(IID_IDispatch, arg.pdispVal, &dispatch_stream);
        if (FAILED(hr)) {
          LOGHR(WARN, hr) << "CoMarshalInterfaceThreadInStream() for IDispatch argument failed";
          result.Clear();
          result.vt = VT_BSTR;
          error_description = L"Couldn't marshal the IDispatch interface to a stream. This is an internal COM error.";
          result.bstrVal = error_description;
          this->result_.Copy(&result);
          return EUNEXPECTEDJSERROR;
        }
        lparam = reinterpret_cast<LPARAM>(dispatch_stream);
        break;
      }
      default: {
        // TODO: Marshal arguments of types other than VT_DISPATCH. At present,
        // the asynchronous execution of JavaScript is only used for Automation
        // Atoms on an element which take a single argument, an IHTMLElement
        // object, which is represented as an IDispatch. This case statement
        // will get much more complex should the need arise to execute
        // arbitrary scripts in an asynchronous manner.
      }
    }
    ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_SET_ARGUMENT, wparam, lparam);
  }
  ::PostMessage(executor_handle, WD_ASYNC_SCRIPT_EXECUTE, NULL, NULL);
  // We will wait a short bit and poll for the execution of the script to be
  // complete. This will allow us to say synchronous for short-running scripts
  // like clearing an input element, yet still be able to continue processing
  // when the script is blocked, as when an alert() window is present.
  LOG(TRACE) << "Waiting for async script execution to be complete";
  retry_counter = static_cast<int>(timeout_in_milliseconds / 10);
  bool is_execution_finished = ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_IS_EXECUTION_COMPLETE, NULL, NULL) != 0;
  while(!is_execution_finished && --retry_counter > 0) {
    ::Sleep(10);
    is_execution_finished = ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_IS_EXECUTION_COMPLETE, NULL, NULL) != 0;
  }

  if (is_execution_finished) {
    // TODO: Marshal the actual result from the AsyncScriptExecutor window
    // thread to this one. At present, the asynchronous execution of JavaScript
    // is only used for Automation Atoms on an element which could cause an
    // alert to appear (e.g., clear, click, or submit), and do not return any
    // return values back to the caller. In this case, the return code of the
    // execution method is sufficent. Marshaling the return will require two
    // more messages, one for determining the variant type of the return value,
    // and another for actually retrieving that value from the worker window's
    // thread.
    LOG(TRACE) << "Async script execution completed, getting result";
    int status_code = static_cast<int>(::SendMessage(executor_handle, WD_ASYNC_SCRIPT_GET_RESULT, NULL, NULL));
    return status_code;
  } else {
    LOG(TRACE) << "Async script execution not completed after timeout, detaching listener";
    ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_DETACH_LISTENTER, NULL, NULL);
  }
  return WD_SUCCESS;
}
FB::variant ActiveXBrowserHost::getVariant(const VARIANT *cVar)
{
    CComVariant converted;
    FB::variant retVal;

    switch(cVar->vt)
    {        
    case VT_R4:
    case VT_R8:
    case VT_DECIMAL:
        converted.ChangeType(VT_R8, cVar);
        retVal = (double)converted.dblVal;
        break;

    case VT_I1:
    case VT_I2:
    case VT_I4:
    case VT_UI1:
    case VT_UI2:
    case VT_INT:
        converted.ChangeType(VT_I4, cVar);
        retVal = (long)converted.lVal;
        break;
    case VT_UI4:
    case VT_UINT:
        converted.ChangeType(VT_UI4, cVar);
        retVal = (unsigned long)converted.ulVal;
        break;

    case VT_I8:
        retVal = static_cast<boost::int64_t>(cVar->llVal);
        break;
    case VT_UI8:
        retVal = static_cast<boost::uint64_t>(cVar->ullVal);
    case VT_LPSTR:
    case VT_LPWSTR:
    case VT_BSTR:
    case VT_CLSID:
        {
            converted.ChangeType(VT_BSTR, cVar);
            std::wstring wStr(converted.bstrVal);

            // return it as a UTF8 std::string
            retVal = FB::wstring_to_utf8(wStr);
        }
        break;

    case VT_DISPATCH:
		retVal = FB::JSObjectPtr(IDispatchAPI::create(cVar->pdispVal, ptr_cast<ActiveXBrowserHost>(shared_ptr()))); 
        break;

    case VT_ERROR:
    case VT_BOOL:
        converted.ChangeType(VT_BOOL, cVar);
        retVal = (converted.boolVal == VARIANT_TRUE) ? true : false;
        break;

    case VT_NULL:
        retVal = FB::FBNull();
        break;

    case VT_EMPTY:
    default:
        // retVal is already empty, leave it such
        break;
    }

    return retVal;
}
Esempio n. 9
0
static HRESULT WINAPI GetDoubleElement(VARTYPE type, SAFEARRAY* pSA, long idx, double* pRetVal)
{
    ATLASSERT(pRetVal);
    ATLASSERT(pSA);

    *pRetVal = 0.;

    HRESULT hr;
    CComVariant v;
    switch(type)
    {
    case VT_R8:
        return SafeArrayGetElement(pSA, &idx, pRetVal);
    case VT_VARIANT:
        hr = SafeArrayGetElement(pSA, &idx, &v);
        if(FAILED(hr))
        {
            return hr;
        }
        hr = v.ChangeType(VT_R8);
        if(FAILED(hr))
        {
            return hr;
        }
        *pRetVal = v.dblVal;
        break;
    case VT_BSTR:
        hr = SafeArrayGetElement(pSA, &idx, &v.bstrVal);
        if(FAILED(hr))
        {
            return hr;
        }
        v.vt = VT_BSTR;
        hr = v.ChangeType(VT_R8);
        if(FAILED(hr))
        {
            return hr;
        }
        *pRetVal = v.dblVal;
        break;
    case VT_I4:
        hr = SafeArrayGetElement(pSA, &idx, &v.lVal);
        if(FAILED(hr))
        {
            return hr;
        }
        v.vt = VT_I4;
        hr = v.ChangeType(VT_R8);
        if(FAILED(hr))
        {
            return hr;
        }
        *pRetVal = v.dblVal;
        break;
    case VT_UI4:
        hr = SafeArrayGetElement(pSA, &idx, &v.ulVal);
        if(FAILED(hr))
        {
            return hr;
        }
        v.vt = VT_I4;
        hr = v.ChangeType(VT_R8);
        if(FAILED(hr))
        {
            return hr;
        }
        *pRetVal = v.dblVal;
        break;
    }
    return S_OK;
}
Esempio n. 10
0
HRESULT CControlState::Load( LPSTREAM pStm )
{
   HRESULT hr = S_OK;
   CComVariant var;

   DWORD dwVer;
   READDATA( dwVer );

   // version 1 and 2 are pre-2.0 and are not backward compatible.  Ignore this data.
   if ( dwVer < 3 )
   {
      return S_FALSE;
   }

   READDATA( m_bColorSyntax );
   READDATA( m_bAllowHSplit );
   READDATA( m_bAllowVSplit );
   READDATA( m_bHScroll );
   READDATA( m_bVScroll );
   READDATA( m_bSmoothScroll );
   READDATA( m_bLineToolTips );
   READDATA( m_bShowLeftMargin );
   READDATA( m_bAllowColumnSel );
   READDATA( m_bAllowDragDrop );
   READDATA( m_bExpandTabs );
   READDATA( m_xPosHSplitter );
   READDATA( m_yPosVSplitter );
   READDATA( m_eIndentStyle );
   READDATA( m_nTabSize );
   READDATA( m_Colors );
   READDATA( m_lf );

   // dealloc old strings
   FreeStrings();

   if ( SUCCEEDED( hr = var.ReadFromStream( pStm ) ) )
   {
       m_bstrText = var.bstrVal;
       var.bstrVal = NULL;
       var.vt = VT_EMPTY;
   }
   else
      goto bail;

   if ( SUCCEEDED( hr = var.ReadFromStream( pStm ) ) )
   {
       m_bstrLang = var.bstrVal;
       var.bstrVal = NULL;
       var.vt = VT_EMPTY;
   }
   else
      goto bail;

   READDATA( m_bDisplayWhitespace );
   READDATA( m_bWantCarriageReturn );
   READDATA( m_bEnabled );
   READDATA( m_bGlobalProps );
   READDATA( m_bModified );
   READDATA( m_bOverType );
   READDATA( m_bReadOnly );
   READDATA( m_bPreserveCase );
   READDATA( m_bCaseSensitiveSearch );
   READDATA( m_bWholeWordOnly );
   READDATA( m_nMaxUndo );
   READDATA( m_bSelBounds );
   READDATA( m_bRegExp );
   READDATA( m_FontStyles );
   READDATA( m_LineNum );
   READDATA( m_bHideSel );
   READDATA( m_bNormalizeCase );
   READDATA( m_bOvertypeCaret );
   READDATA( m_nHighlightedLine );

   if ( dwVer < 4 )
      goto bail;

   READDATA( m_dwBorderStyle );

   if ( dwVer < 5 )
      goto bail;

   READDATA( m_bStealKeys );

   bail:

   return hr;
}
Esempio n. 11
0
BOOL CPeraPDWeb::OnWebCallback( int nCode, WEBCALLBACK_METHOD_PARAM_MAP& mapParams
	, CComVariant& varResult )
{
	varResult.Clear();

	CString str;
	WEBCALLBACK_METHOD_PARAM_MAP::iterator itrParam = mapParams.begin();

	switch (nCode)
	{
		//////////////////////////////////////////////////////////////////////////
		//更新结构树
	case WCB_RUNFLOW_COMPLETED:
		{
			if (mapParams.size() != 1)
			{
				//varResult = "参数个数不正确";
				//lc,国际化乱码问题
				varResult = _bstr_t("参数个数不正确").GetBSTR();
				return FALSE;
			}

			itrParam = mapParams.begin();
			//str = itrParam->second.bstrVal;
			//lc,国际化乱码问题
			str = (LPCTSTR)_bstr_t(itrParam->second.bstrVal);

			ZTools::WriteZToolsFormatLog("CPeraPDWeb::OnWebCallback svg通知运行结束 %s\r\n", str );

			if ( g_aw.m_nExeFlag == WEBTYPE_RUNFLOW )
			{
				CWERunFlowCompleted runFlowCompleted;
				if( !runFlowCompleted.ParseData( str ) )
				{
					ZTools::WriteZToolsLog( "CPeraPDWeb::OnWebCallback svg WCB_RUNFLOW_COMPLETED 解析失败" );
				}
				runFlowCompleted.m_dwWebType = WEBTYPE_RUNFLOW;
				runFlowCompleted.m_dwWebEvent = WE_RUNFLOW_COMPLETED;
				runFlowCompleted.m_sWebId = g_aw.m_sId;
				theCommClient.Send( g_aw.m_hHostWnd, &runFlowCompleted );
				ZTools::WriteZToolsLog( "CPeraPDWeb::OnWebCallback svg WCB_RUNFLOW_COMPLETED 发送完成" );
			}
			else
			{
				ZTools::WriteZToolsLog( "CPeraPDWeb::OnWebCallback svg WCB_RUNFLOW_COMPLETED webtype 不匹配" );
			}
		}
		break;
	//////////////////////////////////////////////////////////////////////////
	case WCB_WEB_LOADED:
		{
			ZTools::WriteZToolsFormatLog("WebPage CPeraPDWeb::OnWebCallback %s\r\n", "WCB_WEB_LOADED");

			if ( IsWindow( g_aw.m_hHostWnd )  )
			{
				if ( g_aw.m_nExeFlag == WEBTYPE_RUNPROCESS || g_aw.m_nExeFlag == WEBTYPE_RUNFLOW )
				{
					::PostMessage( g_aw.m_hHostWnd, WM_WEB_LOADED, 0, 0 );
				}
				else
				{
					ZTools::WriteZToolsLog( "WebPage CPeraPDWeb::OnWebCallback WCB_WEB_LOADED webtype 不匹配" );
				}
			}
		}
		break;

		//////////////////////////////////////////////////////////////////////////
	default:
		return FALSE;
	}

	return TRUE;
}
Esempio n. 12
0
STDMETHODIMP CBDictionary::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
		VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
	if((dispIdMember & 0xff000000) != 0x65000000)
		return CBDispatch<IVariantDictionary>::g_typeinfo.Invoke((IVariantDictionary*)this, dispIdMember, wFlags,
			pDispParams, pVarResult, pExcepInfo, puArgErr);

	dispIdMember &= 0xffffff;

	CBLock l(&m_cs);

	if(dispIdMember < (int)m_posArray.GetCount())
	{
		if((wFlags & (DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF)) && pDispParams->cArgs == 1)
		{
			VARIANT* pvar = pDispParams->rgvarg;

			while(pvar->vt == (VT_VARIANT | VT_BYREF))
				pvar = pvar->pvarVal;

			if(!(wFlags & DISPATCH_PROPERTYPUTREF) &&
				(pvar->vt == VT_UNKNOWN || pvar->vt == VT_DISPATCH))
			{
				l.Unlock();

				if(pvar->punkVal == NULL)
					return DISP_E_UNKNOWNINTERFACE;

				CBDispatchPtr pDisp;
				CComVariant var;

				HRESULT hr = pvar->punkVal->QueryInterface(&pDisp);
				if(FAILED(hr))return hr;

				hr = pDisp.GetProperty(0, &var);
				if(FAILED(hr))return hr;

				l.Lock();
				if(dispIdMember < (int)m_posArray.GetCount())
				{
					var.Detach(&m_posArray[dispIdMember]->m_value);
					return S_OK;
				}else return DISP_E_MEMBERNOTFOUND;
			}else return VariantCopyInd(&m_posArray[dispIdMember]->m_value, pvar);
		}else if(pDispParams->cArgs == 0)
		{
			if(pVarResult != NULL)
				return VariantCopy(pVarResult, &m_posArray[dispIdMember]->m_value);

			return S_OK;
		}

		VARIANT *pvar = &m_posArray[dispIdMember]->m_value;

		if(pvar->vt == VT_UNKNOWN || pvar->vt == VT_DISPATCH)
		{
			CBDispatchPtr pDisp;

			HRESULT hr = pvar->punkVal->QueryInterface(&pDisp);
			if(FAILED(hr))
				return DISP_E_BADPARAMCOUNT;

			l.Unlock();
			return pDisp->Invoke(0, riid, lcid, wFlags, pDispParams,
					pVarResult, pExcepInfo, puArgErr);
		}

		return DISP_E_BADPARAMCOUNT;
	}else return DISP_E_MEMBERNOTFOUND;

	return S_OK;
}
STDMETHODIMP CFoundationExemplars::TMchCreateAndDispenseObject()
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	VWTRACE(m_pWorld, "VWFOUND", VWT_ERROR, "CFoundationExemplars::TMchCreateAndDispenseObject\n");

	CComPtr<IThing>				pThis;
	CComPtr<IThing>				pUser;
	CComPtr<IThing>				pNewObject;
	CComPtr<IPropertyList>		pItemList;
	CComPtr<IVWTransactionItem>	pCurItem;
	CComPtr<IPropertyMap>		pPropertyValues;
	CComBSTR					bstrName;
	CComBSTR					bstrDescription;
	CComBSTR					bstrGraphic;
	CComBSTR					bstrExemplarType;
	CComVariant					varReturnVal;
	CComVariant					varPropertyValue;
	BSTR						bstrPropertyName;
	VARIANT_BOOL				bLastValue;
	VARIANT_BOOL				bIsEmpty;
	VARIANT_BOOL				bIsValid;
	short						nCurIndex;
    HRESULT                     hr;

	if (FAILED(hr = m_pWorld->get_This(&pThis)))
		goto ERROR_ENCOUNTERED;
	if (FAILED(hr = m_pWorld->get_User(&pUser)))
		goto ERROR_ENCOUNTERED;

	if ((pThis)&&(pUser))
	{
		if (FAILED(hr = pThis->get_Short(CComBSTR("CurrentIndex"), &nCurIndex)))
    		goto ERROR_ENCOUNTERED;
		if (FAILED(hr = pThis->get_ObjectProperty(CComBSTR("ItemList"), (IObjectProperty**) &pItemList)))
	    	goto ERROR_ENCOUNTERED;
		if (pItemList)
		{
			if (FAILED(hr = pItemList->get_ObjectProperty(nCurIndex, (IObjectProperty**) &pCurItem)))
		        goto ERROR_ENCOUNTERED;
			if (pCurItem)
			{
				if (FAILED(hr = pCurItem->get_Name(&bstrName.m_str)))
		            goto ERROR_ENCOUNTERED;
				if (FAILED(hr = pCurItem->get_Description(&bstrDescription.m_str)))
		            goto ERROR_ENCOUNTERED;
				if (FAILED(hr = pCurItem->get_Graphic(&bstrGraphic.m_str)))
		            goto ERROR_ENCOUNTERED;
				if (FAILED(hr = pCurItem->get_ExemplarType(&bstrExemplarType.m_str)))
		            goto ERROR_ENCOUNTERED;
				if (FAILED(hr = pCurItem->get_PropertyValues(&pPropertyValues)))
		            goto ERROR_ENCOUNTERED;

				// Now, create new object
				if (FAILED(hr = m_pWorld->CreateInstanceExt(bstrName, CComVariant(bstrExemplarType), NULL, &pNewObject)))
		            goto ERROR_ENCOUNTERED;
				
				// Set new object's properties
				if (pNewObject)
				{
					CComVariant varFile(bstrGraphic);
					CComDISPPARAMS dpInitGraphics(10, varFile, 
					CComVariant(0.0f), CComVariant(0.45f), CComVariant(0.0f),
					CComVariant(0.0f), CComVariant(0.0f), CComVariant(1.0f),
					CComVariant(0.25f), CComVariant(0.25f), CComVariant(0.25f));
					VARIANT_BOOL	bIsArtifact;
					VARIANT_BOOL	bIsAccessory;

#ifdef _DEBUG
					CComPtr<IThing> pOwner, pCaller;
					CComBSTR bstrOwnerName, bstrCallerName;
					if (FAILED(hr = pNewObject->get_Owner(&pOwner)))
		                goto ERROR_ENCOUNTERED;
					if (pOwner)
                    {
						if (FAILED(hr = pOwner->get_Name(&bstrOwnerName.m_str)))
		                    goto ERROR_ENCOUNTERED;
                    }
					if (FAILED(hr = m_pWorld->get_Caller(&pCaller)))
		                goto ERROR_ENCOUNTERED;
					if (pCaller)
                    {
						if (FAILED(hr = pCaller->get_Name(&bstrCallerName.m_str)))
		                    goto ERROR_ENCOUNTERED;
                    }
#endif

				    if (FAILED(hr = pNewObject->InvokeMethodExt(CComBSTR("InitializeSpriteGraphics"), (DISPPARAMS *) dpInitGraphics, NULL)))
		                goto ERROR_ENCOUNTERED;
					if (FAILED(hr = pNewObject->put_Description(bstrDescription)))
		                goto ERROR_ENCOUNTERED;
					if (FAILED(hr = pNewObject->put_BOOL(CComBSTR("IsTakeable"), VARIANT_TRUE)))
		                goto ERROR_ENCOUNTERED;

					// Set additional properties if specified in PropertyValue propertymap
					if (FAILED(hr = pPropertyValues->get_IsEmpty(&bIsEmpty)))
		                goto ERROR_ENCOUNTERED;						
					if (bIsEmpty!=VARIANT_TRUE)
					{
						// Get first pair of values 
						if (FAILED(hr = pPropertyValues->FirstItem(&bstrPropertyName, &varPropertyValue, &bLastValue)))
		                    goto ERROR_ENCOUNTERED;
							
						// Add name/value pair to object and iterate through rest of map
						while (bLastValue!=VARIANT_TRUE)
						{
							// Test that the property name is valid
							// Review: do we need other checks on property name, value?
							if (FAILED(hr = pPropertyValues->IsValid(bstrPropertyName, &bIsValid)))
		                        goto ERROR_ENCOUNTERED;
							if (bIsValid)
                            {
								if (FAILED(hr = pNewObject->put_Property(bstrPropertyName, varPropertyValue)))
		                            goto ERROR_ENCOUNTERED;
                            }

							// Now free values
							SAFEFREESTRING(bstrPropertyName);
							varPropertyValue.Clear();

							// Get next item
							if (FAILED(hr = pPropertyValues->NextItem(&bstrPropertyName, &varPropertyValue, &bLastValue)))
		                        goto ERROR_ENCOUNTERED;
						}
					}
					// Now check if exemplar type is Artifact and IsAccessory set to true,
					// then set the AccessoryGraphic property
					// Review: is there a better way of doing this? strcmp? part of loop in property map?
					// Seems like it would be much cleaner with an Accessory exemplar
					
					if (FAILED(hr = pNewObject->IsOfType(CComBSTR("Artifact"), &bIsArtifact)))
                		goto ERROR_ENCOUNTERED;
					if (bIsArtifact)
					{
						if (FAILED(hr = pNewObject->get_BOOL(CComBSTR("IsAccessory"), &bIsAccessory)))
		                    goto ERROR_ENCOUNTERED;
						if (bIsAccessory)
						{
							CComPtr<IThing> pGlobal;
							CComBSTR bstrEventName(VW_UIELEMENTCHANGED_EVENT_STR );

							if (FAILED(hr = pNewObject->put_Property(CComBSTR("AccessoryGraphic"), CComVariant(bstrGraphic))))
		                        goto ERROR_ENCOUNTERED;
							// Need to fire UI event to get the icon to update in inventory tab
							if (FAILED(hr = m_pWorld->get_Global(&pGlobal)))
		                        goto ERROR_ENCOUNTERED;
							if (FAILED(hr = pGlobal->InvokeMethodExt(CComBSTR("FireRemoteUIEvent"), 
								CComDISPPARAMS(4, CComVariant((IDispatch*) pUser), CComVariant((IDispatch*) pNewObject),
								CComVariant(bstrEventName), CComVariant()), NULL)))
		                        goto ERROR_ENCOUNTERED;
						}
					}
					// Tell user the object has been moved to inventory
					CComBSTR bstrWhisperText(bstrName);
					bstrWhisperText += " is now in your inventory.";
					if (FAILED(hr = pThis->InvokeMethodExt(CComBSTR("Whisper"), CComDISPPARAMS(2, CComVariant(bstrWhisperText), CComVariant((IDispatch*) pUser)), NULL)))
		                goto ERROR_ENCOUNTERED;
				}
			}
		}
	}

    return S_OK;	

ERROR_ENCOUNTERED:

    VWTRACE(m_pWorld, "VWFOUND", VWT_ERROR, "CFoundationExemplars::TMchCreateAndDispenseObject  Error %x\n", hr);

	return hr;
}
Esempio n. 14
0
//
// AdaptorInfo
//
// Description:
//  Invoked by MatLab function daqhwinfo('cbi'). The function
//  is used to extract relavent info about the current HW
//  configuration. Need to get the board names, the board number
//  and what subsystems are supported, AnalogInput, AnalogOutput,
//  and DigitalIO.
//
// UL Routines:
//  cbGetConfig()
//  cbGetBoardName()
//
HRESULT CbDevice::AdaptorInfo(IPropContainer * Container)
{
    int i = 0;          // Index variable
    wchar_t str[40];    // Temp variable for BoardName

    // Place the adaptor name, 'cbi', in the appropriate struct in the engine.
    HRESULT hRes = Container->put_MemberValue(CComBSTR(L"adaptorname"),CComVariant(L"mcc"));
    if (!(SUCCEEDED(hRes))) return hRes;

    TCHAR name[256];
    GetModuleFileName(_Module.GetModuleInstance(),name,256); // null returns MATLABs version (non existant)

    hRes = Container->put_MemberValue(CComBSTR(L"adaptordllname"),CComVariant(name));
    if (!(SUCCEEDED(hRes))) return hRes;

    // First determine the number of boards installed.
    short idVec[16]={0};        // List of board Numbers
    short len=0;                  // Number of boards installed

    // Return a list of board numbers and number of installed boards. 
    GetInstalledBoardInfo(idVec,&len);      

    SAFEARRAY *boardids = SafeArrayCreateVector(VT_BSTR, 0, len);
    if (boardids==NULL) 
        return E_OUTOFMEMORY;
    
    CComBSTR *stringids=NULL;
    CComVariant bids;   
    
    bids.parray=boardids;
    bids.vt = VT_ARRAY | VT_BSTR;           
    
    hRes = SafeArrayAccessData(boardids, (void **) &stringids);
    if (FAILED (hRes)) {
        SafeArrayDestroy (boardids);
        return hRes;
    }

    for (i=0;i<len;i++) {	
		swprintf(str,L"%d",(int)idVec[i]);
		stringids[i] = str;
    }  

    SafeArrayUnaccessData(boardids);
    
    // Return the board numbers to the 'engine'
    hRes = Container->put_MemberValue(CComBSTR(L"installedboardids"),bids);   
    if (!(SUCCEEDED(hRes))) return hRes;    

    bids.Clear();

    // build up an array of device names
    CComVariant val;    
    CComBSTR *strings;
    
    SAFEARRAY *ps = SafeArrayCreateVector(VT_BSTR, 0, len);
    if (ps==NULL) 
        return E_OUTOFMEMORY;

    val.parray=ps;
    val.vt = VT_ARRAY | VT_BSTR;

    HRESULT hr = SafeArrayAccessData(ps, (void **) &strings);
    if (FAILED (hr)) 
    {
        SafeArrayDestroy (ps);
        return hr;
    }             

    
    char bName[BOARDNAMELEN];

    for (i=0;i<len;i++)
    {
        if (!cbGetBoardName(idVec[i], bName))
            strings[i] = CComBSTR(bName);
    }
                        

    hRes = Container->put_MemberValue(CComBSTR(L"boardnames"),val);
    if (!(SUCCEEDED(hRes))) return hRes;

    SafeArrayUnaccessData(ps);

    // up to 3 subsystems per board
    CComBSTR *subsystems;
    SAFEARRAYBOUND arrayBounds[2];  
        arrayBounds[0].lLbound = 0;
        arrayBounds[0].cElements = len;    
        arrayBounds[1].lLbound = 0;
        arrayBounds[1].cElements = 3;    

    ps = SafeArrayCreate(VT_BSTR, 2, arrayBounds);
    if (ps==NULL)
        return E_OUTOFMEMORY;
   
    val.Clear();
    val.parray=ps;
    val.vt = VT_ARRAY | VT_BSTR;
    hr = SafeArrayAccessData(ps, (void **) &subsystems);
    if (FAILED (hr)) 
    {
        SafeArrayDestroy (ps);
        return hr;
    }       
   
    // walk through the board list and determine the available subsystems
    for (i=0;i<len;i++)
    {	
	bool ai=false;
	bool ao=false;
	bool dio=false;
       
	EnumSubsystems(idVec[i], &ai, &ao, &dio);
	if (ai)
        {
            swprintf(str,L"analoginput('mcc',%d)", idVec[i]);
	    subsystems[i]=str;
        }
        else
            subsystems[i]=(BSTR)NULL;
	if (ao)
        {
            swprintf(str,L"analogoutput('mcc',%d)", idVec[i]);
	    subsystems[i+len]=str;
        }
        else
            subsystems[i+len]=(BSTR)NULL;
	if (dio)
        {
            swprintf(str,L"digitalio('mcc',%d)", idVec[i]);
	    subsystems[i+2*len]=str;
        }
        else
            subsystems[i+2*len]=(BSTR)NULL;
    }

    hRes = Container->put_MemberValue(CComBSTR(L"objectconstructorname"),val);
    if (!(SUCCEEDED(hRes))) return hRes;
  
    SafeArrayUnaccessData (ps);    
    
    
    return S_OK;
}
Esempio n. 15
0
HRESULT ExchangeAdmin::CreateExchangeMailBox(LPCWSTR lpwstrNewUser, LPCWSTR lpwstrNewUserPwd,
    LPCWSTR lpwstrlogonuser, LPCWSTR lpwstrLogonUsrPwd)
{
    HRESULT hr = S_OK;

    // Get Logon user DN
    wstring LogonUserDN;
    wstring legacyName;
	wstring msExchHomeSvrName;
    Zimbra::MAPI::Util::GetUserDNAndLegacyName(m_strServer.c_str(), lpwstrlogonuser,
        lpwstrLogonUsrPwd, LogonUserDN, legacyName);
	Zimbra::MAPI::Util::GetmsExchHomeServerName(m_strServer.c_str(), lpwstrlogonuser,
        lpwstrLogonUsrPwd, msExchHomeSvrName);
    Zimbra::Util::ScopedInterface<IDirectoryObject> pLogonContainer;
	Zimbra::Util::ScopedInterface<IADsUser> pIAdUser;
	Zimbra::Util::ScopedInterface<IADs> pIAds;
    wstring strContainer = L"LDAP://";

    strContainer += LogonUserDN.c_str();

    dloge("strContainer %S  msExchHomeSvrName: %S", strContainer.c_str(), msExchHomeSvrName.c_str());
    // Get loggedin user container
    hr = ADsOpenObject(strContainer.c_str(), NULL, NULL, ADS_SECURE_AUTHENTICATION,
        IID_IDirectoryObject, (void **)pLogonContainer.getptr());
    if (FAILED(hr))
    {
        if (hr == 0x8007052e)                   // credentials are not valid
        {
            hr = ADsOpenObject((LPTSTR)strContainer.c_str(), lpwstrlogonuser, lpwstrLogonUsrPwd,
				ADS_SECURE_AUTHENTICATION, IID_IDirectoryObject, (void **)pLogonContainer.getptr());
			if (FAILED(hr)||(pLogonContainer.get()==NULL))
                throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): ADsOpenObject Failed.",
				ERR_ADOBJECT_OPEN, __LINE__, __FILE__);
        }
        else
        {
            throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsOpenObject Failed.",
                ERR_ADOBJECT_OPEN, __LINE__, __FILE__);
        }
    }

    ADS_ATTR_INFO *pAttrInfo = NULL;
    DWORD dwReturn;
    LPWSTR pAttrNames[] = { L"mail", L"homeMDB", L"homeMTA" };
    DWORD dwNumAttr = sizeof (pAttrNames) / sizeof (LPWSTR);
    wstring strLogonHomeMDB;
    wstring strLogonHomeMTA;
    wstring strLogonMail;

    // Get attribute values requested. Its not necessary the order is same as requested.
    if (FAILED(hr = pLogonContainer->GetObjectAttributes(pAttrNames, dwNumAttr, &pAttrInfo,
            &dwReturn)))
        throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): GetObjectAttributes Failed.", 
		ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    for (DWORD idx = 0; idx < dwReturn; idx++)
    {
        if (_wcsicmp(pAttrInfo[idx].pszAttrName, L"mail") == 0)
            strLogonMail = pAttrInfo[idx].pADsValues->Email.Address;

        else if (_wcsicmp(pAttrInfo[idx].pszAttrName, L"homeMTA") == 0)
            strLogonHomeMTA = pAttrInfo[idx].pADsValues->DNString;

        else if (_wcsicmp(pAttrInfo[idx].pszAttrName, L"homeMDB") == 0)
            strLogonHomeMDB = pAttrInfo[idx].pADsValues->DNString;
    }
    // Use FreeADsMem for all memory obtained from the ADSI call.
    FreeADsMem(pAttrInfo);

    wstring twtsrlogonuserDN = LogonUserDN;
    size_t nPos = twtsrlogonuserDN.find(_T("DC="), 0);
    wstring wstrServerDN = twtsrlogonuserDN.substr(nPos);
    wstring wstrADSPath = _T("LDAP://CN=Users,") + wstrServerDN;
    ADSVALUE cnValue;
    ADSVALUE classValue;
    ADSVALUE sAMValue;
    ADSVALUE uPNValue;
	ADSVALUE controlValue;
    ADS_ATTR_INFO attrInfo[] = {
        { L"objectClass", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &classValue, 1 },
        { L"cn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &cnValue, 1 },
        { L"sAMAccountName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &sAMValue, 1 },
        { L"userPrincipalName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &uPNValue, 1 },
		{L"userAccountControl", ADS_ATTR_UPDATE, ADSTYPE_INTEGER,&controlValue, 1},
    };
    DWORD dwAttrs = sizeof (attrInfo) / sizeof (ADS_ATTR_INFO);

    classValue.dwType = ADSTYPE_CASE_IGNORE_STRING;
    classValue.CaseIgnoreString = L"user";

	//int UF_ACCOUNTDISABLE = 0x0002;
	int UF_PASSWD_NOTREQD = 0x0020;
	//int UF_PASSWD_CANT_CHANGE = 0x0040;
	int UF_NORMAL_ACCOUNT = 0x0200;
	int UF_DONT_EXPIRE_PASSWD = 0x10000;
	//int UF_PASSWORD_EXPIRED = 0x800000;

	controlValue.dwType = ADSTYPE_INTEGER;
	controlValue.Integer=UF_NORMAL_ACCOUNT | UF_PASSWD_NOTREQD |UF_DONT_EXPIRE_PASSWD;

    cnValue.dwType = ADSTYPE_CASE_IGNORE_STRING;
    cnValue.CaseIgnoreString = (LPWSTR)lpwstrNewUser;

    sAMValue.dwType = ADSTYPE_CASE_IGNORE_STRING;
    sAMValue.CaseIgnoreString = (LPWSTR)lpwstrNewUser;

    wstring wstrMail;
    size_t nPosMail = strLogonMail.find(_T("@"), 0);

    wstrMail = strLogonMail.substr(nPosMail);
    wstrMail = lpwstrNewUser + wstrMail;

    LPWSTR upnval = (LPWSTR)wstrMail.c_str();

    uPNValue.dwType = ADSTYPE_CASE_IGNORE_STRING;
    uPNValue.CaseIgnoreString = upnval;

    Zimbra::Util::ScopedInterface<IDirectoryObject> pDirContainer;
    Zimbra::Util::ScopedInterface<IDispatch> pDisp;
    Zimbra::Util::ScopedInterface<IADsUser> pIADNewUser;
    wstring wstrLoggedUserName(LogonUserDN);
    size_t snPos = 0;
    size_t enPos = 0;

    if ((snPos = wstrLoggedUserName.find(L"CN=")) != wstring::npos)
    {
        if ((enPos = wstrLoggedUserName.find(L",", snPos)) != wstring::npos)
            wstrLoggedUserName = wstrLoggedUserName.substr(snPos + 3, (enPos - (snPos + 3)));
    }
    // get dir container
    if (FAILED(hr = ADsOpenObject(wstrADSPath.c_str(), wstrLoggedUserName.c_str(),
            lpwstrLogonUsrPwd, ADS_SECURE_AUTHENTICATION, IID_IDirectoryObject,
            (void **)pDirContainer.getptr())))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsOpenObject Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);

    wstring wstrUserCN = L"CN=";

    wstrUserCN += lpwstrNewUser;
    dloge("CreateDSObject: %S",wstrUserCN.c_str());
    if (FAILED(hr = pDirContainer->CreateDSObject((LPWSTR)wstrUserCN.c_str(), attrInfo, dwAttrs,
            pDisp.getptr())))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): CreateDSObject Failed.",
            ERR_CREATE_EXCHMBX,__LINE__, __FILE__);
    if (FAILED(hr = pDisp->QueryInterface(IID_IADsUser, (void **)pIADNewUser.getptr())))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): QueryInterface Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);

    CComVariant varProp;
    varProp.Clear();

    // set samAccount
    varProp = lpwstrNewUser;
    if (FAILED(hr = pIADNewUser->Put(CComBSTR(L"sAMAccountName"), varProp)))
        throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): Put(sAMAccountName) Failed.",
		ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    if(FAILED(hr = pIADNewUser->SetInfo()))
        throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): Put(sAMAccountName) Failed.", 
		ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    // set userAccountControl
    varProp.Clear();
    hr = pIADNewUser->Get(CComBSTR(L"userAccountControl"), &varProp);
    varProp = varProp.lVal & ~(ADS_UF_ACCOUNTDISABLE);
    if (FAILED(hr = pIADNewUser->Put(CComBSTR(L"userAccountControl"), varProp)))
        throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): Put(userAccountControl) Failed.",
		ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - Put(userAccountControl) Failed.");
    // set Account enabled
    if (FAILED(hr = pIADNewUser->put_AccountDisabled(VARIANT_FALSE)))
    {
        throw
            ExchangeAdminException(hr, L"CreateExchangeMailBox(): put_AccountDisabled Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - put_AccountDisabled Failed.");
    // set password
    if (FAILED(hr = pIADNewUser->SetPassword(CComBSTR(lpwstrNewUserPwd))))
    {
        throw
            ExchangeAdminException(hr, L"CreateExchangeMailBox(): SetPassword Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - SetPassword Failed.");
    // user account password does not expire
    varProp.Clear();

    VARIANT var;

    VariantInit(&var);
    if (!FAILED(hr = pIADNewUser->Get(CComBSTR(L"userAccountControl"), &var)))
    {
        V_I4(&var) |= ADS_UF_DONT_EXPIRE_PASSWD;
        if (FAILED(hr = pIADNewUser->Put(CComBSTR(L"userAccountControl"), var)))
        {
            throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): Put(userAccountControl) Failed.", 
				ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
        }
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - userAccountControl Failed.");
    varProp.Clear();
    // set the homeMDB;
    if (!strLogonHomeMDB.empty())
    {
        varProp = strLogonHomeMDB.c_str();
        if (FAILED(hr = pIADNewUser->Put(CComBSTR("homeMDB"), varProp)))
            throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(homeMDB) Failed.",
                ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - Put(homeMDB) Failed.");

	varProp.Clear();
    if (!strLogonHomeMTA.empty())
    {
        varProp = strLogonHomeMTA.c_str();
        if (FAILED(hr = pIADNewUser->Put(CComBSTR("homeMTA"), varProp)))
            throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(homeMTA) Failed.",
                ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - Put(homeMTA) Failed.");

	varProp.Clear();
	if (!msExchHomeSvrName.empty())
    {
        varProp = msExchHomeSvrName.c_str();
        if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchHomeServerName"), varProp)))
            throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(msExchHomeServerName) Failed.",
                ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - Put(msExchHomeServerName) Failed.");
	varProp.Clear();

	varProp.Clear();
	wstring newUsrLegacyName=legacyName;
	size_t nwpos=newUsrLegacyName.rfind(L"cn=");
	if(nwpos !=wstring::npos)
	{
		newUsrLegacyName = newUsrLegacyName.substr(0,nwpos);
		newUsrLegacyName += L"cn=";
		newUsrLegacyName += lpwstrNewUser;
	}
	if (!newUsrLegacyName.empty())
    {
        varProp = newUsrLegacyName.c_str();
        if (FAILED(hr = pIADNewUser->Put(CComBSTR("legacyExchangeDN"), varProp)))
            throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(legacyExchangeDN) Failed.",
                ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - Put(legacyExchangeDN) Failed.");

    // set nickname
    varProp.Clear();
    varProp = lpwstrNewUser;
    if (FAILED(hr = pIADNewUser->Put(CComBSTR("mailNickname"), varProp)))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(mailNickname) Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - Put(mailNickname) Failed.");

    // set the displayName
    varProp.Clear();
    varProp = lpwstrNewUser;
    if (FAILED(hr = pIADNewUser->Put(CComBSTR("displayName"), varProp)))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(displayName) Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - Put(displayName) Failed.");
    // set the mail atrribute
    varProp.Clear();
    varProp = wstrMail.c_str();
    if (FAILED(hr = pIADNewUser->Put(CComBSTR("mail"), varProp)))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(mail) Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - Put(mail) Failed.");
    // set email
    if (FAILED(hr = pIADNewUser->put_EmailAddress(CComBSTR(wstrMail.c_str()))))
    {
        throw
            ExchangeAdminException(hr, L"CreateExchangeMailBox(): put_EmailAddress Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - put_EmailAddress Failed.");

	varProp.Clear();
	wstrMail=L"SMTP:"+wstrMail;
	varProp = wstrMail.c_str();
	if (FAILED(hr = pIADNewUser->Put(CComBSTR("proxyAddresses"),varProp)))
	{
        throw
            ExchangeAdminException(hr, L"CreateExchangeMailBox(): proxyAddressess Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    if(FAILED(hr = pIADNewUser->SetInfo()))
        ThrowSetInfoException(hr, L"SetInfo - proxyAddressess Failed.");

    // add to Domain Admins group
    BSTR bstrADSPath;

    if (FAILED(hr = pIADNewUser->get_ADsPath(&bstrADSPath)))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): get_ADsPath Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);

    wstring wstrGroup = _T("LDAP://CN=Domain Admins,CN=Users,") + wstrServerDN;
    Zimbra::Util::ScopedInterface<IADsGroup> pGroup;

    if (FAILED(hr = ADsGetObject(wstrGroup.c_str(), IID_IADsGroup, (void **)pGroup.getptr())))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsGetObject Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    if (FAILED(hr = ADsOpenObject(wstrGroup.c_str(), wstrLoggedUserName.c_str(),
            lpwstrLogonUsrPwd, ADS_SECURE_AUTHENTICATION, IID_IADsGroup,
            (void **)pGroup.getptr())))
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsOpenObject Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    if (SUCCEEDED(hr = pGroup->Add(bstrADSPath)))
    {
        if (FAILED(hr = pGroup->SetInfo()))
            throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): pGroup SetInfo Failed.",
                ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
    else
    {
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): pGroup Add Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }

	GUID guid;
    if(FAILED(hr = CoCreateGuid(&guid)))
    {
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): CoCreateGuid Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }

    BYTE *str;
    hr = UuidToString((UUID *)&guid, (RPC_WSTR *)&str);
    if (hr != RPC_S_OK)
    {
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): UuidToString Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }

	varProp.Clear();
	//BYTE bytArr[]="3429bb3084703348b8023e94fabf16ea";
	PutBinaryIntoVariant(&varProp,str,16);
	RpcStringFree((RPC_WSTR *)&str);
	if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchMailboxGuid"), varProp)))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put msExchMailboxGuid Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
	}
	if(FAILED(hr = pIADNewUser->SetInfo()))
            ThrowSetInfoException(hr, L"SetInfo - msExchMailboxGuid Failed.");

	if (FAILED(hr = ADsOpenObject(strContainer.c_str(), NULL, NULL, ADS_SECURE_AUTHENTICATION,
        IID_IDirectoryObject, (void **)pIAdUser.getptr())))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsOpenObject2 Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
	}	
	if (FAILED(hr = pIAdUser->QueryInterface(IID_IADs, (void**) pIAds.getptr())))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): pIAdUser->QueryInterface Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
	}

	varProp.Clear();
	if( FAILED(hr= pIAds->Get(CComBSTR("msExchMailboxSecurityDescriptor"),&varProp)))
	{
        throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Get msExchMailboxSecurityDescriptor Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
    }
	if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchMailboxSecurityDescriptor"), varProp)))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put msExchMailboxSecurityDescriptor Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
	}
	if(FAILED(hr = pIADNewUser->SetInfo()))
            ThrowSetInfoException(hr, L"SetInfo - msExchMailboxSecurityDescriptor Failed.");

	varProp.Clear();
	if( FAILED(hr=pIAds->Get(CComBSTR("msExchPoliciesIncluded"),&varProp)))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Get msExchPoliciesIncluded Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);        
    }
	if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchPoliciesIncluded"), varProp)))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put msExchPoliciesIncluded Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);     
	}
	if(FAILED(hr = pIADNewUser->SetInfo()))
            ThrowSetInfoException(hr, L"SetInfo - msExchPoliciesIncluded Failed.");

	varProp.Clear();
	if( FAILED(hr= pIAds->Get(CComBSTR("msExchUserAccountControl"),&varProp)))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Get msExchUserAccountControl Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);        
    }
	if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchUserAccountControl"), varProp)))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put msExchUserAccountControl Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);    
	}
	if(FAILED(hr = pIADNewUser->SetInfo()))
            ThrowSetInfoException(hr, L"SetInfo - msExchUserAccountControl Failed.");

	varProp.Clear();
	if(FAILED(hr = pIAds->GetEx(CComBSTR("showInAddressBook"), &varProp )))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Get showInAddressBook Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);		
	}
	if(FAILED(hr = pIADNewUser->Put(CComBSTR("showInAddressBook"), varProp)))
	{
		throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put showInAddressBook Failed.",
            ERR_CREATE_EXCHMBX, __LINE__, __FILE__);
	}
	if(FAILED(hr = pIADNewUser->SetInfo()))
            ThrowSetInfoException(hr, L"SetInfo - showInAddressBook Failed.");
    return hr;
}
HRESULT CAzAppGroup::Copy(CAzAppGroup &srcAppGroup) {

    CAzLogging::Entering(_TEXT("Copy"));

    CComBSTR bstrData;

    CComVariant cVVar;

    LONG lType;


    HRESULT hr=srcAppGroup.m_native->get_Description(&bstrData);

    CAzLogging::Log(hr,_TEXT("Getting Description for App Group"),COLE2T(srcAppGroup.getName()));

    if (SUCCEEDED(hr)) {

        hr=m_native->put_Description(bstrData);

        CAzLogging::Log(hr,_TEXT("Setting Description for App Group"),COLE2T(getName()));

        bstrData.Empty();
    }

    hr=srcAppGroup.m_native->get_Type(&lType);

    CAzLogging::Log(hr,_TEXT("Getting Type for App Group"),COLE2T(srcAppGroup.getName()));

    if (SUCCEEDED(hr)) {

        hr=m_native->put_Type(lType);

        CAzLogging::Log(hr,_TEXT("Setting Type for App Group"),COLE2T(getName()));

    }


    hr=srcAppGroup.m_native->get_LdapQuery(&bstrData);

    CAzLogging::Log(hr,_TEXT("Getting LDAPQuery for App Group"),COLE2T(srcAppGroup.getName()));

    // THe length check is reqd below as adding an empty string
    // LDAP Query returns an error

    if (SUCCEEDED(hr) && bstrData.Length()!=0) {

        hr=m_native->put_LdapQuery(bstrData);

        CAzLogging::Log(hr,_TEXT("Setting LDAPQuery for App Group"),COLE2T(getName()));

        bstrData.Empty();
    }

    if (CAzGlobalOptions::m_bVersionTwo) {

            hr = CopyVersion2Constructs(srcAppGroup);

            CAzLogging::Log(hr,_TEXT("Copying bizrule properties for App Group"),COLE2T(srcAppGroup.getName()));
    }

    if (!CAzGlobalOptions::m_bIgnoreMembers) {

        hr=srcAppGroup.m_native->get_Members(&cVVar);

        CAzLogging::Log(hr,_TEXT("Getting Members for App Group"),COLE2T(srcAppGroup.getName()));

        if (SUCCEEDED(hr)) {

            hr=InitializeUsingSafeArray(cVVar,&IAzApplicationGroup::AddMember);

            CAzLogging::Log(hr,_TEXT("Setting Members for App Group"),COLE2T(getName()));

            cVVar.Clear();
        }

        hr=srcAppGroup.m_native->get_NonMembers(&cVVar);

        CAzLogging::Log(hr,_TEXT("Getting Non Members for App Group"),COLE2T(srcAppGroup.getName()));

        if (SUCCEEDED(hr)) {

            hr=InitializeUsingSafeArray(cVVar,&IAzApplicationGroup::AddNonMember );

            CAzLogging::Log(hr,_TEXT("Setting Non Members for App Group"),COLE2T(getName()));

            cVVar.Clear();
        }
    }

    hr=m_native->Submit(0,CComVariant());

    CAzLogging::Log(hr,_TEXT("Submitting App Group"),COLE2T(getName()));

    CAzLogging::Exiting(_TEXT("Copy"));

    return hr;
}
Esempio n. 17
0
/////////////////////////////////////////////////////////////////////////////
// WMIClassProvider::createClassNameAndClassQualifiers
//
// ///////////////////////////////////////////////////////////////////////////
void WMIClassProvider::createClassNameAndClassQualifiers(const CIMClass& newClass,
														 IWbemServices *pServices,
														 IWbemClassObject **pNewClass,
														 const bool hasSuperClass)
{
	HRESULT hr;

	PEG_METHOD_ENTER(TRC_WMIPROVIDER, "WmiClassProvider::createClassNameAndClassQualifiers()");

	// if the class has a superclass, we need to spwan a derived
	if (hasSuperClass)
	{
		// get the superclass name
		CComPtr<IWbemClassObject> pSuperClass;
		String tmp = newClass.getSuperClassName().getString();
		CComBSTR bs = tmp.getCString();

		hr = pServices->GetObject(
				bs, 
				NULL, 
				NULL, 
				&pSuperClass, 
				NULL);

		bs.Empty();

		if (FAILED(hr))
		{
			if (pSuperClass)
				pSuperClass.Release();

			CMyString msg;
			msg.Format("Failed to get a pointer to Superclass [%s]. Error: 0x%X", 255, tmp.getCString(), hr);

			Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3, 
						  "WMIClassProvider::createClassNameAndClassQualifiers() - %s", (LPCTSTR)msg);

			throw CIMException(CIM_ERR_FAILED, (LPCTSTR)msg); 
		}

		//Creates the new class
		pSuperClass->SpawnDerivedClass(NULL, pNewClass);
		if (pSuperClass)
			pSuperClass.Release();
	}
	else
	{
		// we are creating a base class
		hr = pServices->GetObject(NULL, 
								  NULL, 
								  NULL, 
								  pNewClass, 
								  NULL);

		if (FAILED(hr))
		{
			CMyString msg;
			msg.Format("Failed to get a pointer to a new class. Error: 0x%X", hr);

			Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3, 
						  "WMIClassProvider::createClassNameAndClassQualifiers() - %s", (LPCTSTR)msg);
			
			throw CIMException(CIM_ERR_FAILED, (LPCTSTR)msg);
		}
	}
	
	// create the class name
	CComVariant v;
	v = newClass.getClassName().getString().getCString();
	hr = (*pNewClass)->Put(L"__CLASS", 0, &v, 0);
	
	v.Clear();

	if (FAILED(hr))
	{
		CMyString msg;
		msg.Format("Failed to add class name on class [%s]. Error: 0x%X", 255, 
			newClass.getClassName().getString().getCString(), hr);

		Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3, 
			          "WMIClassProvider::createClassNameAndClassQualifiers() - %s", (LPCTSTR)msg);

		if (*pNewClass)
			(*pNewClass)->Release();
		
		throw CIMException(CIM_ERR_FAILED, (LPCTSTR)msg);
	}

	// get a pointer to work with qualifiers
	CComPtr<IWbemQualifierSet> pNewClassQualifier;
	hr = (*pNewClass)->GetQualifierSet(&pNewClassQualifier);

	if (FAILED(hr))
	{
		CMyString msg;
		msg.Format("Failed to get the Qualifier set pointer of class [%s]. Error: 0x%X", 255, 
			newClass.getClassName().getString().getCString(), hr);

		Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3, 
			          "WMIClassProvider::createClassNameAndClassQualifiers() - %s", (LPCTSTR)msg);
		
		if (*pNewClass)
			(*pNewClass)->Release();

		if (pNewClassQualifier)
			pNewClassQualifier.Release();

		throw CIMException(CIM_ERR_FAILED, (LPCTSTR)msg);
	}
	
	// check the class qualifiers and create them if they are valid
	// we are taking care of the class qualifiers and not methods/properties qualifiers :D
	for (Uint32 i = 0; i < newClass.getQualifierCount(); i++)
	{
		try 
		{
			WMIQualifier qualifier(newClass.getQualifier(i).clone());
			
			createQualifier(qualifier, pNewClassQualifier);
		}
		catch (CIMException&)
		{
			if (*pNewClass)
				(*pNewClass)->Release();

			if (pNewClassQualifier)
				pNewClassQualifier.Release();

			throw;
		}
	}

	if (pNewClassQualifier)
		pNewClassQualifier.Release();

	PEG_METHOD_EXIT();

	return;
}
Esempio n. 18
0
int _tmain(int argc, _TCHAR* argv[])
{
	//BSTR的使用
	{
		BSTR bstrA = SysAllocString(L"Hello BSTR");
		BSTR bstrB = SysAllocStringLen(bstrA, SysStringLen(bstrA));
		SysFreeString(bstrA);
		SysFreeString(bstrB);
	}

	//用VARIANT保存LONG
	{
		VARIANT var;
		VariantInit(&var);

		var.vt = VT_I4;
		var.lVal = 100;

		VariantClear(&var);

		int i = 0;
		i++;
	}

	//用VARIANT保存FLOAT
	{
		VARIANT var;
		VariantInit(&var);
		
		var.vt = VT_R4;
		var.fltVal = 1.23f;

		VariantClear(&var);
	}

	//用VARIANT保存BSTR
	{
		VARIANT var;
		VariantInit(&var);
		
		var.vt = VT_BSTR;
		var.bstrVal = SysAllocString(L"Hello World");

		VariantClear(&var);
	}

	//用VARIANT保存布尔类型
	{
		VARIANT var;
		VariantInit(&var);

		var.vt = VT_BOOL;
		var.boolVal = VARIANT_FALSE;

		VariantClear(&var);
	}

	//从VARIANT读取相应类型的值
	{
		VARIANT var;
		VariantInit(&var);

		var.vt = VT_I4;
		var.lVal = 100;

		if (var.vt == VT_I4)
		{ 
			LONG lValue = var.lVal;
		}
		else if (var.vt == VT_R4)
		{
			FLOAT fValue = var.fltVal;
		}
		else if (var.vt == VT_BSTR)
		{
			BSTR bstrValue = var.bstrVal;
		}
		else if (var.vt == VT_BOOL)
		{
			VARIANT_BOOL varbValue = var.boolVal;
		}

		VariantClear(&var);
	}

	//COM数据类型的转换,LONG转成FLOAT
	{
		VARIANT var;
		VariantInit(&var);

		var.vt = VT_I4;
		var.lVal = 100;

		VariantChangeType(&var,&var,0, VT_R4);

		if (var.vt == VT_R4)
		{
			FLOAT fValue = var.fltVal;
		}

		VariantClear(&var);
	}

	//COM数据类型的转换,LONG转成BSTR
	{
		VARIANT var;
		VariantInit(&var);

		var.vt = VT_I4;
		var.lVal = 100;

		VariantChangeType(&var,&var,0, VT_BSTR);

		if (var.vt == VT_BSTR)
		{
			BSTR fValue = var.bstrVal;
		}

		VariantClear(&var);
	}

	//CComVariant的构造方法
	{
		VARIANT varA;
		CComVariant varB;
		CComVariant varC(varA);
		CComVariant varD(varB);
		CComVariant varE(L"Hello CComVariant");
		CComVariant varF("CComVariant");
		CComVariant varG(true);
		CComVariant varH(100L);
		CComVariant varI(1.23f);
		//....

	}

	//CComVariant的赋值方法
	{
		VARIANT varA;
		CComVariant varB;
		CComVariant varC;
		varC = varA;
		varC = varB;
		varC = true;
		varC = 100L;
		varC = 1.23f;
		varC = L"Hello CComVariant";
		varC = "Hello CComVariant";
		//....
	}

	//CComVariant与VARIANT的关联
	{
		VARIANT varA;
		VariantInit(&varA);
		varA.vt = VT_I4;
		varA.lVal = 100;
		
		CComVariant varB;

		CComVariant varC(100L);
		
		VARIANT varD;
		VariantInit(&varD);

		//Attach
		varB.Attach(&varA);		//之后无需调用VariantClear(&varA);

		//Detach
		varC.Detach(&varD);
		VariantClear(&varD);	//需要调用VariantClear(&varD);
	}

	return 0;
}
Esempio n. 19
0
int Script::Execute() {
  LOG(TRACE) << "Entering Script::Execute";

  CComVariant result = L"";
  CComBSTR error_description = L"";

  if (this->script_engine_host_ == NULL) {
    LOG(WARN) << "Script engine host is NULL";
    return ENOSUCHDOCUMENT;
  }
  CComVariant temp_function;
  if (!this->CreateAnonymousFunction(&temp_function)) {
    LOG(WARN) << "Cannot create anonymous function";
    return EUNEXPECTEDJSERROR;
  }

  if (temp_function.vt != VT_DISPATCH) {
    LOG(DEBUG) << "No return value that we care about";
    return WD_SUCCESS;
  }

  // Grab the "call" method out of the returned function
  DISPID call_member_id;
  OLECHAR FAR* call_member_name = L"call";
  HRESULT hr = temp_function.pdispVal->GetIDsOfNames(IID_NULL,
                                                     &call_member_name,
                                                     1,
                                                     LOCALE_USER_DEFAULT,
                                                     &call_member_id);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Cannot locate call method on anonymous function";
    return EUNEXPECTEDJSERROR;
  }

  CComPtr<IHTMLWindow2> win;
  hr = this->script_engine_host_->get_parentWindow(&win);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Cannot get parent window, IHTMLDocument2::get_parentWindow failed";
    return EUNEXPECTEDJSERROR;
  }

  // IDispatch::Invoke() expects the arguments to be passed into it
  // in reverse order. To accomplish this, we create a new variant
  // array of size n + 1 where n is the number of arguments we have.
  // we copy each element of arguments_array_ into the new array in
  // reverse order, and add an extra argument, the window object,
  // to the end of the array to use as the "this" parameter for the
  // function invocation.
  size_t arg_count = this->argument_array_.size();
  std::vector<CComVariant> argument_array_copy(arg_count + 1);
  CComVariant window_variant(win);
  argument_array_copy[arg_count].Copy(&window_variant);

  for (size_t index = 0; index < arg_count; ++index) {
    argument_array_copy[arg_count - 1 - index].Copy(&this->argument_array_[index]);
  }

  DISPPARAMS call_parameters = { 0 };
  memset(&call_parameters, 0, sizeof call_parameters);
  call_parameters.cArgs = static_cast<unsigned int>(argument_array_copy.size());
  call_parameters.rgvarg = &argument_array_copy[0];

  int return_code = WD_SUCCESS;
  EXCEPINFO exception;
  memset(&exception, 0, sizeof exception);
  hr = temp_function.pdispVal->Invoke(call_member_id,
                                      IID_NULL,
                                      LOCALE_USER_DEFAULT,
                                      DISPATCH_METHOD,
                                      &call_parameters, 
                                      &result,
                                      &exception,
                                      0);

  if (FAILED(hr)) {
    if (DISP_E_EXCEPTION == hr) {
      error_description = exception.bstrDescription ? exception.bstrDescription : L"EUNEXPECTEDJSERROR";
      CComBSTR error_source(exception.bstrSource ? exception.bstrSource : L"EUNEXPECTEDJSERROR");
      LOG(INFO) << "Exception message was: '" << error_description << "'";
      LOG(INFO) << "Exception source was: '" << error_source << "'";
    } else {
      LOGHR(DEBUG, hr) << "Failed to execute anonymous function, no exception information retrieved";
    }

    result.Clear();
    result.vt = VT_BSTR;
    result.bstrVal = error_description;
    return_code = EUNEXPECTEDJSERROR;
  }

  this->result_.Copy(&result);

  return return_code;
}
Esempio n. 20
0
void CGPAXPlugin::LoadDATAUrl()
{
#ifndef _WIN32_WCE
	HRESULT hr;

	if (m_url[0]) return;
    /*get parent doc*/
	CComPtr<IOleContainer> spContainer;
	if (m_spClientSite->GetContainer(&spContainer) != S_OK)
		return;
    CComPtr<IHTMLDocument2> spDoc = CComQIPtr<IHTMLDocument2>(spContainer);
    CComPtr<IHTMLElementCollection> spColl;
	if (spDoc->get_all(&spColl) != S_OK)
		return;
	/*get HTML <object> in the doc*/
    CComPtr<IDispatch> spDisp;
	CComPtr<IHTMLElementCollection> sphtmlObjects;

    CComPtr<IDispatch> spDispObjects;
	if (spColl->tags(CComVariant("OBJECT"), &spDispObjects) != S_OK)
		return;
    CComPtr<IHTMLElementCollection> spObjs = CComQIPtr<IHTMLElementCollection>(spDispObjects);
	
	/*browse all objects and find us*/
	long lCount = 0;
	spObjs->get_length(&lCount);
	for (long lCnt = 0; lCnt < lCount; lCnt++) {   
		IDispatch *an_obj= NULL;
		CComVariant varEmpty;
		CComVariant varName;
		varName.vt = VT_I4;
		varName.lVal = lCnt;
		hr = spObjs->item(varName, varEmpty, &an_obj);
		varName.Clear();
		varEmpty.Clear();
		if (hr != S_OK) continue;

		/*get the IHTMLObject*/
		IHTMLObjectElement* pObjectElem=NULL;
		an_obj->QueryInterface(IID_IHTMLObjectElement, (void**)&pObjectElem);
		if (!pObjectElem) continue;

		/*get its parent owner - it MUST be us*/
		IDispatch *disp= NULL;
		pObjectElem->get_object(&disp);
		if (disp != this) continue;

		BSTR data = NULL;
		if ((pObjectElem->get_data(&data) == S_OK) && data) {
			const u16 *srcp = (const u16 *) data;
			u32 len = gf_utf8_wcstombs(m_url, MAXLEN_URL, &srcp);
			if (len>=0) m_url[len] = 0;
		}
		SysFreeString(data);
		break;
	}

	if (m_url) {
		UpdateURL();
	}
#endif

}
HRESULT CPageEvents::UpdateItemFromNode(LPARAM lNode)
{
  USES_CONVERSION;

  // Typecast the tree item's param as an XML element pointer
  IXMLDOMElement* pElement = reinterpret_cast<IXMLDOMElement*>(lNode);
  if (!pElement)
    return S_FALSE;

  // Use to enable/disable the check boxes
  bool bEnableLog2NT = false;
  bool bEnableLog2DB = false;

  // Determine if the node is a group element or an event
  CComBSTR bstrTagName;
  VERIFY(SUCCEEDED(pElement->get_tagName(&bstrTagName)));
  bool bIsEvent = 0 == wcscmp(bstrTagName, m_bstrEvent);
  bool bIsGroup = !bIsEvent && 0 == wcscmp(bstrTagName, m_bstrEventGroup);
  ASSERT(bIsEvent || bIsGroup);
  if (bIsEvent)
  {
    // Get the Severity attribute
    CComVariant varSeverity;
    pElement->getAttribute(m_bstrSeverity, &varSeverity);
    VERIFY(SUCCEEDED(varSeverity.ChangeType(VT_BSTR)));
    SetDlgItemText(IDC_EVENT_TYPE, TypeFromSeverity(V_BSTR(&varSeverity)));

    // Get the event id attribute
    CComVariant varEventID;
    pElement->getAttribute(m_bstrID, &varEventID);
    VERIFY(SUCCEEDED(varEventID.ChangeType(VT_I4)));
    SetDlgItemInt(IDC_EVENT_ID, V_I4(&varEventID));

    // Get the CanChangeLogAsNTEvent attribute
    IXMLDOMAttributePtr spAttrNT;
    if (S_OK == pElement->getAttributeNode(m_bstrCanChangeLogAsNTEvent, &spAttrNT))
    {
      CComVariant varCanChange;
      spAttrNT->get_value(&varCanChange);
      VERIFY(SUCCEEDED(varCanChange.ChangeType(VT_BOOL)));
      bEnableLog2NT = !!V_BOOL(&varCanChange);
    }
    else
    {
      // When not specified, the default is true
      bEnableLog2NT = true;
    }

    // Get the LogAsNTEvent attribute
    CComVariant varLog2NT;
    pElement->getAttribute(m_bstrLogAsNTEvent, &varLog2NT);
    VERIFY(SUCCEEDED(varLog2NT.ChangeType(VT_BOOL)));
    CheckDlgButton(IDC_LOG2NT, V_BOOL(&varLog2NT));

    // Get the CanChangeLogAsDBEvent attribute
    IXMLDOMAttributePtr spAttrDB;
    if (S_OK == pElement->getAttributeNode(m_bstrCanChangeLogAsDBEvent, &spAttrDB))
    {
      CComVariant varCanChange;
      spAttrDB->get_value(&varCanChange);
      VERIFY(SUCCEEDED(varCanChange.ChangeType(VT_BOOL)));
      bEnableLog2DB = !!V_BOOL(&varCanChange);
    }
    else
    {
      // When not specified, the default is true
      bEnableLog2DB = true;
    }

    // Get the LogAsDBEvent attribute
    CComVariant varLog2DB;
    pElement->getAttribute(m_bstrLogAsDBEvent, &varLog2DB);
    VERIFY(SUCCEEDED(varLog2DB.ChangeType(VT_BOOL)));
    CheckDlgButton(IDC_LOG2DB, V_BOOL(&varLog2DB));
  }
  else
  {
    // Always show the type as "Group"
    CString strGroup;
    strGroup.LoadString(IDS_TYPE_GROUP);
    SetDlgItemText(IDC_EVENT_TYPE, strGroup);

    // Get the group LowerBound attribute
    CComVariant varLowerBound;
    pElement->getAttribute(m_bstrLowerBound, &varLowerBound);
    VERIFY(SUCCEEDED(varLowerBound.ChangeType(VT_UI4)));

    // Get the group UpperBound attribute
    CComVariant varUpperBound;
    pElement->getAttribute(m_bstrUpperBound, &varUpperBound);
    VERIFY(SUCCEEDED(varUpperBound.ChangeType(VT_UI4)));

    // Format the group's range into a string
    TCHAR szID[_MAX_PATH];
    wsprintf(szID, TEXT("%u - %u"), V_UI4(&varLowerBound),
      V_UI4(&varUpperBound));
    SetDlgItemText(IDC_EVENT_ID, szID);

    // TODO: Work-out how to best support indeterminate checkbox state
    CheckDlgButton(IDC_LOG2NT, false);
    CheckDlgButton(IDC_LOG2DB, false);
  }

  // Get the event/group Description attribute
  CComVariant varDescription;
  pElement->getAttribute(m_bstrDescription, &varDescription);
  VERIFY(SUCCEEDED(varDescription.ChangeType(VT_BSTR)));
  SetDlgItemText(IDC_DESCRIPTION, OLE2CT(V_BSTR(&varDescription)));

  // Enable/disable checkboxes
  GetDlgItem(IDC_LOG2NT)->EnableWindow(bEnableLog2NT);
  GetDlgItem(IDC_LOG2DB)->EnableWindow(bEnableLog2DB);

  // Uncheck checkboxes that are disabled
  if (!bEnableLog2NT)
    CheckDlgButton(IDC_LOG2NT, false);
  if (!bEnableLog2DB)
    CheckDlgButton(IDC_LOG2DB, false);

  // Indicate success
  return S_OK;
}
Esempio n. 22
0
// *****************************************************************
//			GenerateCategories()
// *****************************************************************
vector<CategoriesData>* FieldClassification::GenerateCategories(CString fieldName, FieldType fieldType, 
		vector<VARIANT*>& srcValues, tkClassificationType ClassificationType, 
		long numClasses, long& errorCode)
{
	CComVariant minValue, maxValue;
	minValue.vt = VT_EMPTY;
	maxValue.vt = VT_EMPTY;

	long numShapes = srcValues.size();

	/* we won't define intervals for string values */
	if (ClassificationType != ctUniqueValues && fieldType == STRING_FIELD)
	{
		errorCode = tkNOT_UNIQUE_CLASSIFICATION_FOR_STRINGS;
		return NULL;
	}

	if ((numClasses <= 0 || numClasses > 1000) && (ClassificationType != ctUniqueValues))
	{
		errorCode = tkTOO_MANY_CATEGORIES;
		return NULL;
	}

	if (ClassificationType == ctStandardDeviation)
	{
		errorCode = tkINVALID_PARAMETER_VALUE;
		return NULL;
	}

	// natural breaks aren't designed to work otherwise
	if (numShapes < numClasses && ClassificationType == ctNaturalBreaks)
	{
		numClasses = numShapes;
	}

	// values in specified range should be classified
	bool useRange = minValue.vt != VT_EMPTY && maxValue.vt != VT_EMPTY && fieldType == DOUBLE_FIELD;

	if (useRange) //fieldType == DOUBLE_FIELD)
	{
		double max, min;
		dVal(minValue, min);
		dVal(maxValue, max);
		minValue.vt = VT_R8;
		maxValue.vt = VT_R8;
		minValue.dblVal = min;
		maxValue.dblVal = max;
	}

	//bool useRange = minValue.vt == VT_R8 && maxValue.vt == VT_R8 && fieldType != STRING_FIELD;

	std::vector<CategoriesData>* result = new std::vector<CategoriesData>;
	if (ClassificationType == ctUniqueValues)
	{
		std::set<CComVariant> dict;
		CComVariant val;

		for (long i = 0; i < numShapes; i++)
		{
			VariantCopy(&val, srcValues[i]);
			if (useRange && (val.dblVal < minValue.dblVal || val.dblVal > maxValue.dblVal))
				continue;

			if (dict.find(val) == dict.end())
				dict.insert(val);
		}
		/* creating categories */
		std::vector<CComVariant> values;
		copy(dict.begin(), dict.end(), inserter(values, values.end()));

		for (int i = 0; i < (int)values.size(); i++)
		{
			CategoriesData data;
			data.minValue = values[i];
			data.maxValue = values[i];
			result->push_back(data);
		}
		dict.clear();
		values.clear();
	}
	else if (ClassificationType == ctEqualSumOfValues)
	{
		CComVariant val;

		// sorting the values
		std::vector<double> values;
		double totalSum = 0, dValue;
		for (int i = 0; i < numShapes; i++)
		{
			VariantCopy(&val, srcValues[i]);
			if (useRange && (val.dblVal < minValue.dblVal || val.dblVal > maxValue.dblVal))
				continue;

			dVal(val, dValue); val.Clear();
			values.push_back(dValue);
			totalSum += dValue;
		}
		sort(values.begin(), values.end());

		double step = totalSum / (double)numClasses;
		int index = 1;
		double sum = 0;

		for (int i = 0; i < (int)values.size(); i++)
		{
			sum += values[i];
			if (sum >= step * (double)index || i == numShapes - 1)
			{
				CategoriesData data;

				if (index == numClasses)
					data.maxValue = values[values.size() - 1];
				else if (i != 0)
					data.maxValue = (values[i] + values[i - 1]) / 2;
				else
					data.maxValue = values[0];

				if (index == 1)
					data.minValue = values[0];
				else
					data.minValue = (*result)[result->size() - 1].maxValue;

				result->push_back(data);
				index++;
			}
		}
	}
	else if (ClassificationType == ctEqualIntervals)
	{
		CComVariant vMin, vMax;

		if (useRange)
		{
			vMin = minValue;
			vMax = maxValue;
		}
		else
		{
			GetMinValue(srcValues, vMin, true);
			GetMinValue(srcValues, vMax, false);
		}

		double dMin, dMax;
		dVal(vMin, dMin); dVal(vMax, dMax);
		vMin.Clear(); vMax.Clear();

		/*	creating classes */
		double dStep = (dMax - dMin) / (double)numClasses;
		while (dMin < dMax)
		{
			CategoriesData data;
			data.minValue = dMin;
			data.maxValue = dMin + dStep;
			result->push_back(data);

			dMin += dStep;
		}
	}
	else if (ClassificationType == ctEqualCount)
	{
		CComVariant vMin, vMax;
		if (useRange)
		{
			vMin = minValue;
			vMax = maxValue;
		}
		else
		{
			GetMinValue(srcValues, vMin, true);
			GetMinValue(srcValues, vMax, false);
		}

		double dMin, dMax;
		dVal(vMin, dMin); dVal(vMax, dMax);
		vMin.Clear(); vMax.Clear();

		// sorting the values
		std::vector<double> values;
		for (int i = 0; i < numShapes; i++)
		{
			VariantCopy(&vMin, srcValues[i]);
			dVal(vMin, dMin); vMin.Clear();
			values.push_back(dMin);
		}
		sort(values.begin(), values.end());

		/*	creating classes */
		int i = 0;
		int count = numShapes / numClasses;

		for (int i = 0; i < numShapes; i += count)
		{
			dMin = values[i];
			if (i + count < numShapes)
				dMax = values[i + count];
			else
				dMax = values[numShapes - 1];

			CategoriesData data;
			data.minValue = dMin;
			data.maxValue = dMax;
			result->push_back(data);
		}
		values.clear();
	}
	else if (ClassificationType == ctNaturalBreaks)
	{
		CComVariant vMin; double dMin;
		// sorting the values
		std::vector<double> values;
		for (int i = 0; i < numShapes; i++)
		{
			VariantCopy(&vMin, srcValues[i]);

			if (useRange && (vMin.dblVal < minValue.dblVal || vMin.dblVal > maxValue.dblVal))
				continue;

			dVal(vMin, dMin); vMin.Clear();
			values.push_back(dMin);
		}
		sort(values.begin(), values.end());

		CJenksBreaks breaks(&values, numClasses);
		if (breaks.Initialized())
		{
			breaks.Optimize();
			std::vector<long>* startIndices = breaks.get_Results();
			//std::vector<int>* startIndices = breaks.TestIt(&values, numClasses);

			if (startIndices)
			{
				for (unsigned int i = 0; i < startIndices->size(); i++)
				{
					CategoriesData data;
					data.minValue = values[(*startIndices)[i]];
					if (i == startIndices->size() - 1)
						data.maxValue = values[values.size() - 1];
					else
						data.maxValue = values[(*startIndices)[i + 1]];

					result->push_back(data);
				}
				delete startIndices;
			}
		}
	}
	
	// TODO: implement this as well; then it can be used in table class
	//else if (ClassificationType == ctStandardDeviation)

	// ------------------------------------------------------
	//		generating text expressions
	// ------------------------------------------------------
	if (ClassificationType == ctUniqueValues)
	{
		USES_CONVERSION;
		for (int i = 0; i < (int)result->size(); i++)
		{
			//CString strExpression;
			CString strValue;
			CComVariant* val = &(*result)[i].minValue;
			switch (val->vt)
			{
				case VT_BSTR:
					strValue = OLE2CA(val->bstrVal);
					(*result)[i].name = strValue;
					(*result)[i].expression = "[" + fieldName + "] = \"" + strValue + "\"";
					break;
				case VT_R8:
					strValue.Format("%g", val->dblVal);
					(*result)[i].name = strValue;
					(*result)[i].expression = "[" + fieldName + "] = " + strValue;
					break;
				case VT_I4:
					strValue.Format("%i", val->lVal);
					(*result)[i].name = strValue;
					(*result)[i].expression = "[" + fieldName + "] = " + strValue;
					break;
			}
		}
	}
	else //if (ClassificationType == ctEqualIntervals || ClassificationType == ctEqualCount)
	{
		// in case % is present, we need to put to double it for proper formatting
		fieldName.Replace("%", "%%");

		for (int i = 0; i < (int)result->size(); i++)
		{
			CategoriesData* data = &((*result)[i]);

			CString strExpression, strName, sFormat;

			if (i == 0)
			{
				data->minValue.dblVal = floor(data->minValue.dblVal);
			}
			else if (i == result->size() - 1)
			{
				data->maxValue.dblVal = ceil(data->maxValue.dblVal);
			}

			CString upperBound = (i == result->size() - 1) ? "<=" : "<";

			switch (data->minValue.vt)
			{
				case VT_R8:
					sFormat = "%g";
					data->name = Utility::FormatNumber(data->minValue.dblVal, sFormat) + " - " + Utility::FormatNumber(data->maxValue.dblVal, sFormat);
					data->expression.Format("[" + fieldName + "] >= %f AND [" + fieldName + "] " + upperBound + " %f", data->minValue.dblVal, data->maxValue.dblVal);
					break;
				case VT_I4:
					sFormat = "%i";
					data->name = Utility::FormatNumber(data->minValue.dblVal, sFormat) + " - " + Utility::FormatNumber(data->maxValue.dblVal, sFormat);
					data->expression.Format("[" + fieldName + "] >= %i AND [" + fieldName + "] " + upperBound + " %i", data->minValue.lVal, data->maxValue.lVal);
					break;
			}
		}
	}

	if (result->size() > 0)
	{
		return result;
	}
	else
	{
		delete result;
		return NULL;
	}
}
STDMETHODIMP CLogoMarkerSymbol::Load(IVariantStream *Stream)
{
	CComVariant vLoad;
	HRESULT hr;

	//load ISymbol properties 
	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_I4)
		m_lROP2 = (esriRasterOpCode)vLoad.lVal;
	else
		return E_FAIL;
	vLoad.Clear();

	//load IMarkerSymbol properties
	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_R8)
		m_dSize = vLoad.dblVal;
	else
		return E_FAIL;
	vLoad.Clear();

	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_R8)
		m_dXOffset = vLoad.dblVal;
	else
		return E_FAIL;
	vLoad.Clear();
	
	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_R8)
		m_dYOffset = vLoad.dblVal;
	else
		return E_FAIL;
	vLoad.Clear();
	
	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_R8)
		m_dAngle = vLoad.dblVal;
	else
		return E_FAIL;
	vLoad.Clear();

	//load ISymbolRotation properties
	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_BOOL)
		m_bRotWithTrans = vLoad.boolVal;
	else
		return E_FAIL;
	vLoad.Clear();

	//load IMapLevel properties
	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_I4)
		m_lMapLevel = vLoad.lVal;
	else
		return E_FAIL;
	vLoad.Clear();

	//load custom properties
	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_UNKNOWN)
		m_ipTopColor = (IColorPtr) vLoad.punkVal;
	else
		return E_FAIL;
	vLoad.Clear();
	
	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_UNKNOWN)
		m_ipLeftColor = (IColorPtr) vLoad.punkVal;
	else
		return E_FAIL;
	vLoad.Clear();

	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_UNKNOWN)
		m_ipRightColor = (IColorPtr) vLoad.punkVal;
	else
		return E_FAIL;
	vLoad.Clear();

	if (FAILED(hr = Stream->Read(&vLoad))) return hr;
	if (vLoad.vt == VT_UNKNOWN)
		m_ipBorderColor = (IColorPtr) vLoad.punkVal;
	else
		return E_FAIL;

	return S_OK;
}
Esempio n. 24
0
HRESULT CAzRole::CopyUserData(CAzRole &srcRole){

    CAzLogging::Entering(_TEXT("CAzRole::CopyUserData"));

    HRESULT hr;

    CComVariant var;

    hr=srcRole.m_native->get_Operations(&var);

    CAzLogging::Log(hr,_TEXT("Getting operations for role"),COLE2T(getName()));			

    if (SUCCEEDED(hr)) {

        hr=InitializeUsingSafeArray(var,&IAzRole::AddOperation);

        CAzLogging::Log(hr,_TEXT("Adding Operations"),COLE2T(getName()));

        var.Clear();
    }

    hr=srcRole.m_native->get_AppMembers(&var);

    CAzLogging::Log(hr,_TEXT("Getting app members for role"),COLE2T(getName()));

    if (SUCCEEDED(hr)) {

        hr=InitializeUsingSafeArray(var,&IAzRole::AddAppMember);

        CAzLogging::Log(hr,_TEXT("Setting app members for role"),COLE2T(getName()));

        var.Clear();

    }

    if (!CAzGlobalOptions::m_bIgnoreMembers) {

        hr=srcRole.m_native->get_Members(&var);

        CAzLogging::Log(hr,_TEXT("Getting Members for role"),COLE2T(getName()));

        if (SUCCEEDED(hr)) {

            hr=InitializeUsingSafeArray(var,&IAzRole::AddMember);

            CAzLogging::Log(hr,_TEXT("Setting Members for role"),COLE2T(getName()));

            var.Clear();

        }
    }

    hr=srcRole.m_native->get_Tasks(&var);

    CAzLogging::Log(hr,_TEXT("Getting Tasks for role"),COLE2T(getName()));

    if (SUCCEEDED(hr)) {

        hr=InitializeUsingSafeArray(var,&IAzRole::AddTask);

        CAzLogging::Log(hr,_TEXT("Setting Tasks for role"),COLE2T(getName()));

        }

    CAzLogging::Exiting(_TEXT("CAzRole::CopyUserData"));

    return hr;
}
/*++

Routine description:

    This method copies properties from the source application to *this*
    Application

Arguments: pApp - Source Application

Return Value:

    Returns success, appropriate failure value of the get/set methods done within 
    this method

--*/
HRESULT CAzApplication::Copy(CAzApplication &pApp) {

    CAzLogging::Entering(_TEXT("Copy"));

    if (!m_isNew)

        return E_FAIL;

    CComVariant cVVar;

    HRESULT hr;

    for (long i=0;i<m_uchNumberOfProps;i++) {

        hr=pApp.m_native->GetProperty(m_props[i],CComVariant(), &cVVar);

        CAzLogging::Log(hr,_TEXT("Getting IAzApplication Property ID:"),COLE2T(getName()),m_props[i]);

        if (SUCCEEDED(hr)) {

            hr=m_native->SetProperty(m_props[i],cVVar,CComVariant());

            CAzLogging::Log(hr,_TEXT("Setting IAzApplication Property ID:"),COLE2T(getName()),m_props[i]);

            cVVar.Clear();

        }

    }
    
    if (!CAzGlobalOptions::m_bIgnorePolicyAdmins) {

        hr=pApp.m_native->get_DelegatedPolicyUsers(&cVVar);

        CAzLogging::Log(hr,_TEXT("Getting IAzApplication Delegated Policy Users"),COLE2T(getName()));			

        if (SUCCEEDED(hr)) {

            hr=InitializeUsingSafeArray(cVVar,&IAzApplication::AddDelegatedPolicyUser);

            CAzLogging::Log(hr,_TEXT("Setting IAzApplication Delegated Policy Users"),COLE2T(getName()));

            cVVar.Clear();
        } 

        hr=pApp.m_native->get_PolicyAdministrators(&cVVar);

        CAzLogging::Log(hr,_TEXT("Getting IAzApplication Policy Admins"),COLE2T(getName()));

        if (SUCCEEDED(hr)) {

            hr=InitializeUsingSafeArray(cVVar,&IAzApplication::AddPolicyAdministrator);

            CAzLogging::Log(hr,_TEXT("Setting IAzApplication Policy Admins"),COLE2T(getName()));

            cVVar.Clear();
        }

        hr=pApp.m_native->get_PolicyReaders(&cVVar);

        CAzLogging::Log(hr,_TEXT("Getting IAzApplication Policy Readers"),COLE2T(getName()));

        if (SUCCEEDED(hr)) {

            hr=InitializeUsingSafeArray(cVVar,&IAzApplication::AddPolicyReader);

            CAzLogging::Log(hr,_TEXT("Setting IAzApplication Delegated Policy Readers"),COLE2T(getName()));

            cVVar.Clear();
        } 

    }
    hr=m_native->Submit(0,CComVariant());

    CAzLogging::Log(hr,_TEXT("Submitting for IAzApplication"),COLE2T(getName()));

    hr=CreateChildItems(pApp);

    CAzLogging::Log(hr,_TEXT("Creating Child Objects for IAzApplication"),COLE2T(getName()));

    CAzLogging::Exiting(_TEXT("Copy"));
    return hr;
}
Esempio n. 26
0
CString _getWmiInfo(IWbemClassObject *pClassObject, LPCTSTR lpszName)
{
	CComVariant varValue ;
	CComBSTR bstrName(lpszName);
	CString str ;
	if( pClassObject->Get( bstrName , 0 , &varValue , NULL , 0 ) == S_OK )
	{
		// 对不同的数据类型分别处理
		if( varValue.vt == VT_BSTR )	//字符串
		{
			str = CString(varValue.bstrVal) ;
		}
		else 
			if( varValue.vt == VT_ARRAY ) //数组
			{
				long iLowBound = 0 , iUpBound = 0 ;
				SafeArrayGetLBound( varValue.parray , 1 , &iLowBound ) ;
				SafeArrayGetUBound( varValue.parray , 1 , &iUpBound ) ;
				for( long j = iLowBound ; j <= iUpBound ; j ++ )
				{
					VARIANT *pvar = NULL ;
					long temp = j ;
					if( SafeArrayGetElement( varValue.parray , &temp , pvar ) == S_OK && pvar )
					{
						CComVariant varTemp ;
						if( varTemp.ChangeType( VT_BSTR , pvar ) == S_OK )
						{
							if( !str.IsEmpty() )
								str += _T(",") ;
							str += varTemp.bstrVal ;
						} //if( varTemp...
					} //if( SafeArrayGet...
				} //for( long j=iLowBound;...
			} //if (varValue.vt ...
			else
			{
				switch( varValue.vt)
				{
				case VT_I4:
					str.Format("%d", varValue.lVal);
					break;
				case VT_I8:
					str.Format("%l", varValue.llVal);
					break;
				case VT_I2:
					str.Format("%d", varValue.iVal);
					break;
				case VT_UI1:
					str.Format("%uc", varValue.bVal);
					break;
				case VT_R4:
					str.Format("%f", varValue.fltVal);
					break;
				case VT_R8:
					str.Format("%lf", varValue.dblVal);
					break;
				case VT_I1:
					str.Format("%c", varValue.cVal);
					break;
				case VT_UI2:
					str.Format("%ud", varValue.uiVal);
					break;
				case VT_UI4:
					str.Format("%ud", varValue.ulVal);
					break;
				case VT_UI8:
					str.Format("%ul", varValue.ullVal);
					break;
				case VT_BOOL:
					cout<<"bool***************\n";
					break;
				case VT_NULL:
					str = "NULL";
					break;
				default:
					if( varValue.ChangeType( VT_BSTR ) == S_OK )
						str = varValue.bstrVal ;
					else
						cout<<"Cannot handle the the data type of "<<CString(bstrName)<<": "<<varValue.vt<<endl;
				}
			}

			// 打印出硬件信息
			//cout<<CString(bstrName)<<" = "<<str<<endl;
	}
	else
		str = "";

	return str;
}
Esempio n. 27
0
////////////////////////////////////////////////////////////////
//
// addWMIParametersToCIMMethod
//
// Add parameters from a WMI class to a CIMMethod.
//
///////////////////////////////////////////////////////////////
void addWMIParametersToCIMMethod(
        const CComPtr<IWbemClassObject>& wmiParameters, 
        CIMMethod& method,
        Boolean includeQualifiers)
{
    // Check if wmiParameters is NULL (this will ocurr when there are none)
    HRESULT hr;
    if (wmiParameters)
    {
        // Enumerate all output parameters
        hr = wmiParameters->BeginEnumeration(WBEM_FLAG_LOCAL_ONLY);
        while(true)
        {
            // Get current parameter name and value
            CComBSTR bstrParamName;
            CComVariant vParamValue;
            CIMTYPE wmiType;
            hr = wmiParameters->Next(0, &bstrParamName, 
                &vParamValue, &wmiType, NULL);

            // Check errors
            if (WBEM_S_NO_MORE_DATA == hr) 
            {
                break;
            }
            if (FAILED(hr)) 
            {
                bstrParamName.Empty();
                vParamValue.Clear();
                throw CIMException(CIM_ERR_FAILED);
            }
            
            // Convert to CIMParameter
            BSTR tmpBstr = (BSTR)bstrParamName.Copy();
            String parameterName(_bstr_t(tmpBstr, FALSE));
            SysFreeString(tmpBstr);

            // Add the parameter to this method if it is not the return value
            // and it does not already exist in the method.
            // If the parameter already exists (i.e., an in & out parameter), 
            // then there is no need to re-add or modify it here
            // (the in version is an exact copy of the out version):
            String strRetVal("ReturnValue");
            if (!(String::equalNoCase(parameterName, strRetVal)) &&
                method.findParameter(parameterName) == PEG_NOT_FOUND)
            {
                // Get the qualifier list for this param from WMI:
                CComPtr<IWbemQualifierSet> pParamQualifiers;
                HRESULT hr = 
                    wmiParameters->GetPropertyQualifierSet(bstrParamName, 
                                                           &pParamQualifiers);
                
                // create the CIMParameter
                CIMParameter cimParam = 
                    cimParamFromWMIParam(parameterName,
                                         wmiType,
                                         pParamQualifiers,
                                         includeQualifiers);

                // Now, add the new parameter to the CIMMethod:
                method.addParameter(cimParam);

                if (pParamQualifiers)
                    pParamQualifiers.Release();
            }

            bstrParamName.Empty();
            vParamValue.Clear();
        }
        hr = wmiParameters->EndEnumeration();    
    }
}
Esempio n. 28
0
BOOL CPPageOutput::OnInitDialog()
{
    __super::OnInitDialog();

    SetHandCursor(m_hWnd, IDC_AUDRND_COMBO);

    const CAppSettings& s = AfxGetAppSettings();
    const CRenderersSettings& renderersSettings = s.m_RenderersSettings;

    m_iDSVideoRendererType  = s.iDSVideoRendererType;
    m_iRMVideoRendererType  = s.iRMVideoRendererType;
    m_iQTVideoRendererType  = s.iQTVideoRendererType;

    m_APSurfaceUsageCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_SURF_OFFSCREEN));
    m_APSurfaceUsageCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_SURF_2D));
    m_APSurfaceUsageCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_SURF_3D));
    m_iAPSurfaceUsage       = renderersSettings.iAPSurfaceUsage;

    m_DX9ResizerCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_RESIZE_NN));
    m_DX9ResizerCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_RESIZER_BILIN));
    m_DX9ResizerCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_RESIZER_BIL_PS));
    m_DX9ResizerCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_RESIZER_BICUB1));
    m_DX9ResizerCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_RESIZER_BICUB2));
    m_DX9ResizerCtrl.AddString(ResStr(IDS_PPAGE_OUTPUT_RESIZER_BICUB3));
    m_iDX9Resizer           = renderersSettings.iDX9Resizer;

    m_fVMR9MixerMode        = renderersSettings.fVMR9MixerMode;
    m_fVMR9MixerYUV         = renderersSettings.fVMR9MixerYUV;
    m_fVMR9AlterativeVSync  = renderersSettings.m_RenderSettings.fVMR9AlterativeVSync;
    m_fD3DFullscreen        = s.fD3DFullscreen;

    int EVRBuffers[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30, 35, 40, 45, 50, 55, 60};
    CString EVRBuffer;
    for (size_t i = 0; i < _countof(EVRBuffers); i++) {
        EVRBuffer.Format(_T("%d"), EVRBuffers[i]);
        m_EVRBuffersCtrl.AddString(EVRBuffer);
    }
    m_iEvrBuffers.Format(L"%d", renderersSettings.iEvrBuffers);

    m_iAudioRendererTypeCtrl.SetRedraw(FALSE);
    m_fResetDevice = s.m_RenderersSettings.fResetDevice;
    m_AudioRendererDisplayNames.Add(_T(""));
    m_iAudioRendererTypeCtrl.AddString(_T("1: ") + ResStr(IDS_PPAGE_OUTPUT_SYS_DEF));
    m_iAudioRendererType = 0;

    int i = 2;
    CString Cbstr;

    BeginEnumSysDev(CLSID_AudioRendererCategory, pMoniker) {
        LPOLESTR olestr = NULL;
        if (FAILED(pMoniker->GetDisplayName(0, 0, &olestr))) {
            continue;
        }

        CStringW str(olestr);
        CoTaskMemFree(olestr);

        m_AudioRendererDisplayNames.Add(CString(str));

        CComPtr<IPropertyBag> pPB;
        if (SUCCEEDED(pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void**)&pPB))) {
            CComVariant var;
            pPB->Read(CComBSTR(_T("FriendlyName")), &var, NULL);

            CString fstr(var.bstrVal);

            var.Clear();
            if (SUCCEEDED(pPB->Read(CComBSTR(_T("FilterData")), &var, NULL))) {
                BSTR* pbstr;
                if (SUCCEEDED(SafeArrayAccessData(var.parray, (void**)&pbstr))) {
                    fstr.Format(_T("%s (%08x)"), CString(fstr), *((DWORD*)pbstr + 1));
                    SafeArrayUnaccessData(var.parray);
                }
            }
            Cbstr.Format(_T("%d: %s"), i, fstr);
        } else {
            Cbstr.Format(_T("%d: %s"), i, CString(str));
        }
        m_iAudioRendererTypeCtrl.AddString(Cbstr);

        if (s.strAudioRendererDisplayName == str && m_iAudioRendererType == 0) {
            m_iAudioRendererType = m_iAudioRendererTypeCtrl.GetCount() - 1;
        }
        i++;
    }
Esempio n. 29
0
FFHaaliVideo::FFHaaliVideo(const char *SourceFile, int Track,
	FFMS_Index &Index, int Threads, FFMS_Sources SourceMode)
: Res(FFSourceResources<FFMS_VideoSource>(this)), FFMS_VideoSource(SourceFile, Index, Track, Threads) {
	BitStreamFilter = NULL;

	pMMC = HaaliOpenFile(SourceFile, SourceMode);

	CComPtr<IEnumUnknown> pEU;
	if (!SUCCEEDED(pMMC->EnumTracks(&pEU)))
		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
			"Failed to enumerate tracks");

	CComPtr<IUnknown> pU;
	int CurrentTrack = -1;
	while (pEU->Next(1, &pU, NULL) == S_OK && ++CurrentTrack != Track) pU = NULL;
	CComQIPtr<IPropertyBag> pBag = pU;

	if (CurrentTrack != Track || !pBag)
		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
			"Failed to find track");

	HCodecContext = InitializeCodecContextFromHaaliInfo(pBag);
	CodecContext = HCodecContext;

	const AVCodec *Codec = NULL;
	std::swap(Codec, CodecContext->codec);
	if (avcodec_open2(CodecContext, Codec, NULL) < 0)
		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
			"Could not open video codec");

	CodecContext->thread_count = DecodingThreads;

	if (CodecContext->codec->id == FFMS_ID(H264) && SourceMode == FFMS_SOURCE_HAALIMPEG)
		BitStreamFilter = av_bitstream_filter_init("h264_mp4toannexb");

	Res.CloseCodec(true);

	// Always try to decode a frame to make sure all required parameters are known
	int64_t Dummy;
	DecodeNextFrame(&Dummy);

	VP.FPSDenominator = 1;
	VP.FPSNumerator = 30;

	// Calculate the average framerate
	if (Frames.size() >= 2) {
		double PTSDiff = (double)(Frames.back().PTS - Frames.front().PTS);
		VP.FPSDenominator = (unsigned int)(PTSDiff  / (double)1000 / (double)(Frames.size() - 1) + 0.5);
		VP.FPSNumerator = 1000000;
	}

	// Set the video properties from the codec context
	SetVideoProperties();

	// Output the already decoded frame so it isn't wasted
	OutputFrame(DecodeFrame);

	// Set AR variables
	CComVariant pV;

	USHORT Num = 0, Den = 0;

	pV.Clear();
	if (SUCCEEDED(pBag->Read(L"Video.DisplayWidth", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
		Num = pV.uiVal;
	pV.Clear();
	if (SUCCEEDED(pBag->Read(L"Video.DisplayHeight", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
		Den = pV.uiVal;

	if (Num && Den) {
		VP.SARNum = LocalFrame.EncodedHeight * Num;
		VP.SARDen = LocalFrame.EncodedWidth * Den;
	}
}
Esempio n. 30
0
HRESULT CTRiASMIObjectsCollection::CreateObject (
	VARIANT NameOrHandle, DWORD dwType, const CLSID *pClsId, ITRiASObjects **ppIObjs)
{
	_ASSERTE(NULL != pClsId);
	if (NULL == pClsId) 
		return E_POINTER;

// diverse Vorbereitungen treffen
WDispatch App;
WDispatch Parent;
WTRiASObjectsCollection BaseObjs;

	RETURN_FAILED_HRESULT(m_BaseUnk -> QueryInterface (BaseObjs.ppi()));

	RETURN_FAILED_HRESULT(BaseObjs -> get_Application (App.ppi()));		// für neue Objektklasse
	RETURN_FAILED_HRESULT(BaseObjs -> get_Parent(Parent.ppi()));

// ZugriffsHandle/Namen oder OKS aus NameOrHandle bestimmen
LONG lHandle = 0;
CComVariant v;
bool fHasName = false;
bool fHasOKS = false;
CComBSTR bstrApp, bstrOKS;

	if (VT_BSTR != V_VT(&NameOrHandle) && SUCCEEDED(v.ChangeType (VT_I4, &NameOrHandle)))
		lHandle = V_I4(&v);
	else if (SUCCEEDED(v.ChangeType(VT_BSTR, &NameOrHandle))) {
	// feststellen, ob es ein OKS ist, evtl. Namen isolieren
		if (StringIsOKS(V_BSTR(&v), CLEARED(&bstrOKS), CLEARED(&bstrApp))) {
			if (bstrOKS.Length() > 0)
				fHasOKS = true;
		} else 
			bstrApp = V_BSTR(&v);

		if (bstrApp.Length() > 0)
			fHasName = true;
	} else
		return E_INVALIDARG;

// Objektklasse aus Handle/Name/OKS erzeugen
HRESULT hr = S_OK;

	COM_TRY {
	WTRiASObjects Objs (*pClsId);		// zu liefernde Objektklasse erzeugen

		THROW_FAILED_HRESULT(Objs -> put_Parent (Parent));

#pragma TODO("Neue Objektklasse in Datenbank erzeugen.")

		if (fHasName) 	// S_FALSE heißt: Objekt existiert bereits
			RETURN_FAILED_HRESULT(Objs -> put_Name (bstrApp));
		if (fHasOKS)
			RETURN_FAILED_HRESULT(Objs -> put_OKS (bstrOKS));

	// wenn Objektklasse bereits zu dieser Menge von Objektklassen gehört, dann liefert _Add den Wert S_FALSE
		hr = BaseObjs -> _Add (Objs, VARIANT_TRUE);
		if (SUCCEEDED(hr) && NULL != ppIObjs)
			*ppIObjs = Objs.detach();			// evtl. neue/gefundene Objektklasse liefern

	} COM_CATCH;
	return hr;
}