Beispiel #1
0
STDMETHODIMP CFDMDownload::get_Url(BSTR *pVal)
{
	USES_CONVERSION;
	*pVal = SysAllocString (T2W (m_strUrl));
	return S_OK;
}
Beispiel #2
0
HRESULT
GetElementLONGLONGProperty(
    IN  IAppHostElement * pSitesCollectionEntry,
    IN  LPCWSTR           pwszName,
    OUT LONGLONG *        pllValue
)
{
    HRESULT            hr = S_OK;
    IAppHostProperty * pProperty = NULL;
    BSTR               bstrName = NULL;
    VARIANT            varValue;

    VariantInit( &varValue );

    bstrName = SysAllocString( pwszName );
    if ( bstrName == NULL )
    {
        hr = E_OUTOFMEMORY;
        DBGERROR_HR(hr);
        goto error;
    }

    hr = pSitesCollectionEntry->GetPropertyByName( bstrName,
                                                   &pProperty );
    if ( FAILED ( hr ) )
    {
        goto error;
    }

    hr = pProperty->get_Value( &varValue );
    if ( FAILED ( hr ) )
    {
         goto error;
    }

    hr = VariantChangeType( &varValue, &varValue, 0, VT_I8 );
    if ( FAILED ( hr ) )
    {
         goto error;
    }

    // extract the value
    *pllValue = varValue.ulVal;

error:

    VariantClear( &varValue );

    if ( pProperty != NULL )
    {
        pProperty->Release();
        pProperty = NULL;
    }

    if ( bstrName != NULL )
    {
        SysFreeString( bstrName );
        bstrName = NULL;
    }

    return hr;
}
Beispiel #3
0
HRESULT
FindElementInCollection(
    IAppHostElementCollection           *pCollection,
    CONST WCHAR *                       szKeyName,
    CONST WCHAR *                       szKeyValue,
    ULONG                               BehaviorFlags,
    OUT   ULONG *                       pIndex
    )
{
    HRESULT hr = NOERROR;

    CComPtr<IAppHostElement>        pElement;
    CComPtr<IAppHostProperty>       pKeyProperty;

    VARIANT varIndex;
    VariantInit( &varIndex );

    VARIANT varKeyValue;
    VariantInit( &varKeyValue );

    DWORD   count;
    DWORD   i;

    BSTR bstrKeyName = NULL;
    PFN_FIND_COMPARE_PROC compareProc;

    compareProc = (BehaviorFlags & FIND_ELEMENT_CASE_INSENSITIVE)
                      ? &FindCompareCaseInsensitive
                      : &FindCompareCaseSensitive;

    bstrKeyName = SysAllocString( szKeyName );
    if( !bstrKeyName )
    {
        hr = E_OUTOFMEMORY;
        DBGERROR_HR(hr);
        goto exit;
    }

    hr = pCollection->get_Count( &count );
    if( FAILED(hr) )
    {
        DBGERROR_HR(hr);
        goto exit;
    }

    for( i = 0; i < count; i++ )
    {
        varIndex.vt = VT_UI4;
        varIndex.ulVal = i;

        hr = pCollection->get_Item( varIndex,
                                    &pElement );
        if( FAILED(hr) )
        {
            DBGERROR_HR(hr);
            goto tryNext;
        }

        hr = pElement->GetPropertyByName( bstrKeyName,
                                          &pKeyProperty );
        if( FAILED(hr) )
        {
            DBGERROR_HR(hr);
            goto tryNext;
        }

        hr = pKeyProperty->get_Value( &varKeyValue );

        if( FAILED(hr) )
        {
            DBGERROR_HR(hr);
            goto tryNext;
        }

        if ((compareProc)(szKeyValue, varKeyValue.bstrVal))
        {
            *pIndex = i;
            break;
        }

tryNext:

        pElement.Release();
        pKeyProperty.Release();

        VariantClear( &varKeyValue );
    }

    if (i >= count)
    {
        hr = S_FALSE;
    }

exit:

    SysFreeString( bstrKeyName );
    VariantClear( &varKeyValue );

    return hr;
}
// HandleMessageForDownloadThread runs in the context of the download thread.
HRESULT HandleMessageForDownloadThread(
   MSG* pMsg,
   CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx, 
   CComPtr<IWMPContentPartnerCallback> spCallback)
{
   DOWNLOAD_BATCH_CONTEXT* pBatchCtx = NULL;
   CComPtr<IWMPContentContainerList> spContainerList;
   ULONG numContainers = 0;
   ULONG availableUrlStrings = sizeof(g_tracks)/sizeof(g_tracks[0]);
   HRESULT hr = S_OK;

   if(NULL == pMsg || NULL == pThreadCtx || NULL == spCallback)
   {
      hr = E_INVALIDARG;
      goto cleanup;
   }

   if(pThreadCtx->downloadThreadContext.msgDownloadBatch == pMsg->message)
   {
      // We must handle this message and free the message context.

      ATLTRACE2("%x: HandleMessageForDownloadThread: Received message to download a batch of media items.\n", GetCurrentThreadId());          

      pBatchCtx = reinterpret_cast<DOWNLOAD_BATCH_CONTEXT*>(pMsg->lParam);

      if(NULL == pBatchCtx->pIStream)
      {
         hr = E_UNEXPECTED;        
         goto cleanup;
      }   

      // Get a pointer to an IWMPContentContainerList interface.

      hr = CoGetInterfaceAndReleaseStream(
         pBatchCtx->pIStream,
         __uuidof(IWMPContentContainerList),
         reinterpret_cast<LPVOID*>(&spContainerList) );

      // The stream was released (even if CoGetInterfaceAndReleaseStream failed). 
      // Set the stream pointer to NULL.
      pBatchCtx->pIStream = NULL;

      if(FAILED(hr))
      {
         ATLTRACE2("%x: HandleMessageForDownloadThread: Failed to get IWMPContentContainerList interface. %x\n", GetCurrentThreadId(), hr);          
         goto cleanup;
      }

      if(NULL == spContainerList)
      {
         hr = E_UNEXPECTED;      
         goto cleanup;
      }

      ATLTRACE2("%x: HandleMessageForDownloadThread: Successfully obtained IWMPContentContainerList interface.\n", GetCurrentThreadId());
     
      hr = spContainerList->GetContainerCount(&numContainers);

      if(FAILED(hr))
      {
         ATLTRACE2("%x: HandleMessageForDownloadThread: GetContainerCount failed. %x\n", GetCurrentThreadId(), hr);
         goto cleanup;
      }

      ATLTRACE2("%x: HandleMessageForDownloadThread: numContainers = %d.\n", GetCurrentThreadId(), numContainers);       
  
      for(ULONG j = 0; j < numContainers; ++j)
      {
         ULONG numItems = 0;
         CComPtr<IWMPContentContainer> spContainer;

         hr = spContainerList->GetContainer(j, &spContainer);

         if(FAILED(hr))
         {
            break;  // Break out of the for-j loop.
         }
            
         hr = spContainer->GetContentCount(&numItems); 

         if(FAILED(hr))
         {
            // Make sure we don't enter the for-k loop.
            numItems = 0;
         }      
                
         ATLTRACE2("%x: HandleMessageForDownloadThread: Container has %d items.\n", GetCurrentThreadId(), numItems);

         for(ULONG k = 0; k < numItems; ++k)
         {
            ULONG itemID = 0;
            HRESULT hrDownload = S_OK;
            BSTR bstrUrl = NULL;
            WCHAR url[INTERNET_MAX_URL_LENGTH] = L"";
   
            hr = spContainer->GetContentID(k, &itemID);

            if(FAILED(hr))
            {
               break;  // Break out of the for-k loop.
               // This means we won't call DownloadTrack.
            }

            wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_audioRootURL);
                  
            if(itemID < availableUrlStrings)
            {    
               wcscat_s(url, INTERNET_MAX_URL_LENGTH, g_tracks[itemID]);
            }
            else
            {
               wcscat_s(url, INTERNET_MAX_URL_LENGTH, g_placeholderTrack);       
            }

            bstrUrl = SysAllocString(url);

            if(NULL == bstrUrl)
            {
               hrDownload = E_OUTOFMEMORY;
            }                

            // Tell Windows Media Player to download this one track (or not).
            hr = spCallback->DownloadTrack(
               pBatchCtx->cookie, 
               bstrUrl,
               itemID, 
               NULL, 
               hrDownload);

            // Ignore hr.

            SysFreeString(bstrUrl);

         } // for k
      } // for j  
   } // download message

   else
   {
      ATLTRACE2("%x: HandleMessageForDownloadThread: Received unrecognized message. &x\n", GetCurrentThreadId(), pMsg->message);
   }

