Пример #1
0
STDMETHODIMP CBDictionary::get_Keys(VARIANT *pKeysArray)
{
	CComSafeArray<VARIANT> bstrArray;
	VARIANT* pVar;
	HRESULT hr;

	m_cs.Enter();

	hr = bstrArray.Create((ULONG)m_posArray.GetCount());
	if(FAILED(hr))
	{
		m_cs.Leave();
		return hr;
	}

	pVar = (VARIANT*)bstrArray.m_psa->pvData;

	for(int i = 0; i < (int)m_posArray.GetCount(); i ++)
	{
		hr = VariantCopy(&pVar[i], (VARIANT*)&m_posArray[i]->m_key);
		if(FAILED(hr))
		{
			m_cs.Leave();
			bstrArray.Destroy();
			return hr;
		}
	}

	m_cs.Leave();

	pKeysArray->vt = VT_ARRAY | VT_VARIANT;
	pKeysArray->parray = bstrArray.Detach();

	return S_OK;
}
Пример #2
0
STDMETHODIMP CDlrComServer::GetIntArray(SAFEARRAY **ppsaRetVal)
{
    CComSafeArray<INT>      csaData;
    void HUGEP              *pvData = NULL;
    HRESULT hr = S_OK;

    int rgData [] = { 1, 2, 3, 4, 5 };

    hr = csaData.Create(5, 0);
    if (FAILED(hr)) 
        goto Error;

    hr = SafeArrayAccessData((LPSAFEARRAY)csaData, (void HUGEP **)&pvData);
    if (FAILED(hr))
        goto Error;

    memcpy((void*)pvData, rgData, sizeof(rgData));

    hr = SafeArrayUnaccessData((LPSAFEARRAY)csaData);
    if (FAILED(hr))
        goto Error;

    *ppsaRetVal = csaData.Detach();

Error:

    return hr;
}
Пример #3
0
STDMETHODIMP CXRecords::GetRows(VARIANT key, VARIANT* pVal)
{
	if(!m_pFields)return SetErrorInfo(s_errInit);

	CComSafeArray<VARIANT> bstrArray;
	VARIANT* pVar;
	HRESULT hr;
	int i = 0;
	int pos;
	int count = m_listRecords->GetCount();

	pos = m_pFields->FindField(key);
	if(pos < 0 || pos >= (int)m_pFields->GetCount())
		return DISP_E_BADINDEX;

	hr = bstrArray.Create(count);
	if(FAILED(hr))return hr;

	pVar = (VARIANT*)bstrArray.m_psa->pvData;

	for(i = 0; i < count; i ++)
	{
		hr = VariantCopy(&pVar[i], (VARIANT*)&m_listRecords->GetValue(i)->m_arrayVariant[pos]);
		if(FAILED(hr))
		{
			bstrArray.Destroy();
			return hr;
		}
	}

	pVal->vt = VT_ARRAY | VT_VARIANT;
	pVal->parray = bstrArray.Detach();

	return S_OK;
}
Пример #4
0
STDMETHODIMP CDlrComServer::GetByteArray(SAFEARRAY **ppsaRetVal)
{
    CComBSTR cbstrTestData(L"GetByteArrayTestData");
    CComSafeArray<BYTE>     csaData;
    void HUGEP              *pvData = NULL;
    DWORD                   cbData;
    HRESULT hr = S_OK;

    // create a stream of bytes encoded as UNICODE text
    cbData = SysStringByteLen(cbstrTestData.m_str);

    hr = csaData.Create(cbData, 0);
    if (FAILED(hr)) 
        goto Error;

    hr = SafeArrayAccessData((LPSAFEARRAY)csaData, (void HUGEP **)&pvData);
    if (FAILED(hr))
        goto Error;

    memcpy((void*)pvData, cbstrTestData.m_str, cbData);

    hr = SafeArrayUnaccessData((LPSAFEARRAY)csaData);
    if (FAILED(hr))
        goto Error;

    if (FAILED(hr))
        goto Error;

    *ppsaRetVal = csaData.Detach();

Error:

    return hr;
}
Пример #5
0
	HRESULT GetAssemblyFromAppDomain(_AppDomain* appDomain, const wchar_t* assemblyName, _Assembly **assembly)
	{
		SAFEARRAY* safearray;
		CComSafeArray<IUnknown*> assemblies;

		CHECKCOM(appDomain->GetAssemblies(&safearray));
		assemblies.Attach(safearray);
		for (int i = 0, n = assemblies.GetCount(); i < n; i++)
		{
			CComPtr<_Assembly> a;

			a = assemblies[i];
			if (a == nullptr)
				continue;
			CComBSTR assemblyFullName;
			CHECKCOM(a->get_FullName(&assemblyFullName));
			if (assemblyFullName != nullptr && _wcsnicmp(assemblyFullName, assemblyName, wcslen(assemblyName)) == 0)
			{
				*assembly = a.Detach();
				return S_OK;
			}
		}

		return E_FAIL;
	}
