Exemple #1
0
FFCodecContext InitializeCodecContextFromHaaliInfo(CComQIPtr<IPropertyBag> pBag) {
	CComVariant pV;
	if (FAILED(pBag->Read(L"Type", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
		return FFCodecContext();

	unsigned int TT = pV.uintVal;

	FFCodecContext CodecContext(avcodec_alloc_context3(NULL), DeleteHaaliCodecContext);

	unsigned int FourCC = 0;
	if (TT == TT_VIDEO) {
		pV.Clear();
		if (SUCCEEDED(pBag->Read(L"Video.PixelWidth", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
			CodecContext->coded_width = pV.uintVal;

		pV.Clear();
		if (SUCCEEDED(pBag->Read(L"Video.PixelHeight", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
			CodecContext->coded_height = pV.uintVal;

		pV.Clear();
		if (SUCCEEDED(pBag->Read(L"FOURCC", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
			FourCC = pV.uintVal;

		pV.Clear();
		if (SUCCEEDED(pBag->Read(L"CodecPrivate", &pV, NULL))) {
			CodecContext->extradata_size = vtSize(pV);
			CodecContext->extradata = static_cast<uint8_t*>(av_mallocz(CodecContext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE));
			vtCopy(pV, CodecContext->extradata);
		}
	}
	else if (TT == TT_AUDIO) {
		pV.Clear();
		if (SUCCEEDED(pBag->Read(L"CodecPrivate", &pV, NULL))) {
			CodecContext->extradata_size = vtSize(pV);
			CodecContext->extradata = static_cast<uint8_t*>(av_mallocz(CodecContext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE));
			vtCopy(pV, CodecContext->extradata);
		}

		pV.Clear();
		if (SUCCEEDED(pBag->Read(L"Audio.SamplingFreq", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
			CodecContext->sample_rate = pV.uintVal;

		pV.Clear();
		if (SUCCEEDED(pBag->Read(L"Audio.BitDepth", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
			CodecContext->bits_per_coded_sample = pV.uintVal;

		pV.Clear();
		if (SUCCEEDED(pBag->Read(L"Audio.Channels", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
			CodecContext->channels = pV.uintVal;
	}

	pV.Clear();
	if (SUCCEEDED(pBag->Read(L"CodecID", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_BSTR))) {
		char CodecStr[2048];
		wcstombs(CodecStr, pV.bstrVal, 2000);

		CodecContext->codec = avcodec_find_decoder(MatroskaToFFCodecID(CodecStr, CodecContext->extradata, FourCC, CodecContext->bits_per_coded_sample));
	}
	return CodecContext;
}
//-----------------------------------------------------------------------------------------------//
STDMETHODIMP CMyTrackPriceInfoWithNotify::SubscribeQuote(QuoteUpdateParams *Params)
{
	ATLTRACE(_T("CMyTrackPriceInfoWithNotify::SubscribeQuote\n"));
	CComVariant varParams;
	try
	{
		//		ResetEvent(m_hDisconnect);

		_bstr_t bstrSymbol;
		_bstr_t bstrExchange;
		GetParams(varParams,Params);
		bstrSymbol = Params->Symbol;
		if(Params->Exchange)
			bstrExchange = Params->Exchange;

		_Module.GetMyTrackCore ()->SubscribeQuote(static_cast<CBaseNotifier*>(this),
			Params->Type,
			(LPCSTR)bstrSymbol,
			(LPCSTR)bstrExchange,
			varParams);
	}
	catch (_com_error &err)
	{
		return eg_lib::utils::ComError2ErrInfo (err,this);
	}
	varParams.Clear ();
	return S_OK;
}
Exemple #3
0
void CBoxHttpServer::Close(void)
{
	CBoxTcpServer::Close();

	if(m_pSendThread)
	{
		QueueUserAPC(StopSendThread, m_pSendThread->m_hThread, (ULONG_PTR)this);

		while(m_pSendThread)
			Sleep(1);
	}

	CBoxObject<CBoxHttpHost> pHost;
	CComVariant var;
	int i;
	int count = m_pContents->get_Count();

	for(i = 0; i < count; i ++)
	{
		var.Clear();
		m_pContents->GetValue(i, var);
		if(var.vt == VT_DISPATCH)
		{
			pHost = var.pdispVal;
			if(pHost != NULL)
				pHost->OnEnd();
		}
	}
}
Exemple #4
0
void CBoxHttpHost::OnStart(void)
{
	if(m_bIsStart)return;
	m_bIsStart = TRUE;

	CSingleLock l(&m_cs, TRUE);

	CallEvent(L"OnApplicationStart", NULL, NULL, TRUE);

	CBoxObject<CBoxHttpHost> pHost;
	CComVariant var;
	int i;
	int count = m_pContents->get_Count();

	for(i = 0; i < count; i ++)
	{
		var.Clear();
		m_pContents->GetValue(i, var);
		if(var.vt == VT_DISPATCH)
		{
			pHost = var.pdispVal;
			if(pHost != NULL)
				pHost->OnStart();
		}
	}
}
Exemple #5
0
void CBoxHttpServer::OnSleepTimer(__int64 nNowTime)
{
    CBoxTcpServer::OnSleepTimer(nNowTime);

	if(m_nLastCheckTime != nNowTime)
	{
		m_nLastCheckTime = nNowTime;

		CBoxObject<CBoxHttpHost> pHost;
		CComVariant var;
		int i;
		int count = m_pContents->get_Count();

		for(i = 0; i < count; i ++)
		{
			var.Clear();
			m_pContents->GetValue(i, var);
			if(var.vt == VT_DISPATCH)
			{
				pHost = var.pdispVal;
				if(pHost != NULL)
					pHost->ClearSession(m_nLastCheckTime);
			}
		}
	}
}
STDMETHODIMP CTrackDataStructureProvider::RequestOptions(OptionParams *Params)
{
	CComVariant varParams;
	USES_CONVERSION;
	try
	{ 

		_OptionParams op;
		op.Init();
		op->UnderlyingSymbol = SysAllocString(Params->UnderlyingSymbol);
		op->Exchange = SysAllocString(Params->Exchange);
		op.CopyTo(varParams);

		RT_SYMBOL symbol;
		ZeroMemory(&symbol, sizeof(RT_SYMBOL)); 
		if(Params->UnderlyingSymbol)
			strncpy(symbol.name,W2A(Params->UnderlyingSymbol),10);

		if(Params->Exchange)
			strncpy(symbol.exchange, W2A(Params->Exchange),2);

		m_Client.RequestOptions(this, &symbol, varParams);
	}
	catch (_com_error &err)
	{
		return utils::ComError2ErrInfo (err,this);
	}
	varParams.Clear ();
	return S_OK;

}
/////////////////////////////////////////////////////////////////////////////
// CTrackDataStructureProvider
STDMETHODIMP CTrackDataStructureProvider::RequestStock(StockParams *Params)
{
	CComVariant varParams;
	USES_CONVERSION;
	try
	{

		RT_SYMBOL symbol;
		ZeroMemory(&symbol, sizeof(RT_SYMBOL)); 
		if(Params->Stock)
			strncpy(symbol.name,W2A(Params->Stock),10);

		if(Params->Exchange)
			strncpy(symbol.exchange, W2A(Params->Exchange),2);

		_StockParams op;
		op.Init();
		op->Stock = Params->Stock;
		op->Exchange = Params->Exchange;
		op.CopyTo(varParams);


		if(RT_ERR_OK == m_Client.RequestSymbol(this, &symbol, varParams))
		{
		}
	}
	catch (_com_error &err)
	{
		return utils::ComError2ErrInfo (err,this);
	}
	varParams.Clear ();
	return S_OK;
}
HRESULT CAzAppGroup::CopyVersion2Constructs(CAzAppGroup &srcAppGroup) {

    static unsigned int rgProperties[]={AZ_PROP_GROUP_BIZRULE,AZ_PROP_GROUP_BIZRULE_LANGUAGE,AZ_PROP_GROUP_BIZRULE_IMPORTED_PATH};

    CComVariant cVVar;

    HRESULT hr=S_OK;

    if (!CAzGlobalOptions::m_bVersionTwo)
        goto lDone;

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

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

        CAzLogging::Log(hr,_TEXT("Getting IAzApplicationGroup Property ID:"),COLE2T(srcAppGroup.getName()),rgProperties[i]);

        if (SUCCEEDED(hr) && (SysStringByteLen(cVVar.bstrVal))!=0) {

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

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

            cVVar.Clear();

        }

    }
lDone:
    return hr;
}
HRESULT CAzAppGroup::CopyLinks(CAzAppGroup &srcAppGroup) {

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

    CComVariant cVVar;

    HRESULT hr;

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

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

    if (SUCCEEDED(hr)) {

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

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

        cVVar.Clear();
    }

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

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

    if (SUCCEEDED(hr)) {

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

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

        cVVar.Clear();
    }

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

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

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

    return hr;
}
void lvDCOMInterface::waitForLabviewBoolean(BSTR vi_name, BSTR control_name, bool value)
{
	CComVariant v;
	bool done = false;
	while(!done)
	{
		getLabviewValue(vi_name, control_name, &v);
		if ( v.ChangeType(VT_BOOL) == S_OK )
		{
			done = ( v.boolVal == (value ? VARIANT_TRUE : VARIANT_FALSE) );
			v.Clear();
		}
		epicsThreadSleep(0.1);
	}	
}	
Exemple #11
0
WMIProperty::WMIProperty(const BSTR & name, const VARIANT & value, const CIMTYPE type)
{
	CComBSTR bsName = name;
	CComVariant vValue = value;

	// build the property
	BSTR tmpBstr = (BSTR)bsName.Copy();
	String s(_bstr_t(tmpBstr, FALSE));
	SysFreeString(tmpBstr);
    *this = CIMProperty(CIMName(s), WMIValue(vValue, type));
    // old way -- memory leak?:
	// *this = CIMProperty(WMIString(bsName), WMIValue(vValue, type));

	vValue.Clear();
}
STDMETHODIMP CAvatarProfileObject::get_Keys(IPropertyList** ppKeyList)
{
	HRESULT hr = S_OK;
	IAvatarProfileData* pProfileData = NULL;
	CComBSTR curStr;
	VARIANT_BOOL bDone;
	CComVariant varVal;
	long cKeys = 0;
	
	if (ppKeyList == NULL)
		return E_POINTER;

	*ppKeyList = NULL;

	if (m_pKeys == NULL)
	{
		VWTRACE(m_pWorld, "VWPROPERTY", VWT_ERROR, "CAvatarProfileObject::get_Keys: invalid key map\n");
		hr = VWAVATARPROFILE_E_INVALIDKEYMAP;
		goto ERROR_ENCOUNTERED;
	}

	hr = CreatePropertyList(m_pWorld, ppKeyList);
	if (FAILED(hr) || (!*ppKeyList))
		goto ERROR_ENCOUNTERED;

	// map over the key list, collecting the names of valid keys
	m_pKeys->FirstItem(&curStr.m_str, &varVal, &bDone);

	while (bDone == VARIANT_FALSE)
	{
		hr = m_pKeys->get_ObjectProperty(curStr, (IObjectProperty **)&pProfileData);
		if (SUCCEEDED(hr) && pProfileData)
		{
			if (IsKeyReadable(pProfileData))
				(*ppKeyList)->AddString(curStr);

			SAFERELEASE(pProfileData);
		}

		curStr.Empty();
		varVal.Clear();

		m_pKeys->NextItem(&curStr.m_str, &varVal, &bDone);
	}
		
ERROR_ENCOUNTERED:
	return hr;
}
Exemple #13
0
/////////////////////////////////////////////////////////////////////////////
// WMIClassProvider::createQualifier  creates a qualifiers 
//                                      
/////////////////////////////////////////////////////////////////////////////
void WMIClassProvider::createQualifier (const WMIQualifier &qualifier, 
                                        IWbemQualifierSet *pQual)
{
    HRESULT hr;
    
    PEG_METHOD_ENTER(TRC_WMIPROVIDER, "WmiClassProvider::createQualifier()");

    String sName = qualifier.getName().getString(); 
    CComBSTR bs = sName.getCString();
    WMIValue value(qualifier.getValue());
    WMIFlavor flavor(qualifier.getFlavor());
    
    CComVariant v;
    value.getAsVariant(&v);

    // key is created using a special call to wmi
    //if (!stricmp("key", ))
    if (String::equalNoCase("key", sName))
    {
        hr = pQual->Put(bs, &v, NULL);
    }
    else
    {
        hr = pQual->Put(bs, &v, flavor.getAsWMIValue());
    }
    v.Clear();
    bs.Empty();

    if (FAILED(hr))
    {
        CMyString msg;
        msg.Format("It is not possible to add the qualifier [%s] to "
            "the object! Error: 0x%X", 255, sName.getCString(), hr);
        
        PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL1, 
            "WmiClassProvider::createQualifier() - %s", (LPCTSTR)msg));

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

    PEG_METHOD_EXIT();

    return;
}
STDMETHODIMP CLogoMarkerSymbol::Save(IVariantStream *Stream)
{
	CComVariant vSave;
	HRESULT hr;
	
	//persist ISymbol properties 
	vSave = (long)m_lROP2;
	if (FAILED(hr = Stream->Write(vSave))) return hr;

	//persist IMarkerSymbol properties
	vSave = m_dSize;
	if (FAILED(hr = Stream->Write(vSave))) return hr;
	vSave = m_dXOffset;
	if (FAILED(hr = Stream->Write(vSave))) return hr;
	vSave = m_dYOffset;
	if (FAILED(hr = Stream->Write(vSave))) return hr;
	vSave = m_dAngle;
	if (FAILED(hr = Stream->Write(vSave))) return hr;
	
	//persist ISymbolRotation properties
	// CComVariant does not have assignment operator
	// for VARIANT_BOOL, so do this as for the raw datatype
	vSave.Clear();
	vSave.vt = VT_BOOL;
	vSave.boolVal = m_bRotWithTrans;
	if (FAILED(hr = Stream->Write(vSave))) return hr;

	//persist IMapLevel properties
	vSave = m_lMapLevel;
	if (FAILED(hr = Stream->Write(vSave))) return hr;

	//persist custom properties
	vSave = (IUnknown*)m_ipTopColor;
	if (FAILED(hr = Stream->Write(vSave))) return hr;
	vSave = (IUnknown*)m_ipLeftColor;
	if (FAILED(hr = Stream->Write(vSave))) return hr;
	vSave = (IUnknown*)m_ipRightColor;
	if (FAILED(hr = Stream->Write(vSave))) return hr;
	vSave = (IUnknown*)m_ipBorderColor;
	if (FAILED(hr = Stream->Write(vSave))) return hr;

	return S_OK;
}
Exemple #15
0
void CBoxHttpServer::Start(void)
{
	CBoxObject<CBoxHttpHost> pHost;
	CComVariant var;
	int i;
	int count = m_pContents->get_Count();

	for(i = 0; i < count; i ++)
	{
		var.Clear();
		m_pContents->GetValue(i, var);
		if(var.vt == VT_DISPATCH)
		{
			pHost = var.pdispVal;
			if(pHost != NULL)
				pHost->OnStart();
		}
	}

	CBoxTcpServer::Start();
}
Exemple #16
0
	void DensoRobot::Start()
	{
		/* Start the motor */
		CComVariant pVal; // probably empty
		hr = pRobot->Execute(CComBSTR(L"Motor"), CComVariant(L"1"), &pVal);
		if(FAILED(hr)) throw exception("Failed to start the robot motor!");

		/* Set the external robot speed TO DO*/ 
		CComVariant parameters; 
        parameters.vt = VT_ARRAY | VT_VARIANT; 

        SAFEARRAYBOUND bounds[1]; 
        bounds[0].lLbound = 0; 
        bounds[0].cElements = 3; 
        parameters.parray = SafeArrayCreate(VT_VARIANT, 1, bounds); 

        CComVariant varSpeed; 
        varSpeed.vt = VT_R4; 
        varSpeed.fltVal = (float)this->robotSpeed; 

        CComVariant varAcceleration; 
        varAcceleration.vt = VT_R4; 
        varAcceleration.fltVal = (float)(this->robotSpeed*this->robotSpeed/100); 

        CComVariant varDeceleration; 
		varDeceleration.vt = VT_R4; 
        varDeceleration.fltVal = (float)(this->robotSpeed*this->robotSpeed/100); 

		long index = 0; 
        SafeArrayPutElement(parameters.parray, &index, &varSpeed); 
        index = 1; 
		SafeArrayPutElement(parameters.parray, &index, &varAcceleration); 
        index = 2; 
        SafeArrayPutElement(parameters.parray, &index, &varDeceleration); 

        CComVariant vntDummy; 
        hr = pRobot->Execute(CComBSTR(L"ExtSpeed"), parameters, &vntDummy); 
		if(FAILED(hr)) throw exception("Failed to set the external robot speed!");
        parameters.Clear(); 
	}
Exemple #17
0
STDMETHODIMP CPictHolder::GetTagValue(long tag, VARIANT* pValue)
{
    if( !pValue )
        return E_POINTER;
    if( !m_pPicture )
        return E_FAIL;
    if( !m_pPicture )
        return E_FAIL;
    HRESULT	hr = E_FAIL;
    try {
        TAG	t;
        CComVariant	v;
        v.Clear();
        m_pPicture->GetTag( (PICT_PROPERTY)tag, t );
        switch( t.Type() ) {
        case _DOUBLE :
            v = t.dVal();
            break;
        case _LONG :
            v = t.slVal();
            break;
        case _SLONG :
            v = (long) t.ulVal();
            break;
        case _SSHORT :
            v = t.ssVal();
            break;
        case _ASCII :
            v = t.strVal();
            break;
        }
        if( VT_EMPTY != v.vt ) {
            *pValue = v;
            hr = S_OK;
        }
    } catch(...) {
        hr = E_UNEXPECTED;
    }
    return hr;
}
Exemple #18
0
void CBoxHttpHost::ClearSession(__int64 nNowTime)
{
	CSingleLock l(&m_cs, TRUE);
	CBoxHttpSession* pSession;

	m_nNowTime = nNowTime;
	nNowTime -= (__int64)600000000 * m_nSessionTimeout;

	while((pSession = m_cacheSessions.GetLast()) != NULL && pSession->m_tmLastTime < nNowTime)
		if(pSession->m_dwRef > 1)
		{
			pSession->m_tmLastTime = m_nNowTime;
			m_cacheSessions.Update(pSession);
		}else
		{
			pSession->ExternalAddRef();
			m_cacheSessions.Remove(pSession);
			CallEvent(L"OnSessionEnd", NULL, pSession);
			pSession->m_pContents->RemoveAll();
			pSession->ExternalRelease();
		}

	CBoxObject<CBoxHttpHost> pHost;
	CComVariant var;
	int i;
	int count = m_pContents->get_Count();

	for(i = 0; i < count; i ++)
	{
		var.Clear();
		m_pContents->GetValue(i, var);
		if(var.vt == VT_DISPATCH)
		{
			pHost = var.pdispVal;
			if(pHost != NULL)
				pHost->ClearSession(m_nNowTime);
		}
	}
}
Exemple #19
0
void CBoxHttpHost::OnEnd(void)
{
	if(!m_bIsStart)return;
	m_bIsStart = FALSE;

	CSingleLock l(&m_cs, TRUE);

	CBoxObject<CBoxHttpHost> pHost;
	CComVariant var;
	int i;
	int count = m_pContents->get_Count();

	for(i = 0; i < count; i ++)
	{
		var.Clear();
		m_pContents->GetValue(i, var);
		if(var.vt == VT_DISPATCH)
		{
			pHost = var.pdispVal;
			if(pHost != NULL)
				pHost->OnEnd();
		}
	}

	CBoxHttpSession* pSession;

	while((pSession = m_cacheSessions.GetLast()) != NULL)
	{
		pSession->ExternalAddRef();
		m_cacheSessions.Remove(pSession);
		CallEvent(L"OnSessionEnd", NULL, pSession);
		pSession->m_pContents->RemoveAll();
		pSession->ExternalRelease();
	}

	CallEvent(L"OnApplicationEnd", NULL, NULL);
}
Exemple #20
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);
}
Exemple #21
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();    
    }
}
/////////////////////////////////////////////////////////////////////////////
// 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()
/*++

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;
}
Exemple #24
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;
}
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;
}
Exemple #26
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;
}
Exemple #27
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;
	}
}
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;
}
Exemple #29
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;
}
Exemple #30
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;
}