cleanup:

   if(NULL != pThreadCtx && NULL != pMsg)
   {
      if(pThreadCtx->downloadThreadContext.msgDownloadBatch == pMsg->message)
      {
         // The thread that posted this message allocated a 
         // DOWNLOAD_BATCH_CONTEXT structure. We must free that
         // memory here.

         if(NULL != pBatchCtx)
         {
            if(NULL != pBatchCtx->pIStream)
            {
               // For some reason, CoGetInterfaceAndReleaseStream never got called.
               pBatchCtx->pIStream->Release();
               pBatchCtx->pIStream = NULL;
            }
     
            delete pBatchCtx;
            pBatchCtx = NULL;
         } 
      }
   }

   return hr;    
     
} // HandleMessageForDownloadThread
Beispiel #5
0
HRESULT
GetSharedConfigEnabled(
    BOOL * pfIsSharedConfig
)
/*++

Routine Description:
   Search the configuration for the shared configuration property.

Arguments:

    pfIsSharedConfig - true if shared configuration is enabled

Return Value:
    HRESULT

--*/
{
    HRESULT                 hr = S_OK;
    IAppHostAdminManager    *pAdminManager = NULL;

    BSTR                    bstrSectionName = NULL;
    BSTR                    bstrConfigPath = NULL;

    IAppHostElement *       pConfigRedirSection = NULL;


    bstrSectionName = SysAllocString( L"configurationRedirection" );

    if ( bstrSectionName == NULL )
    {
        hr = E_OUTOFMEMORY;
        DBGERROR_HR(hr);
        goto exit;
    }

    bstrConfigPath = SysAllocString( L"MACHINE/REDIRECTION" );
    if ( bstrConfigPath == NULL )
    {
        hr = E_OUTOFMEMORY;
        DBGERROR_HR(hr);
        goto exit;
    }

    hr = CoCreateInstance( CLSID_AppHostAdminManager,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_IAppHostAdminManager,
                           (VOID **)&pAdminManager );
    if( FAILED(hr) )
    {
        DBGERROR_HR(hr);
        goto exit;
    }

    hr = pAdminManager->GetAdminSection( bstrSectionName,
                                         bstrConfigPath,
                                         &pConfigRedirSection );
    if( FAILED(hr) )
    {
        DBGERROR_HR(hr);
        goto exit;
    }

    hr = GetElementBoolProperty( pConfigRedirSection,
                                 L"enabled",
                                 pfIsSharedConfig );

    if ( FAILED( hr ) )
    {
        DBGERROR_HR(hr);
        goto exit;
    }

    pConfigRedirSection->Release();
    pConfigRedirSection = NULL;


exit:

    //
    // dump config exception to setup log file (if available)
    //

    if ( pConfigRedirSection != NULL )
    {
        pConfigRedirSection->Release();
    }

    if ( pAdminManager != NULL )
    {
        pAdminManager->Release();
    }

    if ( bstrConfigPath != NULL )
    {
        SysFreeString( bstrConfigPath );
    }

    if ( bstrSectionName != NULL )
    {
        SysFreeString( bstrSectionName );
    }

    return hr;
}
HRESULT STDMETHODCALLTYPE TextAreaTextRange::GetText(_In_ int maxLength, _Out_ BSTR * retVal)
{
    if (!IsWindow(_hwnd))
    {
        return UIA_E_ELEMENTNOTAVAILABLE;
    }

    HRESULT hr = S_OK;
    int builderSize;
    PWSTR textBuilder;
    if (maxLength >= 0)
    {
        builderSize = maxLength + 1;
    }
    else
    {
        builderSize = 0;
        EndPoint current = _range.begin;
        while (QuickCompareEndpoints(current, _range.end) < 0)
        {
            if (current.line < _range.end.line)
            {
                int length = _control->GetLineLength(current.line);
                // Add 1 for the implied newline
                builderSize += length - current.character + 1;
                current.line++;
                current.character = 0;
            }
            else
            {
                builderSize += _range.end.character - current.character;
                current.character = _range.end.character;
            }
        }

        // Always allow space for the final string terminator.
        builderSize++;
    }

    textBuilder = new WCHAR[builderSize];
    if (textBuilder != NULL)
    {
        int writePos = 0;
        EndPoint current = _range.begin;
        while (QuickCompareEndpoints(current, _range.end) < 0 && writePos < (builderSize - 1))
        {
            int copyLength = 0;
            EndPoint next;
            bool trailingNewline = false;
            if (current.line < _range.end.line)
            {
                int length = _control->GetLineLength(current.line);
                // Add 1 for the implied newline
                copyLength = length - current.character;
                trailingNewline = true;
                next.line = current.line + 1;
                next.character = 0;
            }
            else
            {
                copyLength = _range.end.character - current.character;
                next.line = current.line;
                next.character = _range.end.character;
            }

            if (writePos + copyLength >= (builderSize - 1))
            {
                copyLength = (builderSize - 1) - writePos;
            }

            TextLine *textLine = _control->GetLine(current.line);
            StringCchCopyN(&textBuilder[writePos], copyLength + 1, &textLine->text[current.character], copyLength);
            writePos += copyLength;
            current = next;

            if (trailingNewline && writePos < (builderSize - 1))
            {
                textBuilder[writePos++] = '\n';
            }
        }
        // Ensure the string is null-terminated
        textBuilder[writePos] = '\0';

        *retVal = SysAllocString(textBuilder);
        if (*retVal == NULL)
        {
            hr = E_OUTOFMEMORY;
        }

        delete [] textBuilder;
    }
    else
    {
        hr = E_OUTOFMEMORY;
    }
        
    return hr;
}
Beispiel #7
0
bool COpenGL::SetShadersGLSL_OLD(const TCHAR *glslFileName)
{
	char *fragment = NULL, *vertex = NULL;
	IXMLDOMDocument * pXMLDoc = NULL;
	IXMLDOMElement * pXDE = NULL;
	IXMLDOMNode * pXDN = NULL;
	HRESULT hr;
	BSTR queryString, nodeContent;

	TCHAR errorMsg[MAX_PATH + 50];

	if (fragmentShader) {
		glDetachShader(shaderProgram, fragmentShader);
		glDeleteShader(fragmentShader);
		fragmentShader = 0;
	}
	if (vertexShader) {
		glDetachShader(shaderProgram, vertexShader);
		glDeleteShader(vertexShader);
		vertexShader = 0;
	}
	if (shaderProgram) {
		glUseProgram(0);
		glDeleteProgram(shaderProgram);
		shaderProgram = 0;
	}

	if (glslFileName == NULL || *glslFileName == TEXT('\0'))
		return true;

	if (!LoadShaderFunctions()) {
		MessageBox(NULL, TEXT("Unable to load OpenGL shader functions"), TEXT("Shader Loading Error"),
			MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pXMLDoc));

	if (FAILED(hr)) {
		MessageBox(NULL, TEXT("Error creating XML Parser"), TEXT("Shader Loading Error"),
			MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	VARIANT fileName;
	VARIANT_BOOL ret;
	fileName.vt = VT_BSTR;
#ifdef UNICODE
	fileName.bstrVal = SysAllocString(glslFileName);
#else
	wchar_t tempfilename[MAX_PATH];
	MultiByteToWideChar(CP_UTF8, 0, glslFileName, -1, tempfilename, MAX_PATH);
	fileName.bstrVal = SysAllocString(tempfilename);
#endif
	hr = pXMLDoc->load(fileName, &ret);
	SysFreeString(fileName.bstrVal);

	if (FAILED(hr) || hr == S_FALSE) {
		_stprintf(errorMsg, TEXT("Error loading GLSL shader file:\n%s"), glslFileName);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK | MB_ICONEXCLAMATION);
		pXMLDoc->Release();
		return false;
	}

	VARIANT attributeValue;
	BSTR attributeName;

	hr = pXMLDoc->get_documentElement(&pXDE);
	if (FAILED(hr) || hr == S_FALSE) {
		_stprintf(errorMsg, TEXT("Error loading root element from file:\n%s"), glslFileName);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK | MB_ICONEXCLAMATION);
		pXMLDoc->Release();
		return false;
	}

	attributeName = SysAllocString(L"language");
	pXDE->getAttribute(attributeName, &attributeValue);
	SysFreeString(attributeName);
	pXDE->Release();

	if (attributeValue.vt != VT_BSTR || lstrcmpiW(attributeValue.bstrVal, L"glsl")) {
		_stprintf(errorMsg, TEXT("Shader language is <%s>, expected <GLSL> in file:\n%s"), attributeValue.bstrVal, glslFileName);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK | MB_ICONEXCLAMATION);
		if (attributeValue.vt == VT_BSTR) SysFreeString(attributeValue.bstrVal);
		pXMLDoc->Release();
		return false;
	}
	if (attributeValue.vt == VT_BSTR) SysFreeString(attributeValue.bstrVal);

	queryString = SysAllocString(L"/shader/fragment");
	hr = pXMLDoc->selectSingleNode(queryString, &pXDN);
	SysFreeString(queryString);

	if (hr == S_OK) {
		hr = pXDN->get_text(&nodeContent);
		if (hr == S_OK) {
			int requiredChars = WideCharToMultiByte(CP_ACP, 0, nodeContent, -1, fragment, 0, NULL, NULL);
			fragment = new char[requiredChars];
			WideCharToMultiByte(CP_UTF8, 0, nodeContent, -1, fragment, requiredChars, NULL, NULL);
		}
		SysFreeString(nodeContent);
		pXDN->Release();
		pXDN = NULL;
	}

	queryString = SysAllocString(L"/shader/vertex");
	hr = pXMLDoc->selectSingleNode(queryString, &pXDN);
	SysFreeString(queryString);

	if (hr == S_OK) {
		hr = pXDN->get_text(&nodeContent);
		if (hr == S_OK) {
			int requiredChars = WideCharToMultiByte(CP_ACP, 0, nodeContent, -1, vertex, 0, NULL, NULL);
			vertex = new char[requiredChars];
			WideCharToMultiByte(CP_UTF8, 0, nodeContent, -1, vertex, requiredChars, NULL, NULL);
		}
		SysFreeString(nodeContent);
		pXDN->Release();
		pXDN = NULL;
	}

	pXMLDoc->Release();

	if (!fragment && !vertex) {
		_stprintf(errorMsg, TEXT("No vertex or fragment program in file:\n%s"), glslFileName);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	shaderProgram = glCreateProgram();
	if (vertex) {
		vertexShader = glCreateShader(GL_VERTEX_SHADER);
		glShaderSource(vertexShader, 1, (const GLchar **)&vertex, NULL);
		glCompileShader(vertexShader);
		glAttachShader(shaderProgram, vertexShader);
		delete[] vertex;
	}
	if (fragment) {
		fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
		glShaderSource(fragmentShader, 1, (const GLchar **)&fragment, NULL);
		glCompileShader(fragmentShader);
		glAttachShader(shaderProgram, fragmentShader);
		delete[] fragment;
	}

	glLinkProgram(shaderProgram);
	glUseProgram(shaderProgram);

	shader_type = OGL_SHADER_GLSL_OLD;

	return true;
}
static BOOL PyCom_ExcepInfoFromServerExceptionInstance(PyObject *v, EXCEPINFO *pExcepInfo)
{
	BSTR temp;

	assert(v != NULL);
	assert(pExcepInfo != NULL);
	memset(pExcepInfo, 0, sizeof(EXCEPINFO));

	PyObject *ob = PyObject_GetAttrString(v, "description");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrDescription = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrDescription = temp;
	} else {
		// No description - leave it empty.
		PyErr_Clear();
	}
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "source");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrSource = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrSource = temp;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "helpfile");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrHelpFile = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrHelpFile = temp;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "code");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->wCode = (unsigned short)PyInt_AsLong(temp);
			Py_DECREF(temp);
		} // XXX - else - what to do here, apart from call the user a moron :-)
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "scode");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->scode = PyInt_AsLong(temp);
			Py_DECREF(temp);
		} else
			// XXX - again, should we call the user a moron?
			pExcepInfo->scode = E_FAIL;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "helpcontext");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->dwHelpContext = (unsigned short)PyInt_AsLong(temp);
			Py_DECREF(temp);
		}
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);
	return TRUE;
}
Beispiel #9
0
static HRESULT function_invoke(DispatchEx *This, func_info_t *func, WORD flags, DISPPARAMS *dp, VARIANT *res,
        EXCEPINFO *ei)
{
    HRESULT hres;

    switch(flags) {
    case DISPATCH_METHOD|DISPATCH_PROPERTYGET:
        if(!res)
            return E_INVALIDARG;
        /* fall through */
    case DISPATCH_METHOD:
        if(This->dynamic_data && This->dynamic_data->func_disps
           && This->dynamic_data->func_disps[func->func_disp_idx].func_obj) {
            func_obj_entry_t *entry = This->dynamic_data->func_disps + func->func_disp_idx;

            if((IDispatch*)&entry->func_obj->dispex.IDispatchEx_iface != entry->val) {
                if(!entry->val) {
                    FIXME("Calling null\n");
                    return E_FAIL;
                }

                hres = invoke_disp_value(This, entry->val, 0, flags, dp, res, ei, NULL);
                break;
            }
        }

        hres = typeinfo_invoke(This, func, flags, dp, res, ei);
        break;
    case DISPATCH_PROPERTYGET: {
        func_obj_entry_t *entry;

        if(func->id == DISPID_VALUE) {
            BSTR ret;

            ret = SysAllocString(objectW);
            if(!ret)
                return E_OUTOFMEMORY;

            V_VT(res) = VT_BSTR;
            V_BSTR(res) = ret;
            return S_OK;
        }

        hres = get_func_obj_entry(This, func, &entry);
        if(FAILED(hres))
            return hres;

        V_VT(res) = VT_DISPATCH;
        V_DISPATCH(res) = entry->val;
        if(V_DISPATCH(res))
            IDispatch_AddRef(V_DISPATCH(res));
        hres = S_OK;
        break;
    }
    case DISPATCH_PROPERTYPUT: {
        func_obj_entry_t *entry;
        VARIANT *v;

        if(dp->cArgs != 1 || (dp->cNamedArgs == 1 && *dp->rgdispidNamedArgs != DISPID_PROPERTYPUT)
           || dp->cNamedArgs > 1) {
            FIXME("invalid args\n");
            return E_INVALIDARG;
        }

        v = dp->rgvarg;
        /* FIXME: not exactly right */
        if(V_VT(v) != VT_DISPATCH)
            return E_NOTIMPL;

        hres = get_func_obj_entry(This, func, &entry);
        if(FAILED(hres))
            return hres;

        if(entry->val)
            IDispatch_Release(entry->val);
        entry->val = V_DISPATCH(v);
        if(entry->val)
            IDispatch_AddRef(entry->val);
        hres = S_OK;
        break;
    }
    default:
        FIXME("Unimplemented flags %x\n", flags);
        hres = E_NOTIMPL;
    }

    return hres;
}
Beispiel #10
0
/******************************************************************************
*  RefreshData -- This method is called by Microsoft Excel to get new data.
*  This method call only takes place after being notified by the real-time
*  data server that there is new data.
*  Parameters: TopicCount -- filled with the count of topics in the safearray
*              parrayOut -- two-dimensional safearray.  First dimension
*                           contains the list of topic IDs.  Second dimension
*                           contains the values of those topics.
*  Returns: S_OK
*           E_POINTER
*           E_FAIL
******************************************************************************/
STDMETHODIMP RTDServer::RefreshData( long *TopicCount,
                                     SAFEARRAY **parrayOut)
{
    //Check the arguments first
    if ((TopicCount == NULL) || (parrayOut == NULL) || (*parrayOut != NULL)) {
        // Bad pointer
        return E_POINTER;
    }

    HRESULT hr = S_OK;

    //Set the TopicCount
    *TopicCount = m_pTopicList.size();


    SAFEARRAYBOUND bounds[2];

    //Build the safe-array values we want to insert
    bounds[0].cElements = 2;
    bounds[0].lLbound = 0;
    bounds[1].cElements = *TopicCount;
    bounds[1].lLbound = 0;
    *parrayOut = SafeArrayCreate(VT_VARIANT, 2, bounds);

    int i = 0;
    for (TopicList::const_iterator iTopic = m_pTopicList.begin();
            iTopic != m_pTopicList.end(); ++iTopic, ++i) {
        std::stringstream topicValue;
        long index[2];
        index[0] = 0;
        index[1] = i;

        VARIANT value;
        VariantInit(&value);
        value.vt = VT_I4;
        value.lVal = iTopic->first;
        SafeArrayPutElement(*parrayOut, index, &value);

        index[0] = 1;
        index[1] = i;

        const std::string& topicName = iTopic->second.name;
        if (topicName != MONITOR_HEARTBEAT) {
            Monitor::RTDMonitor* monitor = getMonitor(iTopic->second);

            if (topicName == MONITOR_COLUMN_COUNT) {
                topicValue << (monitor ? monitor->getColumnCount() : 0);
            } else if (topicName == MONITOR_IS_NODE_VALID) {
                bool isNodeValid = (monitor ? monitor->isNodeValid(iTopic->second.parameters[0]) : false);
                topicValue << (isNodeValid ? "True" : "False");

            } else if (topicName == MONITOR_NODE_VALUE) {
                int index = atoi(iTopic->second.parameters[1].c_str());

                if (monitor == NULL) {
                    topicValue << "#Error: unable to find monitor with id: " << iTopic->second.monitorId;
                } else {
                    topicValue << monitor->getNodeValue(iTopic->second.parameters[0], index);
                }
            } else if (topicName == MONITOR_NODE_COLOR) {
                int index = atoi(iTopic->second.parameters[1].c_str());

                if (monitor != NULL) {
                    topicValue << monitor->getNodeColor(iTopic->second.parameters[0], index);
                }

            } else if (topicName == MONITOR_NODE_CHILDREN) {
                if (monitor == NULL) {
                    topicValue << "{}";
                } else {
                    topicValue << convertToDelimitedString(monitor->getNodeChildren(iTopic->second.parameters[0]));
                }

            } else {
                topicValue << "<unsupported request>";

                hr = E_FAIL;
            }
        }

        VariantInit(&value);
        value.vt = VT_BSTR;

        std::wstring ws;
        std::string s = topicValue.str();
        ws.assign(s.begin(), s.end());
        value.bstrVal = SysAllocString(ws.c_str());

        SafeArrayPutElement(*parrayOut, index, &value);
        VariantClear(&value); // Release memory.
    }

    return hr;
}
BOOL ParseCommandLine( int argc, wchar_t *argv[ ])
{
/*
     ** PARSE the FOLLOWING ARGUMENTS:
    /LDAP <Path of container>
        ADsPath of the container for placing the new group
    
    /UNAME <NT 5 User Name>
        This is the name for the new group
    
    /SAMNAME <Downlevel NT 4 Sam Account name>
        Cannot exceed 20 characters and must be globally unique

    <*> Detailed New User information <*>
    /FILE < Info File >
    
        Filename for file to contain new user information

    <*> OPTIONAL Binding Information <*>
    /USER <User name used for binding to the DC>
    
    /PASS <Password used for binding to the DC>
    (If these are passed, binding is done with ADsOpenObject())
*/        
	if (argc == 1)
	{
        _putws(pwszUsage);
        return FALSE;
    }
    for (int x= 1; x < argc; x++)
    {
        if (_wcsicmp(argv[x],L"/LDAP")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsLDAP = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/UNAME")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsUNAME = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/SAMNAME")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsSAMNAME = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/FILE")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsFILE = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/USER")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsUSER = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/PASS")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsPASS = SysAllocString(argv[x]);                
        }
        else
        {
                wprintf(L"\nERROR: %s UNknown Argument\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
        }
    }
    // Check if User is poassed, then password is required:
    if (bsUSER || bsPASS)
        if (!bsUSER || !bsPASS) // if either one is missing complain
        {
            _putws(L"\nERROR: If /USER is specified /PASS is required!");
            return FALSE;
        }                    
      
    return TRUE;
}
Beispiel #12
0
/******************************************************************************
*  ConnectData -- Adds new topics from a real-time data server. The ConnectData
*  method is called when a file is opened that contains real-time data
*  functions or when a user types in a new formula which contains the RTD
*  function.
*  Parameters: TopicID -- value assigned by Excel to identify the topic
*              Strings -- safe array containing the strings identifying the
*                         data to be served.
*              GetNewValues -- BOOLEAN indicating whether to retrieve new
*                              values or not.
*              pvarOut -- initial value of the topic
*  Returns: S_OK
*           E_POINTER
*           E_FAIL
******************************************************************************/
STDMETHODIMP RTDServer::ConnectData(long TopicID,
                                    SAFEARRAY **Strings,
                                    VARIANT_BOOL *GetNewValues,
                                    VARIANT *pvarOut)
{
    //Check the arguments first
    if (pvarOut == NULL) return E_POINTER;

    HRESULT hr = S_OK;

    std::stringstream topicValue;
    bool addTopic = true;

    TopicData topicData;
    topicData.name = getSafeArrayElementAsStr(Strings, 0);

    if (topicData.name != MONITOR_HEARTBEAT) {
        topicData.monitorId = getSafeArrayElementAsStr(Strings, 1);

        Monitor::RTDMonitor* monitor = getMonitor(topicData);

        if (topicData.name == MONITOR_NEW_MONITOR) {
            if (monitor != NULL) {
                monitor->newRepo("");

                delete monitor;
                this->monitors.erase(topicData.monitorId);
            }

            monitor = new Monitor::RTDMonitor;
            this->monitors.insert(Monitors::value_type(topicData.monitorId, monitor));

            addTopic = false;

            topicValue << "True";
        } else if (topicData.name == MONITOR_REMOVE_MONITOR) {
            if (monitor != NULL) {
                monitor->newRepo("");

                delete monitor;
                this->monitors.erase(topicData.monitorId);
            }
            addTopic = false;
            topicValue << "True";
        } else if (topicData.name == MONITOR_ATTACH_INFOREPO) {
            if (monitor != NULL) {
                std::string ior = getSafeArrayElementAsStr(Strings, 2);
                bool success = monitor->newRepo(ior);

                topicValue << (success ? "True" : "False");
            } else {
                topicValue << "False";
            }
            addTopic = false;
        } else if (topicData.name == MONITOR_DETACH_INFOREPO) {
            if (monitor != NULL) {
                bool success = monitor->newRepo("");

                topicValue << (success ? "True" : "False");
            } else {
                topicValue << "True";
            }

            addTopic = false;
        } else if (topicData.name == MONITOR_COLUMN_COUNT) {
            topicValue << (monitor ? monitor->getColumnCount() : 0);

        } else if (topicData.name == MONITOR_IS_NODE_VALID) {
            std::string id = getSafeArrayElementAsStr(Strings, 2);
            topicData.parameters.push_back(id);

            bool isNodeValid = (monitor ? monitor->isNodeValid(id) : false);
            topicValue << (isNodeValid ? "True" : "False");

        } else if (topicData.name == MONITOR_NODE_VALUE) {
            std::string id = getSafeArrayElementAsStr(Strings, 2);
            topicData.parameters.push_back(id);

            std::string indexStr = getSafeArrayElementAsStr(Strings, 3);
            int index = atoi(indexStr.c_str());
            topicData.parameters.push_back(indexStr);

            if (monitor == NULL) {
                topicValue << "#Error: unable to find monitor with id: " << topicData.monitorId;
            } else {
                topicValue << monitor->getNodeValue(id, index);
            }

        } else if (topicData.name == MONITOR_NODE_COLOR) {
            std::string id = getSafeArrayElementAsStr(Strings, 2);
            topicData.parameters.push_back(id);

            std::string indexStr = getSafeArrayElementAsStr(Strings, 3);
            int index = atoi(indexStr.c_str());
            topicData.parameters.push_back(indexStr);

            if (monitor != NULL) {
                topicValue << monitor->getNodeColor(id, index);
            }
        } else if (topicData.name == MONITOR_NODE_CHILDREN) {
            std::string parentId = getSafeArrayElementAsStr(Strings, 2);

            topicData.parameters.push_back(parentId);

            if (monitor == NULL) {
                topicValue << "{}";
            } else {
                topicValue << convertToDelimitedString(monitor->getNodeChildren(parentId));
            }

        } else {
            topicValue << "<unsupported request>";

            hr = E_FAIL;
        }
    }

    if (addTopic) {
        m_pTopicList.insert(TopicList::value_type(TopicID, topicData));
    }

    VariantInit(pvarOut);
    pvarOut->vt = VT_BSTR;

    std::wstring ws;
    std::string s = topicValue.str();
    ws.assign(s.begin(), s.end());

    pvarOut->bstrVal = SysAllocString(ws.c_str());

    return hr;
}
Beispiel #13
0
/***********************************************************************
 *           AtlAxCreateControlEx            [ATL.@]
 *
 * REMARKS
 *   See http://www.codeproject.com/com/cwebpage.asp for some background
 *
 */