Пример #6
0
ITunesEventInterface::ITunesIdSet
ITunesComEventSink::getIdsFromSafeArray( long index, 
                                         CComSafeArray<VARIANT>& array )
{
    VARIANT elem;
    LONG idx2d[2];

    idx2d[0] = index;
    idx2d[1] = 0;
    array.MultiDimGetAt( idx2d, elem );
    long sourceId = elem.lVal;

    idx2d[1] = 1;
    array.MultiDimGetAt( idx2d, elem );
    long playlistId = elem.lVal;

    idx2d[1] = 2;
    array.MultiDimGetAt( idx2d, elem );
    long trackId = elem.lVal;

    idx2d[1] = 3;
    array.MultiDimGetAt( idx2d, elem );
    long dbId = elem.lVal;

    ITunesEventInterface::ITunesIdSet ids = { sourceId, playlistId, trackId, dbId };
    return ids;
}
Пример #7
0
void CRegionDlg::OnBnClickedSelect()
{
    UpdateData();

    ShowWindow(SW_HIDE);

    CRect rcCapture;
    CComPtr<ITSelectionInfo> pSelInfo;
	CComSafeArray<VARIANT, VT_VARIANT> arSafePoints;
    int nCount = 0;
    LONG hWnd = NULL;
    VARIANT points;

    if (!theApp.Select(tsSelectionRectangle, pSelInfo))
	{
        goto Exit;
	}

    // Capture region
    hWnd = pSelInfo->WindowHandle;
    pSelInfo->get_Points(&points);

	// Ttransform safe arry points
	arSafePoints.CopyFrom(points.parray);
	nCount = (int)arSafePoints.GetCount();
    ATLASSERT(2 == nCount);
    if (2 != nCount)
	{
        goto Exit;
	}

    rcCapture.SetRect(GET_X_LPARAM(arSafePoints[0].lVal), GET_Y_LPARAM(arSafePoints[0].lVal),
                      GET_X_LPARAM(arSafePoints[1].lVal), GET_Y_LPARAM(arSafePoints[1].lVal));

    // Fill the values
    m_strWindowName = theApp.GetWindowText((HWND)(LONG_PTR)hWnd);
    m_strWindowHandle.Format(_T("%X"), hWnd);

    m_nX = rcCapture.left;
    m_nY = rcCapture.top;

    m_nWidth  = rcCapture.Width();
    m_nHeight = rcCapture.Height();

    // Capture
    DoCapture(hWnd, rcCapture);

    UpdateData(FALSE);

Exit:
    if (m_nFullHeight > 0)
    {
        //restore the window
        theApp.RestoreWindow(this, m_nFullHeight);
        m_nFullHeight = 0;
    }

    ShowWindow(SW_SHOW);
}
HRESULT RegisterWithGDEventFramework() {
  CComPtr<IGoogleDesktopRegistrar> registrar;
  HRESULT hr = registrar.CoCreateInstance(L"GoogleDesktop.Registrar");

  if (SUCCEEDED(hr)) {
    CComBSTR our_guid(CONSOLE_PLUGIN_GUID);

    WCHAR icon_path[_MAX_PATH + 1] = {0};
    ATLVERIFY(::GetModuleFileNameW(NULL, icon_path, _MAX_PATH - 2) != 0);
    SafeStrCat(icon_path, L"@0", _MAX_PATH+1);

    CComSafeArray<VARIANT> description;
    ATLVERIFY(SUCCEEDED(description.Create(8)));
    VARIANT* props = reinterpret_cast<VARIANT*>(description.m_psa->pvData);

    for (DWORD i = 0; i < description.GetCount(); ++i) {
      props[i].vt = VT_BSTR;
    }

    props[0].bstrVal = ::SysAllocString(L"Title");
    props[1].bstrVal = ::SysAllocString(L"Console Events");
    props[2].bstrVal = ::SysAllocString(L"Description");
    props[3].bstrVal = ::SysAllocString(L"Outputs events from Google Desktop to the console");
    props[4].bstrVal = ::SysAllocString(L"Icon");
    props[5].bstrVal = ::SysAllocString(icon_path);
    props[6].bstrVal = ::SysAllocString(L"Homepage");
    props[7].bstrVal = ::SysAllocString(L"http://desktop.google.com");

    VARIANT desc;
    desc.vt = VT_ARRAY | VT_VARIANT;
    desc.parray = description;

    hr = registrar->StartComponentRegistration(our_guid, desc);

    if (SUCCEEDED(hr)) {
      CComPtr<IUnknown> unknown;
      hr = registrar->GetRegistrationInterface(CComBSTR(L"GoogleDesktop.EventRegistration"),
                                               &unknown);
      ATLASSERT(SUCCEEDED(hr));

      CComQIPtr<IGoogleDesktopRegisterEventPlugin> event_registration(unknown);
      if (event_registration != NULL) {
        long cookie = 0;
        hr = event_registration->RegisterPlugin(our_guid, &cookie);
        if (SUCCEEDED(hr)) {
          hr = registrar->FinishComponentRegistration();

          if (SUCCEEDED(hr)) {
            hr = StoreRegistrationCookie(cookie);
          }
        }
      }
    }
  }

  return hr;
}
void displayCCOMBSTRFiles(CComSafeArray<BSTR> fileSet)
{

	std::wcout << "Displaying Files Generated from the C++ Interface from COM OBJECT" << std::endl;

	for (ULONG i = 0; i < fileSet.GetCount(); i++)
	{
		std::cout << "Qualified File # " <<i<<" : "<< convertBSTR2stdSTR(fileSet.GetAt(i)) << "\n";
	}

}
CComSafeArray<BSTR> convertVector2CCOMSafeArray(Result x)
{
\
	CComSafeArray<BSTR> result;

	for (std::string inst : x)
	{
		result.Add(convertstdSTR2BSTR(inst));
	}
	return result;

}
// This is an example of an exported function.
NATIVELIBRARYCONSUMER_API int STDAPICALLTYPE fnNativeLibraryConsumer(SAFEARRAY** retval)
{
	//sample of returning array from C++
	CComSafeArray<VARIANT>* arr = new CComSafeArray<VARIANT>(2);	
	VARIANT var;
	var.vt= VT_INT;
	var.intVal = 123;
	arr->SetAt(0,var);
	arr->SetAt(1,var);

	
	*retval = *(arr->GetSafeArrayPtr());
	uses = new CNativeLibrary();
	return 42;
}
Пример #12
0
STDMETHODIMP CDlrComServer::GetObjArray(SAFEARRAY **ppsaRetVal)
{
    CComSafeArray<LPUNKNOWN>      csaData;
    void HUGEP              *pvData = NULL;
    IUnknown*                     punkThis = NULL;
    IUnknown*                     punkOther = NULL;
    void* rgData[] = { 0, 0 };
    HRESULT hr = S_OK;

    hr = csaData.Create(2, 0);
    if (FAILED(hr)) 
        goto Error;

    hr = SafeArrayAccessData((LPSAFEARRAY)csaData, (void HUGEP **)&pvData);
    if (FAILED(hr))
        goto Error;

    hr = this->QueryInterface(IID_IUnknown, (void**)&punkThis);
    if (FAILED(hr))
        goto Error;

    hr = CoCreateInstance(CLSID_DlrComServer, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void**)&punkOther);
    if (FAILED(hr))
        goto Error;

    rgData[0] = punkThis;
    rgData[1] = punkOther;

    memcpy((void*)pvData, rgData, sizeof(rgData));

    hr = SafeArrayUnaccessData((LPSAFEARRAY)csaData);
    if (FAILED(hr))
        goto Error;

    punkThis = 0;
    punkOther = 0;

    *ppsaRetVal = csaData.Detach();