HRESULT WINAPI AtlAxCreateControlEx(LPCOLESTR lpszName, HWND hWnd,
        IStream *pStream, IUnknown **ppUnkContainer, IUnknown **ppUnkControl,
        REFIID iidSink, IUnknown *punkSink)
{
    CLSID controlId;
    HRESULT hRes;
    IOleObject *pControl;
    IUnknown *pUnkControl;
    IPersistStreamInit *pPSInit;
    IUnknown *pContainer;
    enum {IsGUID=0,IsHTML=1,IsURL=2} content;

    TRACE("(%s %p %p %p %p %p %p)\n", debugstr_w(lpszName), hWnd, pStream, 
            ppUnkContainer, ppUnkControl, iidSink, punkSink);

    hRes = CLSIDFromString( lpszName, &controlId );
    if ( FAILED(hRes) )
        hRes = CLSIDFromProgID( lpszName, &controlId );
    if ( SUCCEEDED( hRes ) )
        content = IsGUID;
    else {
        /* FIXME - check for MSHTML: prefix! */
        content = IsURL;
        controlId = CLSID_WebBrowser;
    }

    hRes = CoCreateInstance( &controlId, 0, CLSCTX_ALL, &IID_IOleObject, 
            (void**) &pControl );
    if ( FAILED( hRes ) )
    {
        WARN( "cannot create ActiveX control %s instance - error 0x%08x\n",
                debugstr_guid( &controlId ), hRes );
        return hRes;
    }

    hRes = IOleObject_QueryInterface( pControl, &IID_IPersistStreamInit, (void**) &pPSInit );
    if ( SUCCEEDED( hRes ) )
    {
        if (!pStream)
            IPersistStreamInit_InitNew( pPSInit );
        else
            IPersistStreamInit_Load( pPSInit, pStream );
        IPersistStreamInit_Release( pPSInit );
    } else
        WARN("cannot get IID_IPersistStreamInit out of control\n");

    IOleObject_QueryInterface( pControl, &IID_IUnknown, (void**) &pUnkControl );
    IOleObject_Release( pControl );
     

    hRes = AtlAxAttachControl( pUnkControl, hWnd, &pContainer );
    if ( FAILED( hRes ) )
        WARN("cannot attach control to window\n");

    if ( content == IsURL )
    {
        IWebBrowser2 *browser;

        hRes = IOleObject_QueryInterface( pControl, &IID_IWebBrowser2, (void**) &browser );
        if ( !browser )
            WARN( "Cannot query IWebBrowser2 interface: %08x\n", hRes );
        else {
            VARIANT url;
            
            IWebBrowser2_put_Visible( browser, VARIANT_TRUE ); /* it seems that native does this on URL (but do not on MSHTML:! why? */

            V_VT(&url) = VT_BSTR;
            V_BSTR(&url) = SysAllocString( lpszName );

            hRes = IWebBrowser2_Navigate2( browser, &url, NULL, NULL, NULL, NULL );
            if ( FAILED( hRes ) )
                WARN( "IWebBrowser2::Navigate2 failed: %08x\n", hRes );
            SysFreeString( V_BSTR(&url) );

            IWebBrowser2_Release( browser );
        }
    }

    if (ppUnkContainer)
    {
        *ppUnkContainer = pContainer;
        if ( pContainer )
            IUnknown_AddRef( pContainer );
    }
    if (ppUnkControl)
    {
        *ppUnkControl = pUnkControl;
        if ( pUnkControl )
            IUnknown_AddRef( pUnkControl );
    }

    if ( pUnkControl )
        IUnknown_Release( pUnkControl );
    if ( pContainer )
        IUnknown_Release( pContainer );

    return S_OK;
}
Beispiel #14
0
STDMETHODIMP BallEx::get_Name(BSTR *pVal)
{
	*pVal = SysAllocString(L"Ball");
	return S_OK;
}
Beispiel #15
0
BOOL CPropsetPropExchange::ExchangeProp(LPCTSTR pszPropName, VARTYPE vtProp,
	void* pvProp, const void* pvDefault)
{
	USES_CONVERSION;

	ASSERT(AfxIsValidString(pszPropName));
	ASSERT(AfxIsValidAddress(pvProp, 1, FALSE));
	ASSERT((pvDefault == NULL) || AfxIsValidAddress(pvDefault, 1, FALSE));

	BOOL bSuccess = FALSE;

	if (m_bLoading)
	{
		DWORD dwPropID;
		LPVOID pvData;
		CProperty* pprop;

		if (m_psec.GetID(pszPropName, &dwPropID) &&
			((pprop = m_psec.GetProperty(dwPropID)) != NULL) &&
			((pvData = pprop->Get()) != NULL))
		{
			VARTYPE vtData = (VARTYPE)pprop->GetType();

			CString strTmp;

#ifdef _UNICODE
			// Unicode is "native" format
			if ((vtData == VT_BSTR) || (vtData == VT_LPWSTR))
#else
			// ANSI is "native" format
			if ((vtData == VT_BSTR) || (vtData == VT_LPSTR))
#endif
			{
				strTmp = (LPCTSTR)pvData;
			}

#ifdef _UNICODE
			else if (vtData == VT_LPSTR)
			{
				// Convert from ANSI to Unicode
				strTmp = (LPCSTR)pvData;
			}
#else
			else if (vtData == VT_LPWSTR)
			{
				// Convert from Unicode to ANSI
				strTmp = (LPCWSTR)pvData;
			}
#endif

			switch (vtProp)
			{
			case VT_LPSTR:
			case VT_BSTR:
				bSuccess = _AfxCopyPropValue(VT_BSTR, pvProp, &strTmp);
				break;

			case VT_BOOL:
				{
					short sProp;
					BSTR bstrTmp = NULL;

					if ((vtData == VT_BSTR) || (vtData == VT_LPSTR) ||
						(vtData == VT_LPWSTR))
					{
						bstrTmp = SysAllocString(T2COLE(strTmp));
						pvData = &bstrTmp;
						vtData = VT_BSTR;
					}

					bSuccess = _AfxCoerceNumber(&sProp, VT_BOOL, pvData,
						vtData);

					if (bstrTmp != NULL)
						SysFreeString(bstrTmp);

					if (bSuccess)
					{
						ASSERT((sProp == -1) || (sProp == 0));
						*(BOOL*)pvProp = !!sProp;
					}
				}
				break;

			case VT_I2:
			case VT_I4:
			case VT_CY:
			case VT_R4:
			case VT_R8:
				bSuccess = _AfxCoerceNumber(pvProp, vtProp, pvData, vtData);
				break;
			}
		}
		else
		{
			bSuccess = _AfxCopyPropValue(vtProp, pvProp, pvDefault);
		}
	}
	else
	{
		if (!_AfxIsSamePropValue(vtProp, pvProp, pvDefault))
		{
			++m_dwPropID;

			LPVOID pvData = NULL;
			BOOL bData;

			switch (vtProp)
			{
			case VT_LPSTR:
			case VT_BSTR:
				pvData = (LPVOID)(LPCTSTR)*(CString*)pvProp;
				break;

			case VT_BOOL:
				// Convert boolean value to -1 or 0.
				bData = (*(BOOL*)pvProp) ? -1 : 0;
				pvData = &bData;
				break;

			case VT_I2:
			case VT_I4:
			case VT_CY:
			case VT_R4:
			case VT_R8:
				pvData = pvProp;
				break;
			}

			bSuccess = m_psec.SetName(m_dwPropID, pszPropName) &&
				m_psec.Set(m_dwPropID, pvData, vtProp);
		}
		else
		{
			bSuccess = TRUE;
		}
	}

	return bSuccess;
}
// Add a UPnP port
bool Win32UPnPAddPort(UINT outside_port, UINT inside_port, bool udp, char *local_ip, wchar_t *description, bool remove_before_add)
{
	bool ret = false;
	HRESULT hr;
	IUPnPNAT *nat = NULL;
	wchar_t ip_str[MAX_SIZE];
	BSTR bstr_ip, bstr_description, bstr_protocol;
	wchar_t *protocol_str = (udp ? L"UDP" : L"TCP");
	// Validate arguments
	if (outside_port == 0 || outside_port >= 65536 || inside_port == 0 || inside_port >= 65536 ||
		IsEmptyStr(local_ip) || UniIsEmptyStr(description))
	{
		return false;
	}

	StrToUni(ip_str, sizeof(ip_str), local_ip);
	bstr_ip = SysAllocString(ip_str);
	bstr_description = SysAllocString(description);
	bstr_protocol = SysAllocString(protocol_str);

	hr = CoCreateInstance(CLSID_UPnPNAT, NULL, CLSCTX_INPROC_SERVER, IID_IUPnPNAT, (void **)&nat);

	if (SUCCEEDED(hr))
	{
		if (nat != NULL)
		{
			IStaticPortMappingCollection *collection = NULL;
			hr = nat->get_StaticPortMappingCollection(&collection);

			if (SUCCEEDED(hr))
			{
				if (collection != NULL)
				{
					IStaticPortMapping *mapping = NULL;

					if (remove_before_add)
					{
						hr = collection->Remove((long)outside_port, bstr_protocol);
					}

					hr = collection->Add((long)outside_port, bstr_protocol, (long)inside_port,
						bstr_ip, VARIANT_TRUE, bstr_description, &mapping);

					if (SUCCEEDED(hr))
					{
						ret = true;

						if (mapping != NULL)
						{
							mapping->Release();
						}
					}

					collection->Release();
				}
				else
				{
					WHERE;
				}
			}
			else
			{
				WHERE;
			}

			nat->Release();
		}
		else
		{
			WHERE;
		}
	}
	else
	{
		WHERE;
	}

	SysFreeString(bstr_ip);
	SysFreeString(bstr_description);
	SysFreeString(bstr_protocol);

	return ret;
}
HRESULT STDMETHODCALLTYPE TextAreaProvider::GetPropertyValue(PROPERTYID idProp, _Out_ VARIANT * retVal)
{
    if (!IsWindow(_hwnd))
    {
        return UIA_E_ELEMENTNOTAVAILABLE;
    }
    retVal->vt = VT_EMPTY;

    // Returning the default will leave the property as the default
    // so we only really need to touch it for the properties we want to implement
    if (idProp == UIA_ControlTypePropertyId)
    {
        // This control is the Document control type, implying that it is
        // a complex document that supports text pattern
        retVal->vt = VT_I4;
        retVal->lVal = UIA_DocumentControlTypeId;
    }
    else if (idProp == UIA_NamePropertyId)
    {
         // In a production application, this would be localized text.
         retVal->bstrVal = SysAllocString(L"Text Area");
         if (retVal->bstrVal != NULL)
         {
            retVal->vt = VT_BSTR;
         } 
    }
    else if (idProp == UIA_AutomationIdPropertyId)
    {
         retVal->bstrVal = SysAllocString(L"Text Area");
         if (retVal->bstrVal != NULL)
         {
            retVal->vt = VT_BSTR;
         } 
    }
    else if (idProp == UIA_IsControlElementPropertyId)
    {
        retVal->vt = VT_BOOL;
        retVal->boolVal = VARIANT_TRUE;
    }
    else if (idProp == UIA_IsContentElementPropertyId)
    {
        retVal->vt = VT_BOOL;
        retVal->boolVal = VARIANT_TRUE;
    }
    else if (idProp == UIA_IsKeyboardFocusablePropertyId)
    {
        retVal->vt = VT_BOOL;
        retVal->boolVal = VARIANT_FALSE;
    }
    else if (idProp == UIA_HasKeyboardFocusPropertyId)
    {
        retVal->vt = VT_BOOL;
        retVal->boolVal = VARIANT_FALSE;
    }
    else if (idProp == UIA_ProviderDescriptionPropertyId)
    {
        retVal->bstrVal = SysAllocString(L"Microsoft Sample: Uia Document Content Text Area");
        if (retVal->bstrVal != NULL)
        {
            retVal->vt = VT_BSTR;
        }
    }

    return S_OK;
}
Beispiel #18
0
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	Description :
//		Sends WMI command to target after logging on.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
DWORD startWMICommand(char* command, char* target, char* username, char* password)
{	
	HRESULT hres;
	IWbemLocator *pLoc = NULL;
	IWbemServices *pSvc = NULL;
	COAUTHIDENTITY *userAcct =  NULL ;
	COAUTHIDENTITY authIdent;
	char* serverWMIA;
	PWCHAR serverWMIW;
	PWCHAR usernameW;
	PWCHAR commandW;
	PWCHAR passwordW;
	WCHAR pszDomain[CREDUI_MAX_USERNAME_LENGTH+1];
	WCHAR pszUserName[CREDUI_MAX_USERNAME_LENGTH+1];
	PWCHAR slash;
	int len = 0;

	// WCHAR
	len = strlen(target)+12;
	serverWMIA = (char*)malloc(sizeof(char)*(len));
	strcpy_s(serverWMIA, len, target);
	strcat_s(serverWMIA, len, "\\ROOT\\CIMV2");
	len = MultiByteToWideChar(CP_ACP,0,serverWMIA,-1,NULL,0);
	serverWMIW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,serverWMIA,-1,serverWMIW,len);
	free(serverWMIA);
	len = MultiByteToWideChar(CP_ACP,0,username,-1,NULL,0);
	usernameW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,username,-1,usernameW,len);
	len = MultiByteToWideChar(CP_ACP,0,password,-1,NULL,0);
	passwordW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,password,-1,passwordW,len);
	len = MultiByteToWideChar(CP_ACP,0,command,-1,NULL,0);
	commandW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,command,-1,commandW,len);

	hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		return -1;
	}
	hres =  CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_DEFAULT,RPC_C_IMP_LEVEL_IDENTIFY,NULL,EOAC_NONE,NULL);	   
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		CoUninitialize();
		return -1;
	}
	hres = CoCreateInstance(CLSID_WbemLocator,0,CLSCTX_INPROC_SERVER,IID_IWbemLocator, (LPVOID *) &pLoc);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		CoUninitialize();
		return -1;
	}

	//WMI connection
	hres = pLoc->ConnectServer(_bstr_t(serverWMIW),_bstr_t(usernameW),_bstr_t(passwordW),NULL,NULL,NULL,NULL,&pSvc);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}

	//Set ProxyBlanket options
	memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
	authIdent.PasswordLength = wcslen (passwordW);
	authIdent.Password = (USHORT*)passwordW;
	slash = wcschr (usernameW, L'\\');
	if(slash == NULL)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}
	wcscpy_s(pszUserName,CREDUI_MAX_USERNAME_LENGTH+1, slash+1);
	authIdent.User = (USHORT*)pszUserName;
	authIdent.UserLength = wcslen(pszUserName);
	wcsncpy_s(pszDomain, CREDUI_MAX_USERNAME_LENGTH+1, usernameW, slash - usernameW);
	authIdent.Domain = (USHORT*)pszDomain;
	authIdent.DomainLength = slash - usernameW;
	authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
	userAcct = &authIdent;
	
	//Set the ProxyBlanket
	hres = CoSetProxyBlanket(pSvc,RPC_C_AUTHN_DEFAULT,RPC_C_AUTHZ_DEFAULT,COLE_DEFAULT_PRINCIPAL,RPC_C_AUTHN_LEVEL_PKT_PRIVACY,RPC_C_IMP_LEVEL_IMPERSONATE,userAcct,EOAC_NONE);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}


	BSTR MethodName = SysAllocString(L"Create");
	BSTR ClassName = SysAllocString(L"Win32_Process");

	IWbemClassObject* pClass = NULL;
	hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);
	IWbemClassObject* pInParamsDefinition = NULL;
	hres = pClass->GetMethod(MethodName, 0, 
		&pInParamsDefinition, NULL);
	IWbemClassObject* pClassInstance = NULL;
	hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);

	// Create the values for the "in" parameters
	VARIANT varCommand;
	varCommand.vt = VT_BSTR;
	varCommand.bstrVal = BSTR(commandW);

	// Store the value for the "in" parameters
	hres = pClassInstance->Put(L"CommandLine", 0, &varCommand, 0);

	 // Execute Method
	IWbemClassObject* pOutParams = NULL;
	hres = pSvc->ExecMethod(ClassName, MethodName, 0,
	NULL, pClassInstance, &pOutParams, NULL);

	if (FAILED(hres))
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		VariantClear(&varCommand);
		SysFreeString(ClassName);
		SysFreeString(MethodName);
		pClass->Release();
		pInParamsDefinition->Release();
		pOutParams->Release();
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}


	free(usernameW);
	free(passwordW);
	free(commandW);
	free(serverWMIA);
	free(serverWMIW);
	SecureZeroMemory(pszUserName, sizeof(pszUserName));
	SecureZeroMemory(pszDomain, sizeof(pszDomain));
	VariantClear(&varCommand);
	SysFreeString(ClassName);
	SysFreeString(MethodName);
	pClass->Release();
	pInParamsDefinition->Release();
	pOutParams->Release();
	pSvc->Release();
	pLoc->Release();
	CoUninitialize();

	return 0;
}
void prop_kv_config::g_load(t_map & data, stream_reader * reader, abort_callback & abort) throw()
{
	t_size count;

	data.remove_all();

	try
	{
		// Get count
		reader->read_lendian_t(count, abort);

		for (t_size i = 0; i < count; ++i)
		{
			pfc::string8_fast key;
			t_val val;
			VARTYPE vt;
			int cbRead = 0;

			// read key
			reader->read_string(key, abort);
			// read vtype
			reader->read_lendian_t(vt, abort);

			switch (vt)
			{
			case VT_UI1:
			case VT_I1:
				cbRead = sizeof(BYTE);
				break;

			case VT_I2:
			case VT_UI2:
			case VT_BOOL:
				cbRead = sizeof(short);
				break;

			case VT_I4:
			case VT_UI4:
			case VT_R4:
			case VT_INT:
			case VT_UINT:
				cbRead = sizeof(long);
				break;

			case VT_I8:
			case VT_UI8:
				cbRead = sizeof(LONGLONG);
				break;

			case VT_R8:
			case VT_CY:
			case VT_DATE:
				cbRead = sizeof(double);
				break;
			}

			val.vt = vt;

			if (cbRead != 0)
			{
				reader->read(&val.bVal, cbRead, abort);
			}
			else
			{
				// Read to bstr
				pfc::string8_fast str;

				reader->read_string(str, abort);
				val.bstrVal = SysAllocString(pfc::stringcvt::string_wide_from_utf8_fast(str));
			}

			data[key] = val;
		}
	}
	catch (std::exception &)
	{

	}
}
Beispiel #20
0
static void test_wshshell(void)
{
    static const WCHAR desktopW[] = {'D','e','s','k','t','o','p',0};
    static const WCHAR lnk1W[] = {'f','i','l','e','.','l','n','k',0};
    IWshShell3 *sh3;
    IDispatchEx *dispex;
    IWshCollection *coll;
    IDispatch *disp, *shortcut;
    IUnknown *shell, *unk;
    IFolderCollection *folders;
    ITypeInfo *ti;
    HRESULT hr;
    TYPEATTR *tattr;
    DISPPARAMS dp;
    EXCEPINFO ei;
    VARIANT arg, res;
    BSTR str;
    UINT err;

    hr = CoCreateInstance(&CLSID_WshShell, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER,
            &IID_IDispatch, (void**)&disp);
    if(FAILED(hr)) {
        win_skip("Could not create WshShell object: %08x\n", hr);
        return;
    }

    hr = IDispatch_QueryInterface(disp, &IID_IWshShell3, (void**)&shell);
    EXPECT_HR(hr, S_OK);
    IDispatch_Release(disp);

    hr = IDispatch_QueryInterface(disp, &IID_IDispatchEx, (void**)&dispex);
    EXPECT_HR(hr, E_NOINTERFACE);

    hr = IDispatch_QueryInterface(shell, &IID_IWshShell3, (void**)&sh3);
    EXPECT_HR(hr, S_OK);

    hr = IWshShell3_get_SpecialFolders(sh3, &coll);
    EXPECT_HR(hr, S_OK);

    hr = IWshCollection_QueryInterface(coll, &IID_IFolderCollection, (void**)&folders);
    EXPECT_HR(hr, E_NOINTERFACE);

    hr = IWshCollection_QueryInterface(coll, &IID_IDispatch, (void**)&disp);
    EXPECT_HR(hr, S_OK);

    hr = IDispatch_GetTypeInfo(disp, 0, 0, &ti);
    EXPECT_HR(hr, S_OK);

    hr = ITypeInfo_GetTypeAttr(ti, &tattr);
    EXPECT_HR(hr, S_OK);
    ok(IsEqualIID(&tattr->guid, &IID_IWshCollection), "got wrong type guid\n");
    ITypeInfo_ReleaseTypeAttr(ti, tattr);

    /* try to call Item() with normal IDispatch procedure */
    str = SysAllocString(desktopW);
    V_VT(&arg) = VT_BSTR;
    V_BSTR(&arg) = str;
    dp.rgvarg = &arg;
    dp.rgdispidNamedArgs = NULL;
    dp.cArgs = 1;
    dp.cNamedArgs = 0;
    hr = IDispatch_Invoke(disp, DISPID_VALUE, &IID_NULL, 1033, DISPATCH_PROPERTYGET, &dp, &res, &ei, &err);
    EXPECT_HR(hr, DISP_E_MEMBERNOTFOUND);

    /* try Item() directly, it returns directory path apparently */
    V_VT(&res) = VT_EMPTY;
    hr = IWshCollection_Item(coll, &arg, &res);
    EXPECT_HR(hr, S_OK);
    ok(V_VT(&res) == VT_BSTR, "got res type %d\n", V_VT(&res));
    SysFreeString(str);
    VariantClear(&res);

    /* CreateShortcut() */
    str = SysAllocString(lnk1W);
    hr = IWshShell3_CreateShortcut(sh3, str, &shortcut);
    EXPECT_HR(hr, S_OK);
    SysFreeString(str);
    hr = IDispatch_QueryInterface(shortcut, &IID_IWshShortcut, (void**)&unk);
    EXPECT_HR(hr, S_OK);
    IUnknown_Release(unk);
    IDispatch_Release(shortcut);

    IWshCollection_Release(coll);
    IDispatch_Release(disp);
    IWshShell3_Release(sh3);
    IUnknown_Release(shell);
}
Beispiel #21
0
/// <summary>
/// Loads and invokes the managed portion of the proxy.
/// </summary>
/// <param name="hSession">Handle to the installer session,
/// used for logging errors and to be passed on to the custom action.</param>
/// <param name="pAppDomain">AppDomain which has its application
/// base set to the CA working directory.</param>
/// <param name="szEntryPoint">Name of the CA entrypoint to be invoked.
/// This must be either an explicit &quot;AssemblyName!Namespace.Class.Method&quot;
/// string, or a simple name that maps to a full entrypoint definition
/// in CustomAction.config.</param>
/// <param name="piResult">Return value of the invoked custom
/// action method.</param>
/// <returns>True if the managed proxy was invoked successfully,
/// false if there was some error. Note the custom action itself may
/// return an error via piResult while this method still returns true
/// since the invocation was successful.</returns>
bool InvokeManagedCustomAction(MSIHANDLE hSession, _AppDomain* pAppDomain,
        const wchar_t* szEntryPoint, int* piResult)
{
        VARIANT vResult;
        ::VariantInit(&vResult);

        const bool f64bit = (sizeof(void*) == sizeof(LONGLONG));
        const wchar_t* szMsiAssemblyName   = L"Microsoft.Deployment.WindowsInstaller";
        const wchar_t* szMsiCAProxyClass   = L"Microsoft.Deployment.WindowsInstaller.CustomActionProxy";
        const wchar_t* szMsiCAInvokeMethod = (f64bit ? L"InvokeCustomAction64" : L"InvokeCustomAction32");
        
        _MethodInfo* pCAInvokeMethod;
        if (!GetMethod(hSession, pAppDomain, szMsiAssemblyName,
                szMsiCAProxyClass, szMsiCAInvokeMethod, &pCAInvokeMethod))
        {
                return false;
        }

        HRESULT hr;
        VARIANT vNull;
        vNull.vt = VT_EMPTY;
        SAFEARRAY* saArgs = SafeArrayCreateVector(VT_VARIANT, 0, 3);
        VARIANT vSessionHandle;
        vSessionHandle.vt = VT_I4;
        vSessionHandle.intVal = hSession;
        LONG index = 0;
        hr = SafeArrayPutElement(saArgs, &index, &vSessionHandle);
        if (FAILED(hr)) goto LExit;
        VARIANT vEntryPoint;
        vEntryPoint.vt = VT_BSTR;
        vEntryPoint.bstrVal = SysAllocString(szEntryPoint);
        if (vEntryPoint.bstrVal == NULL)
        {
                hr = E_OUTOFMEMORY;
                goto LExit;
        }
        index = 1;
        hr = SafeArrayPutElement(saArgs, &index, &vEntryPoint);
        if (FAILED(hr)) goto LExit;
        VARIANT vRemotingFunctionPtr;
#pragma warning(push)
#pragma warning(disable:4127) // conditional expression is constant
        if (f64bit)
#pragma warning(pop)
        {
                vRemotingFunctionPtr.vt =  VT_I8;
                vRemotingFunctionPtr.llVal = (LONGLONG) (g_fRunningOutOfProc ? MsiRemoteInvoke : NULL);
        }
        else
        {
                vRemotingFunctionPtr.vt =  VT_I4;
#pragma warning(push)
#pragma warning(disable:4302) // truncation
#pragma warning(disable:4311) // pointer truncation
                vRemotingFunctionPtr.lVal = (LONG) (g_fRunningOutOfProc ? MsiRemoteInvoke : NULL);
#pragma warning(pop)
        }
        index = 2;
        hr = SafeArrayPutElement(saArgs, &index, &vRemotingFunctionPtr);
        if (FAILED(hr)) goto LExit;
        
        hr = pCAInvokeMethod->Invoke_3(vNull, saArgs, &vResult);

LExit:
        SafeArrayDestroy(saArgs);
        pCAInvokeMethod->Release();
        
        if (FAILED(hr))
        {
                Log(hSession, L"Failed to invoke custom action method. Error code 0x%X", hr);
                return false;
        }

        *piResult = vResult.intVal;
        return true;
}
Beispiel #22
0
STDMETHODIMP CWinMergeScript::get_PluginEvent(BSTR *pVal)
{
	*pVal = SysAllocString(L"BUFFER_PREDIFF");
	return S_OK;
}
static bool IsIcfEnabled(void)
{
	HRESULT hr;
	VARIANT_BOOL fwEnabled = VARIANT_FALSE;

	INetFwProfile* fwProfile = NULL;
	INetFwMgr* fwMgr = NULL;
	INetFwPolicy* fwPolicy = NULL;
	INetFwAuthorizedApplication* fwApp = NULL;
	INetFwAuthorizedApplications* fwApps = NULL;
	BSTR fwBstrProcessImageFileName = NULL;
	wchar_t *wszFileName = NULL;

	hr = CoInitialize(NULL);
	if (FAILED(hr)) return false;

	// Create an instance of the firewall settings manager.
	hr = CoCreateInstance(CLSID_NetFwMgr, NULL, CLSCTX_INPROC_SERVER,
			IID_INetFwMgr, (void**)&fwMgr );
	if (FAILED(hr)) goto error;

	// Retrieve the local firewall policy.
	hr = fwMgr->get_LocalPolicy(&fwPolicy);
	if (FAILED(hr)) goto error;

	// Retrieve the firewall profile currently in effect.
	hr = fwPolicy->get_CurrentProfile(&fwProfile);
	if (FAILED(hr)) goto error;

	// Get the current state of the firewall.
	hr = fwProfile->get_FirewallEnabled(&fwEnabled);
	if (FAILED(hr)) goto error;

	if (fwEnabled == VARIANT_FALSE) goto error;

	// Retrieve the authorized application collection.
	hr = fwProfile->get_AuthorizedApplications(&fwApps);
	if (FAILED(hr)) goto error;

	TCHAR szFileName[MAX_PATH];
	GetModuleFileName(NULL, szFileName, SIZEOF(szFileName));

	wszFileName = mir_t2u(szFileName);

	// Allocate a BSTR for the process image file name.
	fwBstrProcessImageFileName = SysAllocString(wszFileName);
	if (FAILED(hr)) goto error;

	// Attempt to retrieve the authorized application.
	hr = fwApps->Item(fwBstrProcessImageFileName, &fwApp);
	if (SUCCEEDED(hr))
	{
		// Find out if the authorized application is enabled.
		fwApp->get_Enabled(&fwEnabled);
		fwEnabled = ~fwEnabled;
	}

error:
	// Free the BSTR.
	SysFreeString(fwBstrProcessImageFileName);
	mir_free(wszFileName);

	// Release the authorized application instance.
	if (fwApp != NULL) fwApp->Release();

	// Release the authorized application collection.
	if (fwApps != NULL) fwApps->Release();

	// Release the firewall profile.
	if (fwProfile != NULL) fwProfile->Release();

	// Release the local firewall policy.
	if (fwPolicy != NULL) fwPolicy->Release();

	// Release the firewall settings manager.
	if (fwMgr != NULL) fwMgr->Release();

	CoUninitialize();

	return fwEnabled != VARIANT_FALSE;
}
Beispiel #24
0
STDMETHODIMP CWinMergeScript::get_PluginDescription(BSTR *pVal)
{
	*pVal = SysAllocString(L"Ignore some fields - ignored fields list from the plugin name");
	return S_OK;
}
Beispiel #25
0
HRESULT
GetElementBoolProperty(
    IN IAppHostElement * pElement,
    IN LPCWSTR           pszPropertyName,
    OUT BOOL *           pBool
)
{
    HRESULT hr = S_OK;
    BSTR    bstrPropertyName = NULL;
    IAppHostProperty * pProperty = NULL;
    VARIANT            varValue;

    VariantInit( &varValue );

    bstrPropertyName = SysAllocString( pszPropertyName );
    if ( bstrPropertyName == NULL )
    {
        hr = E_OUTOFMEMORY;
        DBGERROR_HR(hr);
        goto exit;
    }

    // Now ask for the property and if it succeeds it is returned directly back.
    hr = pElement->GetPropertyByName( bstrPropertyName, &pProperty );
    if ( FAILED ( hr ) )
    {
       goto exit;
    }

    // Now let's get the property and then extract it from the Variant.
    hr = pProperty->get_Value( &varValue );
    if ( FAILED ( hr ) )
    {
         goto exit;
    }

    hr = VariantChangeType( &varValue, &varValue, 0, VT_BOOL );
    if ( FAILED ( hr ) )
    {
         goto exit;
    }

    // extract the value
    *pBool = ( V_BOOL( &varValue ) == VARIANT_TRUE );

exit:

    VariantClear( &varValue );

    if ( bstrPropertyName != NULL )
    {
        SysFreeString( bstrPropertyName );
        bstrPropertyName = NULL;
    }

    if ( pProperty != NULL )
    {
        pProperty->Release();
        pProperty = NULL;
    }

    return hr;

}
Beispiel #26
0
// not used yet
STDMETHODIMP CWinMergeScript::get_PluginFileFilters(BSTR *pVal)
{
	*pVal = SysAllocString(L"\\.csv$");
	return S_OK;
}
Beispiel #27
0
HRESULT
GetElementRawTimeSpanProperty(
    IN IAppHostElement * pElement,
    IN LPCWSTR           pszPropertyName,
    OUT ULONGLONG *      pulonglong
)
{
    HRESULT hr = S_OK;
    BSTR    bstrPropertyName = NULL;
    IAppHostProperty * pProperty = NULL;
    VARIANT            varValue;

    VariantInit( &varValue );

    bstrPropertyName = SysAllocString( pszPropertyName );
    if ( bstrPropertyName == NULL )
    {
        hr = HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY );
        goto Finished;
    }

    // Now ask for the property and if it succeeds it is returned directly back
    hr = pElement->GetPropertyByName( bstrPropertyName, &pProperty );
    if ( FAILED ( hr ) )
    {
       goto Finished;
    }

    // Now let's get the property and then extract it from the Variant.
    hr = pProperty->get_Value( &varValue );
    if ( FAILED ( hr ) )
    {
         goto Finished;
    }

    hr = VariantChangeType( &varValue, &varValue, 0, VT_UI8 );
    if ( FAILED ( hr ) )
    {
         goto Finished;
    }

    // extract the value
    *pulonglong = varValue.ullVal;


Finished:

    VariantClear( &varValue );

    if ( bstrPropertyName != NULL )
    {
        SysFreeString( bstrPropertyName );
        bstrPropertyName = NULL;
    }

    if ( pProperty != NULL )
    {
        pProperty->Release();
        pProperty = NULL;
    }

    return hr;

} // end of Config_GetRawTimeSpanProperty
Beispiel #28
0
void PDBFileReader::ReadEverything(DebugInfo &to)
{
  ULONG celt;
  
  Contribs = 0;
  nContribs = 0;
  
  // read section table
  IDiaEnumTables *enumTables;
  if(Session->getEnumTables(&enumTables) == S_OK)
  {
    VARIANT vIndex;
    vIndex.vt = VT_BSTR;
    vIndex.bstrVal = SysAllocString(L"Sections");

    IDiaTable *secTable;
    if(enumTables->Item(vIndex,&secTable) == S_OK)
    {
      LONG count;

      secTable->get_Count(&count);
      Contribs = new SectionContrib[count];
      nContribs = 0;

      IDiaSectionContrib *item;
      while(SUCCEEDED(secTable->Next(1,(IUnknown **)&item,&celt)) && celt == 1)
      {
        SectionContrib &contrib = Contribs[nContribs++];

        item->get_addressOffset(&contrib.Offset);
        item->get_addressSection(&contrib.Section);
        item->get_length(&contrib.Length);
        item->get_compilandId(&contrib.Compiland);

				BOOL code=FALSE,initData=FALSE,uninitData=FALSE;
				item->get_code(&code);
				item->get_initializedData(&initData);
				item->get_uninitializedData(&uninitData);

				if(code && !initData && !uninitData)
					contrib.Type = DIC_CODE;
				else if(!code && initData && !uninitData)
					contrib.Type = DIC_DATA;
				else if(!code && !initData && uninitData)
					contrib.Type = DIC_BSS;
				else
					contrib.Type = DIC_UNKNOWN;

				BSTR objFileName = 0;
				
				IDiaSymbol *compiland = 0;
				item->get_compiland(&compiland);
				if(compiland)
				{
					compiland->get_name(&objFileName);
					compiland->Release();
				}

				sChar *objFileStr = BStrToString(objFileName,"<noobjfile>");
				contrib.ObjFile = to.GetFileByName(objFileStr);

				delete[] objFileStr;
				if(objFileName)
					SysFreeString(objFileName);

        item->Release();
      }

      secTable->Release();
    }

    SysFreeString(vIndex.bstrVal);
    enumTables->Release();
  }

  // enumerate symbols by (virtual) address
  IDiaEnumSymbolsByAddr *enumByAddr;
  if(SUCCEEDED(Session->getSymbolsByAddr(&enumByAddr)))
  {
    IDiaSymbol *symbol;
    // get first symbol to get first RVA (argh)
    if(SUCCEEDED(enumByAddr->symbolByAddr(1,0,&symbol)))
    {
      DWORD rva;
      if(symbol->get_relativeVirtualAddress(&rva) == S_OK)
      {
        symbol->Release();

        // now, enumerate by rva.
        if(SUCCEEDED(enumByAddr->symbolByRVA(rva,&symbol)))
        {
          do
          {
            ProcessSymbol(symbol,to);
            symbol->Release();

            if(FAILED(enumByAddr->Next(1,&symbol,&celt)))
              break;
          }
          while(celt == 1);
        }
      }
      else
        symbol->Release();
    }

    enumByAddr->Release();
  }

  // clean up
  delete[] Contribs;
}
HRESULT STDMETHODCALLTYPE C[!output Safe_root]::RefreshLicense( 
   DWORD dwCookie,
   VARIANT_BOOL fLocal,
   BSTR bstrURL,
   WMPStreamingType type,
   ULONG contentID,
   BSTR bstrRefreshReason,
   VARIANT *pReasonContext)
{
   REFRESH_LICENSE_CONTEXT* pRefrLicCtx = NULL; 
   BOOL postResult = 0;
   HRESULT hr = S_OK;
   
   if(NULL == bstrURL || NULL == bstrRefreshReason || NULL == pReasonContext)
   {
      hr = E_INVALIDARG;
      goto cleanup;
   }

   // If the refresh-license thread has not already been started,
   // start it now.
   
   if(0 == m_refreshLicenseThreadHandle)
   {  
      hr = this->StartContentPartnerThread(ThreadTypeRefreshLicense);

      if(FAILED(hr))
      {
         ATLTRACE2("%x: RefreshLicense: StartContentPartnerThread failed. %x\n", GetCurrentThreadId(), hr);
         goto cleanup;
      } 
      
      ATLTRACE2("%x: RefreshLicense: StartContentPartnerThread succeeded.\n", GetCurrentThreadId());     
   }

   // At this point, we khow the refresh-license thread started, but
   // we don't know whether it is still active.

   // When we post a refresh-license message, we must provide
   // all the information we were passed in the seven parameters
   // of this method. So we copy the seven parameters into a
   // REFRESH_LICENSE_CONTEXT structure.

   pRefrLicCtx = new REFRESH_LICENSE_CONTEXT();
   // This memory is freed in HandleMessageForRefreshLicenseThread.

   if(NULL == pRefrLicCtx)
   {
      ATLTRACE2("%x: RefreshLicense: Failed to create new REFRESH_LICENSE_CONTEXT.\n", GetCurrentThreadId());
      hr = E_OUTOFMEMORY;
      goto cleanup;
   }

   ZeroMemory(pRefrLicCtx, sizeof(REFRESH_LICENSE_CONTEXT));

   pRefrLicCtx->dwCookie = dwCookie;
   pRefrLicCtx->fLocal = fLocal;

   pRefrLicCtx->bstrURL = SysAllocString(bstrURL);
   // This memory is freed in HandleMessageForRefreshLicenseThread. 

   pRefrLicCtx->type = type;
   pRefrLicCtx->contentID = contentID;

   pRefrLicCtx->bstrRefreshReason = SysAllocString(bstrRefreshReason);
   // This memory is freed in HandleMessageForRefreshLicenseThread. 

   VariantInit(pRefrLicCtx->pReasonContext);
   VariantCopy(pRefrLicCtx->pReasonContext, pReasonContext);
   // This memory is freed in HandleMessageForRefreshLicenseThread. 

   // If the refresh-license thread is not active, the following
   // call to PostThreadMessage will fail.

   postResult = PostThreadMessage(
      m_refreshLicenseThreadId,
      m_msgRefreshLicense,
      0,
      reinterpret_cast<LPARAM>(pRefrLicCtx) );

   if(0 == postResult)
   {     
      hr = HRESULT_FROM_WIN32(GetLastError()); 
      ATLTRACE2("%x: RefreshLicense: PostThreadMessage failed. %x\n", GetCurrentThreadId(), hr);
      goto cleanup;
   }
  
   ATLTRACE2("%x: RefreshLicense: PostThreadMessage succeeded.\n", GetCurrentThreadId());

   // We successfully posted the message to the refresh-license thread.
   // We have no more need for the pointer to the refresh-license context.
   pRefrLicCtx = NULL;

   // The refresh-license thread must free the memory 
   // that pRefrLicCtx pointed to previously.

   
cleanup:

   if(pRefrLicCtx)
   {
      // We failed to post a message to the refresh-license thread.
      // The refresh-license thread will not be able to free the memory
      // pointed to by pRefrLicCtx.  So we free it here.
      SysFreeString(pRefrLicCtx->bstrURL);
      SysFreeString(pRefrLicCtx->bstrRefreshReason);
      VariantClear(pRefrLicCtx->pReasonContext);
      delete pRefrLicCtx;
      pRefrLicCtx = NULL;
   }

   // If pRefrLicCtx is NULL, refresh-license thread will free the memory 
   // pointed to by pRefrLicCtx.  

   return hr;
}
Beispiel #30
0
bool Common::isXInputController( const GUID* pGuidProductFromDirectInput )
{
    IWbemLocator*           pIWbemLocator  = NULL;
    IEnumWbemClassObject*   pEnumDevices   = NULL;
    IWbemClassObject*       pDevices[20]   = {0};
    IWbemServices*          pIWbemServices = NULL;
    BSTR                    bstrNamespace  = NULL;
    BSTR                    bstrDeviceID   = NULL;
    BSTR                    bstrClassName  = NULL;
    DWORD                   uReturned      = 0;
    bool                    bIsXinputDevice= false;
    UINT                    iDevice        = 0;
    VARIANT                 var;
    HRESULT                 hr;

//unsigned int t0 = Time::getTimeAsMilliseconds();

    // CoInit if needed
    hr = CoInitialize(NULL);
	bool bCleanupCOM = SUCCEEDED(hr);

//unsigned int t1 = Time::getTimeAsMilliseconds();

    // Create WMI
    hr = CoCreateInstance( __uuidof(WbemLocator),
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           __uuidof(IWbemLocator),
                           (LPVOID*) &pIWbemLocator);
    if( FAILED(hr) || pIWbemLocator == NULL )
        goto LCleanup;
//unsigned int t2 = Time::getTimeAsMilliseconds();
    bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );if( bstrNamespace == NULL ) goto LCleanup;        
    bstrClassName = SysAllocString( L"Win32_PNPEntity" );   if( bstrClassName == NULL ) goto LCleanup;        
    bstrDeviceID  = SysAllocString( L"DeviceID" );          if( bstrDeviceID == NULL )  goto LCleanup;        
    
    // Connect to WMI 
    hr = pIWbemLocator->ConnectServer( bstrNamespace, NULL, NULL, 0L, 
                                       0L, NULL, NULL, &pIWbemServices );
    if( FAILED(hr) || pIWbemServices == NULL )
        goto LCleanup;