Error:
    if (punkThis)
        punkThis->Release();

    if (punkOther)
        punkOther->Release();

    return hr;
}
Пример #13
0
/**
 * Output = Map of topic id and field data  -  Map to be deleted by caller
 */
std::map<long,CComVariant>* RTDClient::readNewData(){    
    
    SAFEARRAY  *data_sa;
    long        topic_count = 0;
    HRESULT     hr          = comObjectScripRTD->RefreshData( &topic_count, &data_sa );      
                                                                 // Pass Address of SAFEARRAY pointer so that we get pointer to 2D safearray
    if( FAILED(hr) ){                                            // Output Data has to be deleted by client
        std::cout << "RefreshData COM failure." << " - hr - " << hr <<   std::endl;    
        return 0;
    }
    CComSafeArray<VARIANT>  data;                                // Passing data_sa as Constructor input will copy it, but we need to destroy it after use
    data.Attach( data_sa );                                      // So attach instead and let CComSafeArray handle it
    

    ULONG  row_count = data.GetCount(1);                         // No of Rows = 2nd Dimension Count
    if( row_count == 0) return 0 ;
        
    std::map<long,CComVariant> *output = new std::map<long,CComVariant>;    // Map: Topicid, Field Data
         
    long index[2];
    for( ULONG i=0 ; i<row_count; i++  ){
        
        index[0] = 0;                                            // 0,x - Topic ids.   1,x - Data
        index[1] = i;
        CComVariant topic_id_var;
        data.MultiDimGetAt( index, topic_id_var);         
        long topic_id = (long)MiscUtil::getLong( topic_id_var );
        
        index[0] = 1;
        index[1] = i;
        CComVariant topic_data_var;
        data.MultiDimGetAt( index, topic_data_var); 
                
        
        if( output->count(topic_id) != 0  && (*output)[topic_id] != topic_data_var  ){            
            std::cout << "Duplicate:";  MiscUtil::printVariant((*output)[topic_id]); std::cout << "-";  MiscUtil::printVariant(topic_data_var);
            std::cout << std::endl;
            //abort();                                           // If exists - we can have multiple topic values in same call => use vector
        }
        
        (*output)[topic_id] = topic_data_var;   
    } 

    return output;
}
Пример #14
0
void printHistory(CComVariant history) {
	if (history.vt == (VT_ARRAY | VT_I2)) {
		printf("Ping code history for server: ");

		CComSafeArray<SHORT> codes = history.parray;

		int codeCount = codes.GetCount();
		for (int i = 0; i < codeCount; i++) {
			printf("%hd ", codes[i]);
		}
		printf("\n");

		codes.Destroy();
	}
	else {
		printf("Incorrect variant type\n");
	}
}
Пример #15
0
STDMETHODIMP CotProjTransform::Transform(LONG count, SAFEARRAY** inX, SAFEARRAY** inY, SAFEARRAY** outX, SAFEARRAY** outY)
{
	if(!CheckPointer())
	{
		return E_FAIL;
	}

    double *dxs =new double[count];
	double *dys =new double[count];

	CComSafeArray<double> safeInx;
	CComSafeArray<double> safeIny;

	safeInx.Attach(*inX);
	safeIny.Attach(*inY);

	for(long i=0;i<count;i++)
	{
		dxs[i] =safeInx[i];
		dys[i] =safeIny[i];

	}
	safeInx.Detach();
	safeIny.Detach();

	//转换
    (*m_ppTrans)->Transform(count,dxs,dys);

	//将转换结果放到输出数组中
	safeInx.Attach(*outX);
	safeIny.Attach(*outY);

	for(long i=0;i<count;i++)
	{
		safeInx[i] = dxs[i] ;
		safeIny[i] = dys[i] ;

	}
	safeInx.Detach();
	safeIny.Detach();


	return S_OK;
}
Пример #16
0
LRESULT IGToolCutterSquare::OnMouseUp (UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	CComSafeArray <int> spSafeArrayPts;
	spSafeArrayPts.Add (m_xPos1);
	spSafeArrayPts.Add (m_yPos1);
	m_xPos1 = GET_X_LPARAM(lParam); 
	m_yPos1 = GET_Y_LPARAM(lParam); 
	m_pFrame->ConvertCoordFrameToPixel ((LONG*)&m_xPos1, (LONG*)&m_yPos1);
	spSafeArrayPts.Add (m_xPos1);
	spSafeArrayPts.Add (m_yPos1);
	CComVariant spVarArray (spSafeArrayPts);
	int nTypeSelection = IGSELECTION_REPLACE;
	if (::GetKeyState (VK_SHIFT) < 0)
		nTypeSelection = IGSELECTION_ADD;
	else if (::GetKeyState (VK_CONTROL) < 0)
		nTypeSelection = IGSELECTION_REMOVE;
	m_pFrame->ManageSelection (IGSELECTION_SQUARE | nTypeSelection, &spVarArray);
	return 0L;
}
Пример #17
0
STDMETHODIMP CLDAPQuery::explodeDn(
	/* [in] */ BSTR str,
	/* [in] */ ULONG notypes,
	/* [retval][out] */ SAFEARRAY **result)
{
	PTCHAR *vals = ldap_explode_dn(CComBSTR(str), notypes);
	m_errorCode = LdapGetLastError();
	if(vals)
	{
		CComSafeArray<VARIANT> dnValues;
		for(LONG i = 0L; vals[i]!=NULL; i++)
		{
			dnValues.Add(CComVariant(vals[i]));
		}
		ldap_value_free(vals);
		*result = dnValues.Detach();
	}
	return S_OK;
}
Пример #18
0
STDMETHODIMP CTextSearch::GetResults(SAFEARRAY ** files)
{
	// TODO: Add your implementation code here
	Search searchService;
	std::string path = searchService.ConvertBSTRToMBS(_searchPath);
	//std::string keyword = searchService.ConvertBSTRToMBS(_searchKeyword);
	std::vector<std::string> keywords;

	for (int i = 0; i < (int)_searchKeywords.GetCount(); ++i)
		keywords.push_back(searchService.ConvertBSTRToMBS(_searchKeywords[i].Copy()));

	std::vector<std::string> results = searchService.StartTextSearch(keywords, path, _searchAll);
	CComSafeArray<BSTR> temp;
	
	for (auto result : results)
		temp.Add(CComBSTR(result.c_str()));

	*files = temp.Detach();

	return S_OK;
}
void lvDCOMInterface::getLabviewValue(const char* param, T* value, size_t nElements, size_t& nIn)
{
	if (value == NULL)
	{
		throw std::runtime_error("getLabviewValue failed (NULL)");
	}
	if (param == NULL || *param == '\0')
	{
		throw std::runtime_error("getLabviewValue: param is NULL");
	}
	CComVariant v;
	char vi_name_xpath[MAX_PATH_LEN], control_name_xpath[MAX_PATH_LEN];
	_snprintf(vi_name_xpath, sizeof(vi_name_xpath), "/lvinput/section[@name='%s']/vi/@path", m_configSection.c_str());
	_snprintf(control_name_xpath, sizeof(control_name_xpath), "/lvinput/section[@name='%s']/vi/param[@name='%s']/read/@target", m_configSection.c_str(), param);
	CComBSTR vi_name(doPath(vi_name_xpath).c_str());
	CComBSTR control_name(doXPATH(control_name_xpath).c_str());
	if (vi_name.Length() == 0 || control_name.Length() == 0)
	{
		throw std::runtime_error("getLabviewValue: vi or control is NULL");
	}
	getLabviewValue(vi_name, control_name, &v);
	if ( v.vt != (VT_ARRAY | CVarTypeInfo<T>::VT) )
	{
		throw std::runtime_error("getLabviewValue failed (type mismatch)");
	}
	CComSafeArray<T> sa;
	sa.Attach(v.parray);
	nIn = ( sa.GetCount() > nElements ? nElements : sa.GetCount() );
	for(LONG i=0; i<nIn; ++i)
	{
		value[i] = sa.GetAt(i);
	}
	sa.Detach();
}
Пример #20
0
STDMETHODIMP CBQueue::get_Items(VARIANT *pItemsArray)
{
	CComSafeArray<VARIANT> bstrArray;
	VARIANT* pVar;
	HRESULT hr;
	POSITION pos;
	int i;

	m_cs.Enter();

	hr = bstrArray.Create((ULONG)m_listItems.GetCount());
	if(FAILED(hr))
	{
		m_cs.Leave();
		return hr;
	}

	pVar = (VARIANT*)bstrArray.m_psa->pvData;

	pos = m_listItems.GetHeadPosition();
	i = 0;

	while(pos)
	{
		hr = VariantCopy(&pVar[i ++], &m_listItems.GetNext(pos));
		if(FAILED(hr))
		{
			m_cs.Leave();
			return hr;
		}
	}

	m_cs.Leave();

	pItemsArray->vt = VT_ARRAY | VT_VARIANT;
	pItemsArray->parray = bstrArray.Detach();

	return S_OK;
}
Пример #21
0
/*
 * Converts the specified (reply) string into a Variant value.
 * If the string contains tab characters ('\t), the string is
 * considered to contain an array of values.
 */