//unsigned int t3 = Time::getTimeAsMilliseconds();
    // Switch security level to IMPERSONATE. 
    CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, 
                       RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE );                    

    hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, NULL, &pEnumDevices ); 
    if( FAILED(hr) || pEnumDevices == NULL )
        goto LCleanup;
//unsigned int t4 = Time::getTimeAsMilliseconds();
    // Loop over all devices
    for( ;; )
    {
        // Get 20 at a time
        hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned );
        if( FAILED(hr) )
            goto LCleanup;
        if( uReturned == 0 )
            break;

        for( iDevice=0; iDevice<uReturned; iDevice++ )
        {
            // For each device, get its device ID
            hr = pDevices[iDevice]->Get( bstrDeviceID, 0L, &var, NULL, NULL );
            if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL )
            {
                // Check if the device ID contains "IG_".  If it does, then it's an XInput device
				    // This information can not be found from DirectInput 
                if( wcsstr( var.bstrVal, L"IG_" ) )
                {
                    // If it does, then get the VID/PID from var.bstrVal
                    DWORD dwPid = 0, dwVid = 0;
                    WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" );
#ifdef _MSC_VER
	#pragma warning( push )
	#pragma warning ( disable : 4996 )
#endif
                    if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )
                        dwVid = 0;
                    WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" );
                    if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )
                        dwPid = 0;