CComVariant CMELCommand::MakeVariant(const CAtlString& strText)
{
	int tabCount = 0;
	int tabPos = 0;
	while (tabPos < strText.GetLength()) {
		tabPos = strText.Find(L'\t', tabPos);
		if (tabPos < 0)
			break;
		++tabCount;
		++tabPos;
	}
	if (!tabCount) {
		return MakeVariantNotArray(strText);
	}
	CComSafeArray<VARIANT> safeArray;
	safeArray.Create(tabCount + 1);
	int curPos = 0;
	int index = 0;
	tabPos = strText.Find(L'\t');
	for (;;) {
		CAtlString strElement;
		if (tabPos > curPos) {
			strElement = strText.Mid(curPos, tabPos - curPos).Trim();
		}
		safeArray[index++] = MakeVariantNotArray(strElement);
		curPos = tabPos + 1;
		if (curPos == strText.GetLength()) {
			safeArray[index] = CComVariant(L"");
			break;
		}
		tabPos = strText.Find(L'\t', curPos);
		if (tabPos < 0) {
			safeArray[index] = MakeVariant(strText.Mid(curPos).Trim());
			break;
		}
	}
	return CComVariant(safeArray);
}
Пример #22
0
//----------------------------------------------------------------------------
//
HRESULT CAnchoRuntime::fireOnBeforeRequest(const std::wstring &aUrl, const std::wstring &aMethod, const CAnchoRuntime::FrameRecord *aFrameRecord, /*out*/ BeforeRequestInfo &aOutInfo)
{
  CComPtr<ComSimpleJSObject> info;
  IF_FAILED_RET(SimpleJSObject::createInstance(info));
  fillRequestInfo(*info, aUrl, aMethod, aFrameRecord);

  CComPtr<ComSimpleJSArray> argArray;
  IF_FAILED_RET(SimpleJSArray::createInstance(argArray));
  argArray->push_back(CComVariant(info.p));

  CComVariant result;
  m_pAnchoService->invokeEventObjectInAllExtensions(CComBSTR(L"webRequest.onBeforeRequest"), argArray.p, &result);
  if (result.vt & VT_ARRAY) {
    CComSafeArray<VARIANT> arr;
    arr.Attach(result.parray);
    //contained data already managed by CComSafeArray
    VARIANT tmp = {0}; HRESULT hr = result.Detach(&tmp);
    BEGIN_TRY_BLOCK
      aOutInfo.cancel = false;
      for (ULONG i = 0; i < arr.GetCount(); ++i) {
        Ancho::Utils::JSObjectWrapperConst item = Ancho::Utils::JSValueWrapperConst(arr.GetAt(i)).toObject();

        Ancho::Utils::JSValueWrapperConst cancel = item[L"cancel"];
        if (!cancel.isNull()) {
          aOutInfo.cancel = aOutInfo.cancel || cancel.toBool();
        }

        Ancho::Utils::JSValueWrapperConst redirectUrl = item[L"redirectUrl"];
        if (!redirectUrl.isNull()) {
          aOutInfo.redirect = true;
          aOutInfo.newUrl = redirectUrl.toString();
        }
      }
    END_TRY_BLOCK_CATCH_TO_HRESULT

  }
Пример #23
0
bool XlLibraryInitialize(XlAddInExportInfo* pExportInfo)
{
	HRESULT hr;
	CComPtr<ICorRuntimeHost> pHost;

	hr = LoadClr20(&pHost);
	if (FAILED(hr) || pHost == NULL)
	{
		// LoadClr20 shows diagnostic MessageBoxes if needed.
		// Perhaps remember that we are not loaded?
		return 0;
	}

	// If all is fine now, also start the CLR (always safe to do again.
	hr = pHost->Start();
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_NEEDCLR20, 
					IDS_MSG_BODY_HOSTSTART,
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CString addInFullPath = AddInFullPath();

	CPath xllDirectory(addInFullPath);
	xllDirectory.RemoveFileSpec();

	CComPtr<IUnknown> pAppDomainSetupUnk;
	hr = pHost->CreateDomainSetup(&pAppDomainSetupUnk);
	if (FAILED(hr) || pAppDomainSetupUnk == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPDOMAINSETUP, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComQIPtr<IAppDomainSetup> pAppDomainSetup = pAppDomainSetupUnk;

	hr = pAppDomainSetup->put_ApplicationBase(CComBSTR(xllDirectory));
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPLICATIONBASE, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}
	
	CComBSTR configFileName = addInFullPath;
	configFileName.Append(L".config");
	pAppDomainSetup->put_ConfigurationFile(configFileName);

	CComBSTR appDomainName = L"ExcelDna: ";
	appDomainName.Append(addInFullPath);
	pAppDomainSetup->put_ApplicationName(appDomainName);

	IUnknown *pAppDomainUnk = NULL;
	hr = pHost->CreateDomainEx(appDomainName, pAppDomainSetupUnk, 0, &pAppDomainUnk);
	if (FAILED(hr) || pAppDomainUnk == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPDOMAIN, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComQIPtr<_AppDomain> pAppDomain(pAppDomainUnk);

	// Load plan for ExcelDna.Loader:
	// Try AppDomain.Load with the name ExcelDna.Loader.
	// Then if it does not work, we will try to load from a known resource in the .xll.

	CComPtr<_Assembly> pExcelDnaLoaderAssembly;
	hr = pAppDomain->Load_2(CComBSTR(L"ExcelDna.Loader"), &pExcelDnaLoaderAssembly);
	if (FAILED(hr) || pExcelDnaLoaderAssembly == NULL)
	{
		HRSRC hResInfoLoader = FindResource(hModuleCurrent, L"EXCELDNA_LOADER", L"ASSEMBLY");
		if (hResInfoLoader == NULL)
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_MISSINGEXCELDNALOADER, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}
		HGLOBAL hLoader = LoadResource(hModuleCurrent, hResInfoLoader);
		void* pLoader = LockResource(hLoader);
		ULONG sizeLoader = (ULONG)SizeofResource(hModuleCurrent, hResInfoLoader);
		
		CComSafeArray<BYTE> bytesLoader;
		bytesLoader.Add(sizeLoader, (byte*)pLoader);

		hr = pAppDomain->Load_3(bytesLoader, &pExcelDnaLoaderAssembly);
		if (FAILED(hr))
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_EXCELDNALOADER, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}

		CComBSTR pFullName;
		hr = pExcelDnaLoaderAssembly->get_FullName(&pFullName);
		if (FAILED(hr))
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_EXCELDNALOADERNAME, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}
	}
	
	CComPtr<_Type> pXlAddInType;
	hr = pExcelDnaLoaderAssembly->GetType_2(CComBSTR(L"ExcelDna.Loader.XlAddIn"), &pXlAddInType);
	if (FAILED(hr) || pXlAddInType == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_XLADDIN, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComSafeArray<VARIANT> initArgs;
	initArgs.Add(CComVariant((INT32)pExportInfo));
	initArgs.Add(CComVariant((INT32)hModuleCurrent));
	initArgs.Add(CComVariant(addInFullPath.AllocSysString()));
	CComVariant initRetVal;
	CComVariant target;
	hr = pXlAddInType->InvokeMember_3(CComBSTR("Initialize"), (BindingFlags)(BindingFlags_Static | BindingFlags_Public | BindingFlags_InvokeMethod), NULL, target, initArgs, &initRetVal);
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_XLADDININIT, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	pHost_ForUnload = pHost.Detach();
	pAppDomain_ForUnload = (IUnknown*)pAppDomain.Detach();

	return initRetVal.boolVal == 0 ? false : true;
}
Пример #24
0
STDMETHODIMP CConsoleObject::BstrPrintf(BSTR* ret, const SAFEARRAY& varg) const
{
	//DUMP_VARIANTSAFEARRAY(&varg);

	if (ret == NULL)
		return E_POINTER;

	CComSafeArray<VARIANT> safearray;

	HRESULT hr = safearray.Attach(&varg);
	if (FAILED(hr)) return hr;

	if (safearray.GetDimensions() != 1)
		return E_INVALIDARG;

	CAtlString result(_T(""));

	_variant_t current;
	int upper = safearray.GetUpperBound() + 1;
	for (int i = safearray.GetLowerBound(); i < upper; i++) {
		current.Attach(safearray[i]);

		if (current.vt == VT_I4) {
			result.AppendFormat(_T("%ld"), current.lVal);
		} else if (current.vt == VT_BSTR) {
			_bstr_t str(current.bstrVal);
			int specCount = 0;
			TCHAR* lastFound = str;
			TCHAR* found;
			TCHAR next;
			int specLength = 0;

			found = _tcschr(str, _T('%'));

			if (found == NULL) {
				result += static_cast<TCHAR*>(str);
			} else {
				while (found) {
					next = *(found + 1);

					switch (next) {
					case _T('%') : {
						specLength = 2;
						result.CopyChars(result.GetBuffer(), lastFound,
							static_cast<int>(found + 1 - lastFound));
								   }
					case _T('s') : {
						specLength = 2;

						_variant_t varstr;
						GET_NEXT_VARIANT(varstr, VT_BSTR);

						result.Append(lastFound, static_cast<int>(found - lastFound));
						result += varstr.bstrVal;

						break;
								   }
					case _T('d') : {
						specLength = 2;

						_variant_t varint;
						GET_NEXT_VARIANT(varint, VT_I4);

						result.Append(lastFound, static_cast<int>(found - lastFound));
						result.AppendFormat(_T("%ld"), varint.lVal);

						break;
								   }
					case _T('f') : {
						specLength = 2;

						//GET_NEXT_VARIANT(VT_R8);
						break;
								   }
					case _T('x') :
						break;
					default:
						break;
					}

					found += specLength;
					lastFound = found;
					found = _tcschr(found, _T('%'));
				} // while loop
			}
		} else {
			result += _T("[unsupported argument type]");
		}

		result += _T(' ');
		current.Detach();
	} // for loop

	safearray.Detach();

	result.SetAt(result.GetLength() - 1, _T('\0'));
	BSTR tmp = result.AllocSysString();
	if (tmp == NULL) return E_OUTOFMEMORY;

	*ret = tmp;
	return S_OK;
}
void main(int argc, char**argv)
{
	std::wcout << L"\n ===================================\n";
	std::wcout << L"\n  TextFinderComponent C++ Interface ";
	std::wcout << L"\n ===================================\n";

	HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

	if (!SUCCEEDED(hr))
	{
		std::wcout << L"\n  could not initialize COM";
	}

	try
	{
		CComQIPtr<ITextCompCOM> TextFinderComp;

		TextFinderComp.CoCreateInstance(CLSID_TextCompCOM);
		
		if (TextFinderComp != 0)
		{
			std::wcout << L"\n =============================================================\n";

			std::wcout << "The Text Component Interface was successfully initialized" << std::endl;

			std::wcout << L"\n =============================================================\n";

			InputArgumentParser parser;

			if (parser.parseCommandLineArgs2TextCompArguments(argc, argv))
			{
				HRESULT h0 = TextFinderComp->InitializeComponent();

				HRESULT h1 = TextFinderComp->SetSearchPath(CComBSTR(parser.getDirectoryPath().c_str()));

				BSTR allPatterns;
				BSTR recursion;

				allPatterns = convertstdSTR2BSTR(bool2String(true)) ;    //By default find all patterns
				
				recursion = convertstdSTR2BSTR(bool2String(false)) ;  // By default Recursion is disabled

				if (parser.getRecursionFlag())
				{
					recursion = convertstdSTR2BSTR(bool2String(true));
				}

				if (!parser.getAllPatternsFlag())
				{
					allPatterns = convertstdSTR2BSTR(bool2String(false));
				}

				HRESULT h2 = TextFinderComp->SetSpecialSearchClause(recursion, allPatterns);

				HRESULT h3 = TextFinderComp->SetFilePatterns(convertVector2CCOMSafeArray(parser.getFilePatterns()).GetSafeArrayPtr());

				HRESULT h4 = TextFinderComp->SetTextPatterns(convertVector2CCOMSafeArray(parser.getTextPatterns()).GetSafeArrayPtr());

				if (SUCCEEDED(h0) && SUCCEEDED(h1) && SUCCEEDED(h2) && SUCCEEDED(h3) && SUCCEEDED(h4))
				{
					
					SAFEARRAY files;
				
					SAFEARRAY* pFiles = &files;

					TextFinderComp->GetQualifyingFileList(&pFiles);

					CComSafeArray<BSTR> Files;

					Files.Attach(pFiles);	

					std::wcout << L"\n =============================================================\n";
					std::wcout << L"\n =============================================================\n";

					std::wcout<<"The Qualifying Files from the Text Search Component via C++ COM interface"<<std::endl;

					displayCCOMBSTRFiles(Files);

					std::cout << "End of C++ Client for Text Search Component" << std::endl;

					std::wcout << L"\n =============================================================\n";

				}
			}

			else
			{
				parser.displayIllegalArgumentMessage();
			}

		}

	}
	catch (std::exception& ex)
	{
		std::wcout << L"\n  Exception Encountered during COM Stuff .. Contact Admin and Bug Him!" << ex.what() << L"\n\n";
		return;
	}

	std::wcout << L"\n\n";
	CoUninitialize();
}
Пример #26
0
LRESULT CChildFrame::OnTvnSelChanged(int idCtrl, LPNMHDR pNMHDR, BOOL& bHandled)
{ 
    USES_CONVERSION; 
    HRESULT hr = E_FAIL; 

    idCtrl, pNMHDR, bHandled; 
    CTreeViewCtrl ctrlTree = m_wndCatalog; 

    bHandled = FALSE; 

    NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; 
    ATLASSERT( pNMTreeView ); 

    { 
        m_pData.m_hTreeItem = pNMTreeView->itemNew.hItem; 
        m_pData.m_pTreeView = &m_wndCatalog; 
    } 

    CTreeItem hItem(pNMTreeView->itemNew.hItem, &m_wndCatalog); 

    TREE_ITEM_DATA * pCurrSel = NULL; 
    pCurrSel = (TREE_ITEM_DATA *) ctrlTree.GetItemData(hItem); 

    if (pCurrSel && STGTY_STREAM == pCurrSel->dwStgType) 
    { 
        CComPtr<IStream> spStrm; 
        hr = pCurrSel->spStgOrStrm->QueryInterface(&spStrm); 
        if (FAILED(hr)) return hr; 

        STATSTG st = { 0 }; 
        hr = spStrm->Stat(&st, STATFLAG_NONAME); 
        if (FAILED(hr)) return hr; 

        LARGE_INTEGER liBegin = { 0 }; 
        hr = spStrm->Seek(liBegin, STREAM_SEEK_SET, NULL); 

        BYTE * byBuff = new BYTE[st.cbSize.QuadPart+1]; 
        ZeroMemory(byBuff, (st.cbSize.QuadPart+1)*sizeof(BYTE)); 
        ULONG ulSize = 0; 
        hr = spStrm->Read(byBuff, st.cbSize.QuadPart, &ulSize); 

		ATLASSERT(SUCCEEDED(hr));

        if(st.cbSize.QuadPart) 
        { 
            CComSafeArray data; 
            data.CreateOneDim(VT_UI1, st.cbSize.QuadPart, (const void *)byBuff); 
            m_wndHexEdit.SetData(data); 
        } 
        else 
        {
            CComVariant data; 
            m_wndHexEdit.SetData(data); 
        }

        { 
            m_wndFileDetails.ShowWindow(SW_HIDE); 
            m_wndHexEdit.ShowWindow(SW_NORMAL); 
            SetSplitterPane(SPLIT_PANE_RIGHT, m_wndHexEdit); 
        } 

        delete [] byBuff; 
    } 
    else if (pCurrSel && STGTY_STORAGE == pCurrSel->dwStgType) 
    { 
        CComVariant data; 
        m_wndHexEdit.SetData(data); 
        m_wndHexEdit.ShowWindow(SW_HIDE); 

        std::vector<STATSTG_EX> vecFileInfo; 

        CTreeItem tiChild = hItem.GetChild(); 
        while (FALSE == tiChild.IsNull()) 
        { 
            TREE_ITEM_DATA * pData = (TREE_ITEM_DATA *)tiChild.GetData(); 

            STATSTG_EX statstgex; 

            do 
            { 
                if (pData->dwStgType == STGTY_STREAM) 
                { 
                    CComPtr<IStream> spStrm; 
                    hr = pData->spStgOrStrm->QueryInterface(&spStrm); 
                    if (FAILED(hr)) break; 
                    
                    hr = spStrm->Stat(&statstgex, STATFLAG_NONAME); 
                    if (FAILED(hr)) break; 
                } 
                else if (pData->dwStgType == STGTY_STORAGE) 
                { 
                    CComPtr<IStorage> spStg; 
                    hr = pData->spStgOrStrm->QueryInterface(&spStg); 
                    if (FAILED(hr)) break; 
                    
                    hr = spStg->Stat(&statstgex, STATFLAG_NONAME); 
                    if (FAILED(hr)) break; 
                } 
            } while(0); 
            
            statstgex.htiHost = tiChild.m_hTreeItem; 
            
            TCHAR szSwap[MAX_PATH] = { 0 }; 
            tiChild.GetText(szSwap, _countof(szSwap)); 
            TCHAR2WCHAR(szSwap, statstgex.szwName, _countof(statstgex.szwName)); 
            
            vecFileInfo.push_back(statstgex); 

            tiChild = tiChild.GetNextSibling(); 
        } 

        m_wndFileDetails.SetFileInfo(vecFileInfo); 

        m_wndFileDetails.ShowWindow(SW_NORMAL); 
        SetSplitterPane(SPLIT_PANE_RIGHT, m_wndFileDetails); 
    } 

    return 0;
}