#ifdef _MSC_VER
	#pragma warning(pop)
#endif
                    // Compare the VID/PID to the DInput device
                    DWORD dwVidPid = MAKELONG( dwVid, dwPid );
                    if( dwVidPid == pGuidProductFromDirectInput->Data1 )
                    {
                        bIsXinputDevice = true;
                        goto LCleanup;
                    }
                }
            }   
            SAFE_RELEASE( pDevices[iDevice] );
        }
    }
LCleanup:
//unsigned int t5 = Time::getTimeAsMilliseconds();
    if(bstrNamespace)
        SysFreeString(bstrNamespace);
    if(bstrDeviceID)
        SysFreeString(bstrDeviceID);
    if(bstrClassName)
        SysFreeString(bstrClassName);
    for( iDevice=0; iDevice<20; iDevice++ )
        SAFE_RELEASE( pDevices[iDevice] );
    SAFE_RELEASE( pEnumDevices );
    SAFE_RELEASE( pIWbemLocator );
    SAFE_RELEASE( pIWbemServices );

    if( bCleanupCOM )
		CoUninitialize();
//unsigned int t6 = Time::getTimeAsMilliseconds();

/*t1 = t1-t0;
t2 = t2-t0;
t3 = t3-t0;
t4 = t4-t0;
t5 = t5-t0;
t6 = t6-t0;
t0 = 0;
*/
    return bIsXinputDevice;
}