Esempio n. 1
0
static void test_select( IWbemServices *services )
{
    static const WCHAR emptyW[] = {0};
    static const WCHAR sqlW[] = {'S','Q','L',0};
    static const WCHAR query1[] =
    {   'S','E','L','E','C','T',' ','H','O','T','F','I','X','I','D',' ','F','R','O','M',' ',
        'W','i','n','3','2','_','Q','u','i','c','k','F','i','x','E','n','g','i','n','e','e','r','i','n','g',0
    };
    static const WCHAR query2[] =
    {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','W','i','n','3','2','_','B','I','O','S',0};
    static const WCHAR query3[] =
    {   'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','W','i','n','3','2','_',
        'L','o','g','i','c','a','l','D','i','s','k',' ','W','H','E','R','E',' ',
        '\"','N','T','F','S','\"',' ','=',' ','F','i','l','e','S','y','s','t','e','m',0
    };
    static const WCHAR query4[] =
    {'S','E','L','E','C','T',' ','a',' ','F','R','O','M',' ','b',0};
    static const WCHAR query5[] =
    {'S','E','L','E','C','T',' ','a',' ','F','R','O','M',' ','W','i','n','3','2','_','B','i','o','s',0};
    static const WCHAR query6[] =
    {   'S','E','L','E','C','T',' ','D','e','s','c','r','i','p','t','i','o','n',' ','F','R','O','M',' ',
        'W','i','n','3','2','_','B','i','o','s',0
    };
    static const WCHAR query7[] =
    {   'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','W','i','n','3','2','_',
        'P','r','o','c','e','s','s',' ','W','H','E','R','E',' ','C','a','p','t','i','o','n',' ',
        'L','I','K','E',' ','\'','%','%','R','E','G','E','D','I','T','%','\'',0
    };
    static const WCHAR query8[] =
    {   'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','W','i','n','3','2','_',
        'D','i','s','k','D','r','i','v','e',' ','W','H','E','R','E',' ','D','e','v','i','c','e','I','D','=',
        '\"','\\','\\','\\','\\','.','\\','\\','P','H','Y','S','I','C','A','L','D','R','I','V','E','0','\"',0
    };
    static const WCHAR query9[] =
    {'S','E','L','E','C','T','\n','a','\r','F','R','O','M','\t','b',0};
    static const WCHAR query10[] =
    {   'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','W','i','n','3','2','_',
        'P','r','o','c','e','s','s',' ','W','H','E','R','E',' ','C','a','p','t','i','o','n',' ',
        'L','I','K','E',' ','"','%','f','i','r','e','f','o','x','.','e','x','e','"',0
    };
    static const WCHAR query11[] =
    {   'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        'W','i','n','3','2','_','V','i','d','e','o','C','o','n','t','r','o','l','l','e','r',' ','w','h','e','r','e',' ',
        'a','v','a','i','l','a','b','i','l','i','t','y',' ','=',' ','\'','3','\'',0
    };
    static const WCHAR *test[] = { query1, query2, query3, query4, query5, query6, query7, query8, query9, query10,
                                   query11
                                 };
    HRESULT hr;
    IEnumWbemClassObject *result;
    BSTR wql = SysAllocString( wqlW );
    BSTR sql = SysAllocString( sqlW );
    BSTR query = SysAllocString( query1 );
    UINT i;

    hr = IWbemServices_ExecQuery( services, NULL, NULL, 0, NULL, &result );
    ok( hr == WBEM_E_INVALID_PARAMETER, "query failed %08x\n", hr );

    hr = IWbemServices_ExecQuery( services, NULL, query, 0, NULL, &result );
    ok( hr == WBEM_E_INVALID_PARAMETER, "query failed %08x\n", hr );

    hr = IWbemServices_ExecQuery( services, wql, NULL, 0, NULL, &result );
    ok( hr == WBEM_E_INVALID_PARAMETER, "query failed %08x\n", hr );

    hr = IWbemServices_ExecQuery( services, sql, query, 0, NULL, &result );
    ok( hr == WBEM_E_INVALID_QUERY_TYPE, "query failed %08x\n", hr );

    hr = IWbemServices_ExecQuery( services, sql, NULL, 0, NULL, &result );
    ok( hr == WBEM_E_INVALID_PARAMETER, "query failed %08x\n", hr );

    SysFreeString( query );
    query = SysAllocString( emptyW );
    hr = IWbemServices_ExecQuery( services, wql, query, 0, NULL, &result );
    ok( hr == WBEM_E_INVALID_PARAMETER, "query failed %08x\n", hr );

    for (i = 0; i < sizeof(test)/sizeof(test[0]); i++)
    {
        hr = exec_query( services, test[i], &result );
        ok( hr == S_OK, "query %u failed: %08x\n", i, hr );
        if (result) IEnumWbemClassObject_Release( result );
    }

    SysFreeString( wql );
    SysFreeString( sql );
    SysFreeString( query );
}
Esempio n. 2
0
bool tLuaCOM::getFUNCDESC(const char *name, FuncInfo& funcinfo)
{
  // First, tries to see we have the FUNCDESC's cached

  long counter = 0;

  for(counter = 0; counter < MAX_FUNCINFOS; counter++)
  {
    // when .name is NULL, there is no further information
    if(pFuncInfo[counter].name == NULL)
      break;

    if(strcmp(name, pFuncInfo[counter].name) == 0)
      break;
  }

  // checks whether funcinfo was found
  if(counter < MAX_FUNCINFOS && pFuncInfo[counter].name != NULL)
  {
    funcinfo = pFuncInfo[counter];
    return true;
  }

  // did not find, so gets type information through
  // ITypeComp

  HRESULT hr = S_OK;
  BINDPTR bindptr;
  DESCKIND desckind;
  BSTR wName;
  ITypeInfo *info = NULL;

  unsigned int dumb = 0;

  wName = tUtil::string2bstr(name);

  unsigned long lhashval = LHashValOfName(LOCALE_SYSTEM_DEFAULT, wName);

  hr = ptcomp->Bind(wName, lhashval, INVOKE_PROPERTYGET,
    &info, &desckind, &bindptr);
  
  if(FAILED(hr) || desckind == DESCKIND_NONE)
    funcinfo.propget = NULL;
  else
  {
    funcinfo.propget = bindptr.lpfuncdesc;
    info->Release();
  }

  hr = ptcomp->Bind(wName, lhashval, INVOKE_FUNC,
    &info, &desckind, &bindptr);
  
  if(FAILED(hr) || desckind == DESCKIND_NONE)
    funcinfo.func = NULL;
  else
  {
    funcinfo.func = bindptr.lpfuncdesc;
    info->Release();
  }


  hr = ptcomp->Bind(wName, lhashval, INVOKE_PROPERTYPUT,
    &info, &desckind, &bindptr);
  
  if(FAILED(hr) || desckind == DESCKIND_NONE)
    funcinfo.propput = NULL;
  else
  {
    funcinfo.propput = bindptr.lpfuncdesc;
    info->Release();
  }

  // if there is not propertyput, then tries propputref

  if(funcinfo.propput == NULL)
  {
    hr = ptcomp->Bind(wName, lhashval, INVOKE_PROPERTYPUTREF,
      &info, &desckind, &bindptr);

    if(FAILED(hr) || desckind == DESCKIND_NONE)
      funcinfo.propput = NULL;
    else
    {
      funcinfo.propput = bindptr.lpfuncdesc;
      info->Release();
    }
  }

  SysFreeString(wName);

  // If no type information found, returns NULL
  if(!funcinfo.propget && !funcinfo.propput && !funcinfo.func)
    return false;
  else if(counter < MAX_FUNCINFOS)
  {
    CHECKPRECOND(pFuncInfo[counter].name == NULL);

    pFuncInfo[counter].name = tUtil::strdup(name);

    pFuncInfo[counter].propget  = funcinfo.propget;
    pFuncInfo[counter].propput  = funcinfo.propput;
    pFuncInfo[counter].func     = funcinfo.func;

    return true;
  }
  else
    return true;
}
Esempio n. 3
0
/**
 * Gets the switch port info from WMI (switch port friendly name, ifSpeed) 
 * and merges into the list of existing ports.
 */
void readWMISwitchPorts(HSP *sp)
{
	myLog(LOG_INFO, "entering readWMISwitchPorts");
	BSTR path = SysAllocString(WMI_VIRTUALIZATION_NS_V2);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	if (FAILED(hr)) {
		//only try the v2 namespace since this will only be present
		//with the extensible switch that supports sampling.
	    //don't try to get counters if there is no sampling.
		SysFreeString(path);
		myLog(LOG_INFO, "readWMISwitchPorts: virtualization namespace v2 not found");
		return;
	} else {
		SysFreeString(path);
	}

	BSTR queryLang = SysAllocString(L"WQL");
	BSTR query = SysAllocString(L"SELECT * FROM Msvm_EthernetSwitchPort");
	IEnumWbemClassObject *switchPortEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &switchPortEnum);
	SysFreeString(queryLang);
	SysFreeString(query);
	if (FAILED(hr)) {
		myLog(LOG_ERR,"readWMISwitchPorts: ExecQuery() failed for query %S error=0x%x", query, hr);
		CoUninitialize();
		return;
	}

	if (sp->vAdaptorList == NULL) {
		sp->vAdaptorList = adaptorListNew();
	}
	IWbemClassObject *switchPortObj = NULL;

	BSTR propElementName = SysAllocString(L"ElementName");
	BSTR propSystemName = SysAllocString(L"SystemName");
	BSTR propName = SysAllocString(L"Name");
	BSTR propSpeed = SysAllocString(L"Speed");
	//could also get ifDirection but FullDuplex=True always
	VARIANT systemVal;
	VARIANT elementVal;
	VARIANT nameVal;
	VARIANT speedVal;

	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		SFLAdaptor *vAdaptor = NULL;
		ULONG uReturned = 1;
		hr = switchPortEnum->Next(WBEM_INFINITE, 1, &switchPortObj, &uReturned);
		if (0 == uReturned) {
			break;
		}
		HRESULT portHr;
		portHr = switchPortObj->Get(propName, 0, &nameVal, 0, 0);
		char portGuid[FORMATTED_GUID_LEN+1];
		guidToString(nameVal.bstrVal, (UCHAR *)portGuid, FORMATTED_GUID_LEN);
		myLog(LOG_INFO, "readWMISwitchPorts: portGuid=%s", portGuid);
		VariantClear(&nameVal);
		vAdaptor = adaptorListGet(sp->vAdaptorList, portGuid);
		if (vAdaptor != NULL) {
			portHr = switchPortObj->Get(propSystemName, 0, &systemVal, 0, 0);
			portHr = switchPortObj->Get(propElementName, 0, &elementVal, 0, 0);
			portHr = switchPortObj->Get(propSpeed, 0, &speedVal, 0, 0);
			int length = SysStringLen(systemVal.bstrVal)+1; //include room for terminating null
			wchar_t *switchName = (wchar_t *)my_calloc(length*sizeof(wchar_t));
			wcscpy_s(switchName, length, systemVal.bstrVal);
			length = SysStringLen(elementVal.bstrVal)+1; 
			wchar_t *friendlyName = (wchar_t *)my_calloc(length*sizeof(wchar_t));
			wcscpy_s(friendlyName, length, elementVal.bstrVal);
			ULONGLONG ifSpeed = _wcstoui64(speedVal.bstrVal, NULL, 10);
			VariantClear(&systemVal);
			VariantClear(&elementVal);
			VariantClear(&speedVal);
			HVSVPortInfo *portInfo = (HVSVPortInfo *)vAdaptor->userData;
			if (portInfo->switchName != NULL) {
				my_free(portInfo->switchName);
			}
			portInfo->switchName = switchName;
			if (portInfo->portFriendlyName != NULL) {
				my_free(portInfo->portFriendlyName);
			}
			portInfo->portFriendlyName = friendlyName;
			setPortCountersInstance(vAdaptor);
			vAdaptor->ifSpeed = ifSpeed;
			//Get the MACs and VM system name when we enumerate the vms.
			myLog(LOG_INFO, 
				  "readWMISwitchPorts: updated switch port %s %S portId=%u ifIndex=%u ifSpeed=%llu counterName=%S", 
				  vAdaptor->deviceName, portInfo->portFriendlyName, portInfo->portId, vAdaptor->ifIndex, 
				  vAdaptor->ifSpeed, portInfo->portCountersInstance);
		} else {
			myLog(LOG_INFO, "readWMISwitchPorts: vAdapter not found");
		}
		switchPortObj->Release();
	}
	switchPortEnum->Release();
	pNamespace->Release();
	CoUninitialize();
	SysFreeString(propElementName);
	SysFreeString(propSystemName);
	SysFreeString(propName);
	SysFreeString(propSpeed);

	return;
}
bool CAddCADFrameMenu::GetAcadMenuGroup(IAcadMenuGroup  **pVal,LPCTSTR menuname)
{
 IAcadApplication *acadApp = NULL;
 HRESULT hr = S_OK;
 
 if(!GetAcadApplication(acadApp))
  return false;
 
 LPDISPATCH  pTempDisp = NULL;
 IAcadMenuGroups *mnuGrps = NULL;
 long cnt = 0, cntmnu=0;
 
 //得到菜单组集
 hr = acadApp->get_MenuGroups(&mnuGrps);
 if (FAILED(hr))
 {
  acadApp->Release();
  return false;
 }
 acadApp->Release();
 
 mnuGrps->get_Count(&cnt);
 
 //得到菜单组
 IAcadMenuGroup *mnuGrp = NULL;
 IAcadPopupMenus  *mnus = NULL;
 IAcadPopupMenu *pPopUpMenu=NULL;
 
 VARIANT  vtName,vtMenu;
 vtName.vt = VT_I4;
 vtMenu.vt = VT_I4;

 BSTR  mnuName;
 bool found = false ;
 for (long i=0; i < cnt; i++)
 {
  vtName.lVal = i;
  hr = mnuGrps->Item(vtName, &mnuGrp);
  if (FAILED(hr))
  {
   return false;
  }
  
  mnuGrp->get_Menus(&mnus);

  mnus->get_Count(&cntmnu);

  for(long j=0;j<cntmnu;j++)
  {
   vtMenu.lVal=j;
   hr=mnus->Item(vtMenu,&pPopUpMenu);
   if(FAILED(hr))
    continue;

   pPopUpMenu->get_Name(&mnuName);
   pPopUpMenu->Release();

   CString sMenuName(mnuName);
   SysFreeString(mnuName);
   
   sMenuName.Replace("&","");//debug
   if(sMenuName.CompareNoCase(menuname)==0)
   {
    found=true;
    *pVal = mnuGrp;
    break;
   }
  }

  mnus->Release();

  if(found)
  {
   break;
  }
  else
  {
   mnuGrp->Release();
  }
 }

 mnuGrps->Release();
 
 return found;
}
Esempio n. 5
0
void SettingsXML::AppendNewLine(IXMLDOMNode* apFrom)
{
	BSTR bsText = SysAllocString(L"\r\n");
	AppendText(apFrom, bsText);
	SysFreeString(bsText);
}
int  CVMR_Capture::EnumDevices(HWND hList)
{
	if (!hList)
		return  -1;

	
	int id = 0;
	
    // enumerate all video capture devices
	CComPtr<ICreateDevEnum> pCreateDevEnum;
//    ICreateDevEnum *pCreateDevEnum;
    HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
			  IID_ICreateDevEnum, (void**)&pCreateDevEnum);
    if (hr != NOERROR)
	{

		return -1;
	}



    CComPtr<IEnumMoniker> pEm;
    hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,
								&pEm, 0);
    if (hr != NOERROR) 
	{

		return -1 ;
    }

    pEm->Reset();
    ULONG cFetched;
    IMoniker *pM;
    while(hr = pEm->Next(1, &pM, &cFetched), hr==S_OK)
    {
		IPropertyBag *pBag;
		hr = pM->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);
		if(SUCCEEDED(hr)) 
		{
			VARIANT var;
			var.vt = VT_BSTR;
			hr = pBag->Read(L"FriendlyName", &var, NULL);
			if (hr == NOERROR) 
			{
				TCHAR str[2048];		
				

				id++;
				WideCharToMultiByte(CP_ACP,0,var.bstrVal, -1, str, 2048, NULL, NULL);
				
				
				(long)SendMessage(hList, CB_ADDSTRING, 0,(LPARAM)str);

				SysFreeString(var.bstrVal);
			}
			pBag->Release();
		}
		pM->Release();
    }
	return id;
}
Esempio n. 7
0
int main(int argc, char* argv[])
{
	IADsContainer *pSchema=NULL;
	HRESULT hr;

	CoInitialize(NULL);

	hr = ADsGetObject(L"WinNT://INDEPENDENCE/Schema", IID_IADsContainer, (void**) &pSchema );

	if ( !SUCCEEDED(hr) )
	{
		return hr;
	}


	////////////// Enumerate Schema objects ///////////////////////////////////
	IEnumVARIANT *pEnum = NULL;
	hr = ADsBuildEnumerator( pSchema, &pEnum );
	pSchema->Release(); // no longer needed, since we have the enumerator already
	
	if ( SUCCEEDED(hr) )
	{
		VARIANT var;
		ULONG lFetch;
		IADs *pChild=NULL;
		VariantInit(&var);
		
		while( SUCCEEDED(ADsEnumerateNext( pEnum, 1, &var, &lFetch )) && lFetch == 1 )
		{
			hr = V_DISPATCH(&var)->QueryInterface( IID_IADs, (void**) &pChild );
			if ( SUCCEEDED(hr) )
			{
				BSTR bstrName;
				BSTR bstrClass;
				// Get more information on the child classes
				pChild->get_Name(&bstrName);
				pChild->get_Class(&bstrClass);
				
				printf("%S\t\t(%S)\n", bstrName, bstrClass );
				
				// Clean-up
				SysFreeString(bstrName);
				SysFreeString(bstrClass);
				
				pChild->Release();
			}
			VariantClear(&var);
		}
	}

              //Release the enumerator.
              if (pEnum != NULL) 
              {
                  ADsFreeEnumerator(pEnum);
              }


	CoUninitialize();



	return 0;
}
Esempio n. 8
0
BString::~BString()
{
    SysFreeString(m_bstr);
}
Esempio n. 9
0
HRESULT CModuleConfiguration::CreateNodeEnvironment(IHttpContext* ctx, PCH namedPipe, PCH* env)
{
	HRESULT hr;
	LPCH currentEnvironment = NULL;
	LPCH tmpStart, tmpIndex = NULL;
	DWORD tmpSize;
	DWORD environmentSize;
	IAppHostElement* section = NULL;
	IAppHostElementCollection* appSettings = NULL;
	IAppHostElement* entry = NULL;
	IAppHostPropertyCollection* properties = NULL;
	IAppHostProperty* prop = NULL;
	BSTR keyPropertyName = NULL;
	BSTR valuePropertyName = NULL;
	VARIANT vKeyPropertyName;
	VARIANT vValuePropertyName;
	DWORD count;
	BSTR propertyValue;
	int propertySize;

	CheckNull(env);
	*env = NULL;

	// this is a zero terminated list of zero terminated strings of the form <var>=<value>

	// calculate size of current environment

	ErrorIf(NULL == (currentEnvironment = GetEnvironmentStrings()), GetLastError());
	environmentSize = 0;
	do {
		while (*(currentEnvironment + environmentSize++) != 0);
	} while (*(currentEnvironment + environmentSize++) != 0);

	// allocate memory for new environment variables

	tmpSize = 32767 - environmentSize;
	ErrorIf(NULL == (tmpIndex = tmpStart = new char[tmpSize]), ERROR_NOT_ENOUGH_MEMORY);
	RtlZeroMemory(tmpIndex, tmpSize);

	// set PORT and IISNODE_VERSION variables

	ErrorIf(tmpSize < (strlen(namedPipe) + strlen(IISNODE_VERSION) + 6 + 17), ERROR_NOT_ENOUGH_MEMORY);
	sprintf(tmpIndex, "PORT=%s", namedPipe);
	tmpIndex += strlen(namedPipe) + 6;
	sprintf(tmpIndex, "IISNODE_VERSION=%s", IISNODE_VERSION);
	tmpIndex += strlen(IISNODE_VERSION) + 17;

	// add environment variables from the appSettings section of config

	ErrorIf(NULL == (keyPropertyName = SysAllocString(L"key")), ERROR_NOT_ENOUGH_MEMORY);
	vKeyPropertyName.vt = VT_BSTR;
	vKeyPropertyName.bstrVal = keyPropertyName;
	ErrorIf(NULL == (valuePropertyName = SysAllocString(L"value")), ERROR_NOT_ENOUGH_MEMORY);
	vValuePropertyName.vt = VT_BSTR;
	vValuePropertyName.bstrVal = valuePropertyName;
	CheckError(GetConfigSection(ctx, &section, L"appSettings"));
	CheckError(section->get_Collection(&appSettings));
	CheckError(appSettings->get_Count(&count));

	for (USHORT i = 0; i < count; i++)
	{
		VARIANT index;
		index.vt = VT_I2;
		index.iVal = i;		

		CheckError(appSettings->get_Item(index, &entry));
		CheckError(entry->get_Properties(&properties));
		
		CheckError(properties->get_Item(vKeyPropertyName, &prop));
		CheckError(prop->get_StringValue(&propertyValue));
		ErrorIf(0 == (propertySize = WideCharToMultiByte(CP_ACP, 0, propertyValue, wcslen(propertyValue), NULL, 0, NULL, NULL)), E_FAIL);
		ErrorIf((propertySize + 2) > (tmpSize - (tmpStart - tmpIndex)), ERROR_NOT_ENOUGH_MEMORY);
		ErrorIf(propertySize != WideCharToMultiByte(CP_ACP, 0, propertyValue, wcslen(propertyValue), tmpIndex, propertySize, NULL, NULL), E_FAIL);
		tmpIndex[propertySize] = '=';
		tmpIndex += propertySize + 1;
		SysFreeString(propertyValue);
		propertyValue = NULL;
		prop->Release();
		prop = NULL;

		CheckError(properties->get_Item(vValuePropertyName, &prop));
		CheckError(prop->get_StringValue(&propertyValue));
		ErrorIf(0 == (propertySize = WideCharToMultiByte(CP_ACP, 0, propertyValue, wcslen(propertyValue), NULL, 0, NULL, NULL)), E_FAIL);
		ErrorIf((propertySize + 1) > (tmpSize - (tmpStart - tmpIndex)), ERROR_NOT_ENOUGH_MEMORY);
		ErrorIf(propertySize != WideCharToMultiByte(CP_ACP, 0, propertyValue, wcslen(propertyValue), tmpIndex, propertySize, NULL, NULL), E_FAIL);
		tmpIndex += propertySize + 1;
		SysFreeString(propertyValue);
		propertyValue = NULL;
		prop->Release();
		prop = NULL;

		properties->Release();
		properties = NULL;
		entry->Release();
		entry = NULL;
	}

	// concatenate new environment variables with the current environment block

	ErrorIf(NULL == (*env = (LPCH)new char[environmentSize + (tmpIndex - tmpStart)]), ERROR_NOT_ENOUGH_MEMORY);	
	memcpy(*env, tmpStart, (tmpIndex - tmpStart));
	memcpy(*env + (tmpIndex - tmpStart), currentEnvironment, environmentSize);

	// cleanup

	FreeEnvironmentStrings(currentEnvironment);
	section->Release();
	appSettings->Release();
	SysFreeString(keyPropertyName);
	SysFreeString(valuePropertyName);
	delete [] tmpStart;

	return S_OK;
Error:

	if (currentEnvironment)
	{
		FreeEnvironmentStrings(currentEnvironment);
		currentEnvironment = NULL;
	}

	if (section)
	{
		section->Release();
		section = NULL;
	}

	if (appSettings)
	{
		appSettings->Release();
		appSettings = NULL;
	}

	if (keyPropertyName)
	{
		SysFreeString(keyPropertyName);
		keyPropertyName = NULL;
	}

	if (valuePropertyName)
	{
		SysFreeString(valuePropertyName);
		valuePropertyName = NULL;
	}

	if (entry)
	{
		entry->Release();
		entry = NULL;
	}

	if (properties)
	{
		properties->Release();
		properties = NULL;
	}

	if (prop)
	{
		prop->Release();
		prop = NULL;
	}

	if (propertyValue)
	{
		SysFreeString(propertyValue);
		propertyValue = NULL;
	}

	if (tmpStart)
	{
		delete [] tmpStart;
		tmpStart = NULL;
	}

	return hr;
}
Esempio n. 10
0
BOOL getWordByAccEx( POINT pt )
{
HRESULT hr;
IAccessible *pAcc, *pAccParent;
ITextProvider *pText;
ITextRangeProvider *pTextRange;
VARIANT var;
long idChild;
BSTR bstr = NULL;
int n;
UiaPoint upt;
POINT ppt = { 0, 0 };

	if( getPhysicalCursorPosFunc != NULL ) {
		getPhysicalCursorPosFunc( &ppt );
	} else {
		ppt = pt;
	}

	upt.x = ppt.x;
	upt.y = ppt.y;

	pAcc = NULL;
	hr = AccessibleObjectFromPoint( ppt, &pAcc, &var );
	idChild = var.lVal;

	if( hr != S_OK || pAcc == NULL) {
		VariantClear( &var );
		return FALSE;
	}

	pText = NULL;
	while( pAcc != NULL) {
		hr = GetPatternFromIAccessible( pAcc, 0, UIA_TextPatternId, &IID_ITextProvider, (void **)&pText );
		if( hr == S_OK && pText != NULL )
			break;
		pAccParent = NULL;
		hr = GetParentAccessibleObject( pAcc, &pAccParent );
		pAcc->lpVtbl->Release( pAcc );
		pAcc = pAccParent;
	}
	if( pAcc == NULL ) 
		return FALSE;

	pAcc->lpVtbl->Release( pAcc );

	pTextRange = NULL;
	hr = pText->lpVtbl->RangeFromPoint( pText, upt, &pTextRange );
	if( hr != S_OK || pTextRange == NULL ) {
		pText->lpVtbl->Release( pText );
		return FALSE;
	}

	hr = pTextRange->lpVtbl->ExpandToEnclosingUnit( pTextRange, TextUnit_Word );
	if( hr == S_OK) {
		bstr = NULL;
		hr = pTextRange->lpVtbl->GetText( pTextRange, 255, &bstr );
		if (hr == S_OK) {
			n = SysStringLen( bstr );
			if( n != 0 ) {
				n = WideCharToMultiByte( CP_UTF8, 0, (LPCWSTR)bstr, n, GlobalData->CurMod.MatchedWord, sizeof( GlobalData->CurMod.MatchedWord ) - 1, NULL, NULL );
				GlobalData->CurMod.WordLen = n;
				GlobalData->CurMod.MatchedWord[n] = 0;
			}
			SysFreeString( bstr );
		}
	}
	pTextRange->lpVtbl->Release( pTextRange );
	pText->lpVtbl->Release( pText );

	return TRUE;
}
/* **************************************************************************
 * dhExitEx:
 *   This function is called when exiting a DispHelper function.
 *
 * Parameter Info:
 *   bDispatchError   - TRUE if the error was returned from the IDispatch interface.  
 *   szMember         - The member name that caused the error. eg. "TypeText"
 *   szCompleteMember - The complete member. eg. "Selection.TypeText(%S)"
 *   pExcepInfo       - A pointer to the EXCEPINFO structure returned by IDispatch::Invoke.
 *   iArgError        - The index of the argument that caused the error as returned by Invoke.
 *   szFunctionName   - The function which is exiting(string must have global life time).
 * 
 * Notes:
 *   szMember, szCompleteMember, pExcepInfo and iArgError are NULL or 0 if not available.
 *
 ============================================================================ */
HRESULT dhExitEx(HRESULT hr, BOOL bDispatchError, LPCWSTR szMember, LPCWSTR szCompleteMember,
                 EXCEPINFO * pExcepInfo, UINT iArgError, LPCWSTR szFunctionName)
{
	UINT nStackCount = GetStackCount();

	SetStackCount(nStackCount - 1);

	if (FAILED(hr) && !g_ExceptionOptions.bDisableRecordExceptions)
	{
		PDH_EXCEPTION pException = GetExceptionPtr();

		if (!pException) /* No exception allocated for this thread yet */
		{ 
			pException = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DH_EXCEPTION));
			if (!pException) return hr;
			SetExceptionPtr(pException);
		}
		else if (pException->bOld) /* Exception is from a former call */
		{
			SysFreeString(pException->szDescription);
			SysFreeString(pException->szSource);
			SysFreeString(pException->szHelpFile);
			ZeroMemory(pException, sizeof(DH_EXCEPTION));
		}

		if (pException->hr == 0)
		{
			/* Only record the error information the first time it is reported */

			pException->hr              = hr;
			pException->iArgError       = iArgError;
			pException->szErrorFunction = szFunctionName;
			pException->bDispatchError  = bDispatchError;

			if (szMember) hlprStringCchCopyW(pException->szMember, ARRAYSIZE(pException->szMember), szMember);

			if (pExcepInfo && hr == DISP_E_EXCEPTION)
			{
				/* Extract error info returned by IDispatch::Invoke in an EXCEPINFO */

				if (pExcepInfo->pfnDeferredFillIn &&
				    !IsBadCodePtr((FARPROC) pExcepInfo->pfnDeferredFillIn)) pExcepInfo->pfnDeferredFillIn(pExcepInfo);

				pException->szDescription = pExcepInfo->bstrDescription;
				pException->szSource      = pExcepInfo->bstrSource;
				pException->szHelpFile    = pExcepInfo->bstrHelpFile;
				pException->dwHelpContext = pExcepInfo->dwHelpContext;
				pException->swCode        = (pExcepInfo->wCode ? pExcepInfo->wCode : pExcepInfo->scode);
			}
		}

		if (nStackCount == 1) /* We are exiting the outer most function */
		{
			pException->bOld              = TRUE;
			pException->szInitialFunction = szFunctionName;

			if (szCompleteMember) hlprStringCchCopyW(pException->szCompleteMember, ARRAYSIZE(pException->szCompleteMember), szCompleteMember);

			if (g_ExceptionOptions.bShowExceptions)
				dhShowException(pException);

			if (g_ExceptionOptions.pfnExceptionCallback)
				g_ExceptionOptions.pfnExceptionCallback(pException);
		}
	}
	else if (hr == DISP_E_EXCEPTION && pExcepInfo)
	{
		/* We are responsible for cleaning up pExcepInfo even if we don't use it */
		SysFreeString(pExcepInfo->bstrDescription);
		SysFreeString(pExcepInfo->bstrSource);
		SysFreeString(pExcepInfo->bstrHelpFile);
	}

	return hr;
}
Esempio n. 12
0
HWND COccManager::CreateDlgControl(CWnd* pWndParent, HWND hwAfter,
	BOOL bDialogEx, LPDLGITEMTEMPLATE pItem, WORD nMsg, BYTE* lpData, DWORD cb)
{
	LPWSTR pszClass = (LPWSTR)(pItem + 1);
	DLGITEMTEMPLATE dlgItemTmp;

	if (bDialogEx)
	{
		// We have an extended dialog template: copy relevant parts into an
		// ordinary dialog template, because their layouts are different
		DLGITEMTEMPLATEEX* pItemEx = (DLGITEMTEMPLATEEX*)pItem;
		dlgItemTmp.style = pItemEx->style;
		dlgItemTmp.dwExtendedStyle = pItemEx->exStyle;
		dlgItemTmp.x = pItemEx->x;
		dlgItemTmp.y = pItemEx->y;
		dlgItemTmp.cx = pItemEx->cx;
		dlgItemTmp.cy = pItemEx->cy;
		dlgItemTmp.id = (WORD)pItemEx->id;
		pItem = &dlgItemTmp;
		pszClass = (LPWSTR)(pItemEx + 1);
	}

	CRect rect(pItem->x, pItem->y, pItem->x + pItem->cx, pItem->y + pItem->cy);
	::MapDialogRect(pWndParent->m_hWnd, &rect);

	BSTR bstrLicKey = NULL;

	// extract license key data, if any
	if (cb >= sizeof(ULONG))
	{
		ULONG cchLicKey = *(UNALIGNED ULONG*)lpData;
		lpData += sizeof(ULONG);
		cb -= sizeof(ULONG);
		if (cchLicKey > 0)
		{
			bstrLicKey = SysAllocStringLen((LPCOLESTR)lpData, cchLicKey);
			lpData += cchLicKey * sizeof(WCHAR);
			cb -= cchLicKey * sizeof(WCHAR);
		}
	}

	// If WM_OCC_INITNEW, we should have exhausted all of the data by now.
	ASSERT((nMsg != WM_OCC_INITNEW) || (cb == 0));

	CDataBoundProperty* pBindings = NULL;
	CString strDataField;
	WORD ctlidRowSource = 0;
	DISPID defdispid = 0;
	UINT dwType = 0;

	if (nMsg == WM_OCC_LOADFROMSTREAM_EX ||
		nMsg == WM_OCC_LOADFROMSTORAGE_EX)
	{
		// Read the size of the section
		ULONG cbOffset = *(UNALIGNED ULONG*)lpData;
		ULONG cbBindInfo = cbOffset - sizeof(DWORD);
		lpData += sizeof(DWORD);

		ULONG dwFlags = *(UNALIGNED ULONG*)lpData;
		cbBindInfo -= sizeof(DWORD);
		lpData += sizeof(DWORD);
		ASSERT(dwFlags == 1);

		ULONG cbBinding = *(UNALIGNED ULONG*)lpData;
		cbBindInfo -= sizeof(DWORD);
		lpData += sizeof(DWORD);

		while(cbBindInfo > 0)
		{
			DISPID dispid;
			UWORD ctlid;

			dispid = *(UNALIGNED DISPID *)lpData;
			lpData += sizeof(DISPID);
			cbBindInfo -= sizeof(DISPID);
			ctlid =  *(UNALIGNED WORD *)lpData;
			lpData += sizeof(WORD);
			cbBindInfo -= sizeof(WORD);

			if(dispid == DISPID_DATASOURCE)
			{
				defdispid = *(UNALIGNED ULONG*)lpData;
				cbBindInfo -= sizeof(DISPID);
				lpData += sizeof(DISPID);
				dwType = *(UNALIGNED ULONG*)lpData;
				cbBindInfo -= sizeof(DWORD);
				lpData += sizeof(DWORD);

				ASSERT(*(UNALIGNED DISPID *)lpData == DISPID_DATAFIELD);
				lpData += sizeof(DISPID);
				cbBindInfo -= sizeof(DISPID);
				// Skip the string length
				lpData += sizeof(DWORD);
				cbBindInfo -= sizeof(DWORD);
				strDataField = (char *)lpData;
				lpData += strDataField.GetLength()+1;
				cbBindInfo -= strDataField.GetLength()+1;
				ctlidRowSource = ctlid;
			} else
				pBindings = new CDataBoundProperty(pBindings, dispid, ctlid);
		}
		cb -= cbOffset;
	}

	// From now on act as a regular type
	nMsg -= (WM_OCC_LOADFROMSTREAM_EX - WM_OCC_LOADFROMSTREAM);

	GUID clsid;
	HRESULT hr;
	if (pszClass[0] == L'{')
		hr = CLSIDFromString(pszClass, &clsid);
	else
		hr = CLSIDFromProgID(pszClass, &clsid);

#ifdef _DEBUG
	if (FAILED(hr))
	{
		TRACE1("Unable to convert \"%ls\" to a class ID.\n", pszClass);
		TRACE1(">>> Result code: 0x%08lx\n", hr);
		if (pszClass[0] != L'{')
			TRACE0(">>> Is the control properly registered?\n");
	}
#endif

	CMemFile memFile(lpData, cb);
	CMemFile* pMemFile = (nMsg == WM_OCC_INITNEW) ? NULL : &memFile;

	CWnd* pWndNew = NULL;
	COleControlSite* pSite = NULL;

	if (SUCCEEDED(hr) &&
		pWndParent->InitControlContainer() &&
		pWndParent->m_pCtrlCont->CreateControl(NULL, clsid, NULL, pItem->style,
			rect, pItem->id, pMemFile, (nMsg == WM_OCC_LOADFROMSTORAGE),
			bstrLicKey, &pSite))
	{
		ASSERT(pSite != NULL);
		// set ZOrder only!
		SetWindowPos(pSite->m_hWnd, hwAfter, 0, 0, 0, 0,
			SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);

		pSite->m_pBindings = pBindings;
		pSite->m_strDataField = strDataField;
		pSite->m_ctlidRowSource = ctlidRowSource;
		pSite->m_defdispid = defdispid;
		pSite->m_dwType = dwType;

		// Determine if this is a DataSource by QI for ICursor
		ICursor* pCursor;
		if (SUCCEEDED(pSite->m_pObject->QueryInterface(IID_ICursor,
			(LPVOID *)&pCursor)))
		{
			pCursor->Release();
            pSite->m_pDataSourceControl = new CDataSourceControl(pSite);
		}
	}

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

	return (pSite != NULL) ? pSite->m_hWnd : NULL;
}
Esempio n. 13
0
std::string OHTTPPost(const std::string &url, 
                      const std::vector<std::pair<std::string, std::string>> &postArgs,
                      std::function<void(long, std::string)> onError)
{
    HRESULT hr;
    CComPtr<IXMLHTTPRequest> request;

    hr = request.CoCreateInstance(CLSID_XMLHTTP60);
    if (postArgs.empty())
    {
        hr = request->open(_bstr_t("GET"),
                           _bstr_t(url.c_str()),
                           _variant_t(VARIANT_FALSE),
                           _variant_t(),
                           _variant_t());
        hr = request->send(_variant_t());
    }
    else
    {
        hr = request->open(_bstr_t("POST"),
                           _bstr_t(url.c_str()),
                           _variant_t(VARIANT_FALSE),
                           _variant_t(),
                           _variant_t());
        std::string args;
        bool first = true;
        for (auto &kv : postArgs)
        {
            if (first)
            {
                first = false;
                args += kv.first + "=" + kv.second;
            }
            else
            {
                args += "&" + kv.first + "=" + kv.second;
            }
        }
        request->setRequestHeader(_bstr_t("Content-type"), _bstr_t("application/x-www-form-urlencoded"));
        request->setRequestHeader(_bstr_t("Content-length"), _bstr_t(std::to_string(args.size()).c_str()));
        hr = request->send(_variant_t(args.c_str()));
    }

    if (hr != S_OK)
    {
        if (onError)
        {
            onError(0, "error");
        }
        return "";
    }

    // get status - 200 if succuss
    long status;
    hr = request->get_status(&status);
    if (hr != S_OK)
    {
        if (onError)
        {
            onError(0, "error");
        }
        return "";
    }

    // Load the text
    BSTR bstrResponse = NULL;
    request->get_responseText(&bstrResponse);
    std::wstring wret = bstrResponse;
    if (bstrResponse) SysFreeString(bstrResponse);
    std::string ret = onut::utf16ToUtf8(wret);

    if (status == 200)
    {
        return ret;
    }
    else
    {
        if (onError)
        {
            onError(status, ret);
        }
        return "";
    }
}
Esempio n. 14
0
static HRESULT HttpProtocol_open_request(Protocol *prot, IUri *uri, DWORD request_flags,
        HINTERNET internet_session, IInternetBindInfo *bind_info)
{
    HttpProtocol *This = impl_from_Protocol(prot);
    LPWSTR addl_header = NULL, post_cookie = NULL;
    IServiceProvider *service_provider = NULL;
    IHttpNegotiate2 *http_negotiate2 = NULL;
    BSTR url, host, user, pass, path;
    LPOLESTR accept_mimes[257];
    const WCHAR **accept_types;
    BYTE security_id[512];
    DWORD len, port, flags;
    ULONG num, error;
    BOOL res, b;
    HRESULT hres;

    static const WCHAR wszBindVerb[BINDVERB_CUSTOM][5] =
        {{'G','E','T',0},
         {'P','O','S','T',0},
         {'P','U','T',0}};

    hres = IUri_GetPort(uri, &port);
    if(FAILED(hres))
        return hres;

    hres = IUri_GetHost(uri, &host);
    if(FAILED(hres))
        return hres;

    hres = IUri_GetUserName(uri, &user);
    if(SUCCEEDED(hres)) {
        hres = IUri_GetPassword(uri, &pass);

        if(SUCCEEDED(hres)) {
            This->base.connection = InternetConnectW(internet_session, host, port, user, pass,
                    INTERNET_SERVICE_HTTP, This->https ? INTERNET_FLAG_SECURE : 0, (DWORD_PTR)&This->base);
            SysFreeString(pass);
        }
        SysFreeString(user);
    }
    SysFreeString(host);
    if(FAILED(hres))
        return hres;
    if(!This->base.connection) {
        WARN("InternetConnect failed: %d\n", GetLastError());
        return INET_E_CANNOT_CONNECT;
    }

    num = sizeof(accept_mimes)/sizeof(accept_mimes[0])-1;
    hres = IInternetBindInfo_GetBindString(bind_info, BINDSTRING_ACCEPT_MIMES, accept_mimes, num, &num);
    if(hres == INET_E_USE_DEFAULT_SETTING) {
        static const WCHAR default_accept_mimeW[] = {'*','/','*',0};
        static const WCHAR *default_accept_mimes[] = {default_accept_mimeW, NULL};

        accept_types = default_accept_mimes;
        num = 0;
    }else if(hres == S_OK) {
        accept_types = (const WCHAR**)accept_mimes;
    }else {
        WARN("GetBindString BINDSTRING_ACCEPT_MIMES failed: %08x\n", hres);
        return INET_E_NO_VALID_MEDIA;
    }
    accept_mimes[num] = 0;

    if(This->https)
        request_flags |= INTERNET_FLAG_SECURE;

    hres = IUri_GetPathAndQuery(uri, &path);
    if(SUCCEEDED(hres)) {
        This->base.request = HttpOpenRequestW(This->base.connection,
                This->base.bind_info.dwBindVerb < BINDVERB_CUSTOM
                    ? wszBindVerb[This->base.bind_info.dwBindVerb] : This->base.bind_info.szCustomVerb,
                path, NULL, NULL, accept_types, request_flags, (DWORD_PTR)&This->base);
        SysFreeString(path);
    }
    while(num--)
        CoTaskMemFree(accept_mimes[num]);
    if(FAILED(hres))
        return hres;
    if (!This->base.request) {
        WARN("HttpOpenRequest failed: %d\n", GetLastError());
        return INET_E_RESOURCE_NOT_FOUND;
    }

    hres = IInternetProtocolSink_QueryInterface(This->base.protocol_sink, &IID_IServiceProvider,
            (void **)&service_provider);
    if (hres != S_OK) {
        WARN("IInternetProtocolSink_QueryInterface IID_IServiceProvider failed: %08x\n", hres);
        return hres;
    }

    hres = IServiceProvider_QueryService(service_provider, &IID_IHttpNegotiate,
            &IID_IHttpNegotiate, (void **)&This->http_negotiate);
    if (hres != S_OK) {
        WARN("IServiceProvider_QueryService IID_IHttpNegotiate failed: %08x\n", hres);
        IServiceProvider_Release(service_provider);
        return hres;
    }

    hres = IUri_GetAbsoluteUri(uri, &url);
    if(FAILED(hres)) {
        IServiceProvider_Release(service_provider);
        return hres;
    }

    hres = IHttpNegotiate_BeginningTransaction(This->http_negotiate, url, default_headersW,
            0, &addl_header);
    SysFreeString(url);
    if(hres != S_OK) {
        WARN("IHttpNegotiate_BeginningTransaction failed: %08x\n", hres);
        IServiceProvider_Release(service_provider);
        return hres;
    }

    len = addl_header ? strlenW(addl_header) : 0;

    This->full_header = heap_alloc(len*sizeof(WCHAR)+sizeof(default_headersW));
    if(!This->full_header) {
        IServiceProvider_Release(service_provider);
        return E_OUTOFMEMORY;
    }

    if(len)
        memcpy(This->full_header, addl_header, len*sizeof(WCHAR));
    CoTaskMemFree(addl_header);
    memcpy(This->full_header+len, default_headersW, sizeof(default_headersW));

    hres = IServiceProvider_QueryService(service_provider, &IID_IHttpNegotiate2,
            &IID_IHttpNegotiate2, (void **)&http_negotiate2);
    IServiceProvider_Release(service_provider);
    if(hres != S_OK) {
        WARN("IServiceProvider_QueryService IID_IHttpNegotiate2 failed: %08x\n", hres);
        /* No goto done as per native */
    }else {
        len = sizeof(security_id)/sizeof(security_id[0]);
        hres = IHttpNegotiate2_GetRootSecurityId(http_negotiate2, security_id, &len, 0);
        IHttpNegotiate2_Release(http_negotiate2);
        if (hres != S_OK)
            WARN("IHttpNegotiate2_GetRootSecurityId failed: %08x\n", hres);
    }

    /* FIXME: Handle security_id. Native calls undocumented function IsHostInProxyBypassList. */

    if(This->base.bind_info.dwBindVerb == BINDVERB_POST) {
        num = 0;
        hres = IInternetBindInfo_GetBindString(bind_info, BINDSTRING_POST_COOKIE, &post_cookie, 1, &num);
        if(hres == S_OK && num) {
            if(!InternetSetOptionW(This->base.request, INTERNET_OPTION_SECONDARY_CACHE_KEY,
                                   post_cookie, lstrlenW(post_cookie)))
                WARN("InternetSetOption INTERNET_OPTION_SECONDARY_CACHE_KEY failed: %d\n", GetLastError());
            CoTaskMemFree(post_cookie);
        }
    }

    flags = INTERNET_ERROR_MASK_COMBINED_SEC_CERT;
    res = InternetSetOptionW(This->base.request, INTERNET_OPTION_ERROR_MASK, &flags, sizeof(flags));
    if(!res)
        WARN("InternetSetOption(INTERNET_OPTION_ERROR_MASK) failed: %u\n", GetLastError());

    b = TRUE;
    res = InternetSetOptionW(This->base.request, INTERNET_OPTION_HTTP_DECODING, &b, sizeof(b));
    if(!res)
        WARN("InternetSetOption(INTERNET_OPTION_HTTP_DECODING) failed: %u\n", GetLastError());

    do {
        error = send_http_request(This);

        if(error == ERROR_IO_PENDING || error == ERROR_SUCCESS)
            return S_OK;

        hres = handle_http_error(This, error);

    } while(hres == RPC_E_RETRY);

    WARN("HttpSendRequest failed: %d\n", error);
    return hres;
}
Esempio n. 15
0
CDot11SampleExtUIConProperty::~CDot11SampleExtUIConProperty()
{
    SysFreeString(m_bstrFN);
    InterlockedDecrement(&g_objRefCount);        
}
Esempio n. 16
0
static HRESULT WINAPI ProtocolSinkHandler_ReportData(IInternetProtocolSink *iface,
        DWORD bscf, ULONG progress, ULONG progress_max)
{
    BindProtocol *This = impl_from_IInternetProtocolSinkHandler(iface);

    TRACE("(%p)->(%x %u %u)\n", This, bscf, progress, progress_max);

    This->bscf = bscf;
    This->progress = progress;
    This->progress_max = progress_max;

    if(!This->protocol_sink)
        return S_OK;

    if((This->pi & PI_MIMEVERIFICATION) && !This->reported_mime) {
        BYTE buf[BUFFER_SIZE];
        DWORD read = 0;
        LPWSTR mime;
        HRESULT hres;

        do {
            read = 0;
            if(is_apartment_thread(This))
                This->continue_call++;
            hres = IInternetProtocol_Read(This->protocol, buf,
                    sizeof(buf)-This->buf_size, &read);
            if(is_apartment_thread(This))
                This->continue_call--;
            if(FAILED(hres) && hres != E_PENDING)
                return hres;

            if(!This->buf) {
                This->buf = heap_alloc(BUFFER_SIZE);
                if(!This->buf)
                    return E_OUTOFMEMORY;
            }else if(read + This->buf_size > BUFFER_SIZE) {
                BYTE *tmp;

                tmp = heap_realloc(This->buf, read+This->buf_size);
                if(!tmp)
                    return E_OUTOFMEMORY;
                This->buf = tmp;
            }

            memcpy(This->buf+This->buf_size, buf, read);
            This->buf_size += read;
        }while(This->buf_size < MIME_TEST_SIZE && hres == S_OK);

        if(This->buf_size < MIME_TEST_SIZE && hres != S_FALSE)
            return S_OK;

        bscf = BSCF_FIRSTDATANOTIFICATION;
        if(hres == S_FALSE)
            bscf |= BSCF_LASTDATANOTIFICATION|BSCF_DATAFULLYAVAILABLE;

        if(!This->reported_mime) {
            BSTR raw_uri;

            hres = IUri_GetRawUri(This->uri, &raw_uri);
            if(FAILED(hres))
                return hres;

            hres = FindMimeFromData(NULL, raw_uri, This->buf, min(This->buf_size, MIME_TEST_SIZE),
                    This->mime, 0, &mime, 0);
            SysFreeString(raw_uri);
            if(FAILED(hres))
                return hres;

            heap_free(This->mime);
            This->mime = heap_strdupW(mime);
            CoTaskMemFree(mime);
            This->reported_mime = TRUE;
            if(This->protocol_sink)
                IInternetProtocolSink_ReportProgress(This->protocol_sink, BINDSTATUS_MIMETYPEAVAILABLE, This->mime);
        }
    }

    if(!This->protocol_sink)
        return S_OK;

    return IInternetProtocolSink_ReportData(This->protocol_sink, bscf, progress, progress_max);
}
Esempio n. 17
0
STDMETHODIMP CConsumer::IndicateToConsumer(IWbemClassObject *pLogicalConsumer,
											long lNumObjects,
											IWbemClassObject **ppObjects)
{

	// NOTE: If this routine returns a failure code, including GPFs from called routines,
	// CIMOM will recreate the object and call here again. If you see this routine being
	// called twice for every indication, it means this routine is returning a failure code
	// somehow. Especially watch the AddRef()/Release() semantics for the embedded object.
	// If they're too low, you'll return a GPF.
	HRESULT  hRes;
	CString clMyBuff;
	BSTR objName = NULL;
	BSTR propName = NULL;
	VARIANT pVal, vUnk;
	IUnknown *pUnk = NULL;
	IWbemClassObject *tgtInst = NULL;

	VariantInit(&pVal);
	VariantInit(&vUnk);

	TRACE(_T("Indicate() called\n"));

	objName = SysAllocString(L"TargetInstance");
	if (!objName)
	{
		TRACE(_T("SysAllocString failed\n"));
		return E_OUTOFMEMORY;
	}
	propName = SysAllocString(L"Item");
	if (!propName)
	{
		TRACE(_T("SysAllocString failed\n"));
		SysFreeString(objName);
		return E_OUTOFMEMORY;
	}

	// walk though the classObjects...
	for (int i = 0; i < lNumObjects; i++)
	{
		// clear my output buffer.
		clMyBuff.Empty();

		// get what was added. This will be an embedded object (VT_UNKNOWN). All
		// WMI interfaces are derived from IUnknown.
		if ((hRes = ppObjects[i]->Get(objName, 0L, 
										&vUnk, NULL, NULL)) == S_OK) 
		{
			//--------------------------------
			// pull the IUnknown out of the various. Dont cast directly to to IWbemClassObject.
			// it MIGHT work now but a suptle change later will break your code. The PROPER 
			// way is to go through QueryInterface and do all the right Release()'s.
			pUnk = (IUnknown *)V_UNKNOWN(&vUnk);

			//--------------------------------
			// Even though you didn't use QI(), you just made a copy of a COM ptr so you 
			// better do the AddRef() that QI() would otherwise do for you.
			pUnk->AddRef();

			//--------------------------------
			// ask for the IWbemClassObject which is the embedded object. This will be the
			// instance that was created.
			if(SUCCEEDED(pUnk->QueryInterface(IID_IWbemClassObject, (void **)&tgtInst)))
			{
				//--------------------------------
				// done with it.
				pUnk->Release();

				//--------------------------------
				// get the 'Item' property out of the embedded object.
				if ((hRes = tgtInst->Get(propName, 0L, 
										&pVal, NULL, NULL)) == S_OK) 
				{
					//--------------------------------
					// done with it.
					tgtInst->Release();

					// compose a string for the listbox.
					clMyBuff = _T("OfficeEquipment Instance added for: ");
					clMyBuff += V_BSTR(&pVal);
				
					// output the buffer.
					m_pOutputList->AddString(clMyBuff);
				}
				else
				{
					TRACE(_T("Get() Item failed %s\n"), ErrorString(hRes));
				}
			}
			else
			{
				TRACE(_T("QI() failed \n"));
			}
		}
		else
		{
			TRACE(_T("Get() targetInst failed %s\n"), ErrorString(hRes));
			m_pOutputList->AddString(_T("programming error"));
		} //endif Get()

	} // endfor

	SysFreeString(propName);
	SysFreeString(objName);
	VariantClear(&pVal);
	VariantClear(&vUnk);

	TRACE(_T("walked indication list\n"));

	return S_OK;
}
Esempio n. 18
0
void BString::adoptBSTR(BSTR bstr)
{
    if (m_bstr)
        SysFreeString(m_bstr);
    m_bstr = bstr;
}
Esempio n. 19
0
static HRESULT WINAPI IRecordInfoImpl_RecordClear(IRecordInfo *iface, PVOID pvExisting)
{
    IRecordInfoImpl *This = impl_from_IRecordInfo(iface);
    int i;
    PVOID var;

    TRACE("(%p)->(%p)\n", This, pvExisting);

    if(!pvExisting)
        return E_INVALIDARG;

    for(i=0; i<This->n_vars; i++) {
        if(This->fields[i].varkind != VAR_PERINSTANCE) {
            ERR("varkind != VAR_PERINSTANCE\n");
            continue;
        }
        var = ((PBYTE)pvExisting)+This->fields[i].offset;
        switch(This->fields[i].vt) {
        case VT_BSTR:
            SysFreeString(*(BSTR*)var);
            *(BSTR*)var = NULL;
            break;
        case VT_I2:
        case VT_I4:
        case VT_R4:
        case VT_R8:
        case VT_CY:
        case VT_DATE:
        case VT_ERROR:
        case VT_BOOL:
        case VT_DECIMAL:
        case VT_I1:
        case VT_UI1:
        case VT_UI2:
        case VT_UI4:
        case VT_I8:
        case VT_UI8:
        case VT_INT:
        case VT_UINT:
        case VT_HRESULT:
            break;
        case VT_INT_PTR:
        case VT_UINT_PTR:
            *(void**)var = NULL;
            break;
        case VT_SAFEARRAY:
            SafeArrayDestroy(var);
            break;
        case VT_UNKNOWN:
        case VT_DISPATCH:
        {
            IUnknown *unk = *(IUnknown**)var;
            if (unk)
                IUnknown_Release(unk);
            *(void**)var = NULL;
            break;
        }
        default:
            FIXME("Not supported vt = %d\n", This->fields[i].vt);
            break;
        }
    }

    return S_OK;
}
Esempio n. 20
0
int main(void)
{
  IUnknown *iunk;
  ITiEmuOLE *tiemuOLE;
  VARIANT_BOOL ready;
  BSTR command;

  fprintf(stdout, "Initializing OLE...\n");
  if (OleInitialize(0) != S_OK) {puts("OLE error. (#1)");return 1;}

  fprintf(stdout, "Getting object...");
  if (GetActiveObject(&CLSID_TiEmuOLE,NULL,&iunk) != S_OK || !iunk) 
  {
    // TiEmu not running
    // Figure out the path of TiEmu and run it
    char buffer[2049];
    HKEY hKey;
    DWORD type, size=2048;

    if (RegOpenKeyEx(HKEY_CLASSES_ROOT,"CLSID\\{B2A17B13-9D6F-4DD4-A2A9-6FE06ADC1D33}\\LocalServer32",0, KEY_QUERY_VALUE,&hKey))
      {OleUninitialize();puts("OLE error (#2).");return 2;}

    if (RegQueryValueEx(hKey,NULL,NULL,&type,buffer,&size) || type != REG_SZ)
      {RegCloseKey(hKey);OleUninitialize();puts("OLE error (#3).");return 3;}
    buffer[2048]=0;

    if (RegCloseKey(hKey))
      {OleUninitialize();puts("OLE error (#4).");return 4;}

    if ((int)ShellExecute(NULL,NULL,buffer,NULL,NULL,SW_SHOW)<=32)
      {OleUninitialize();puts("OLE error (#5).");return 5;}

    while (GetActiveObject(&CLSID_TiEmuOLE,NULL,&iunk) != S_OK || !iunk); // Wait for the object
  }
  fprintf(stdout, "Done !\n");

  fprintf(stdout, "Querying interface...\n");
  if (iunk->lpVtbl->QueryInterface(iunk,&IID_ITiEmuOLE,(void**)&tiemuOLE) != S_OK || !tiemuOLE)
    {OleUninitialize();puts("OLE error (#6).");return 6;}

  fprintf(stdout, "Waiting for ready... ");
  do 
  {
    if (tiemuOLE->lpVtbl->ready_for_transfers(tiemuOLE,&ready) != S_OK)
      {tiemuOLE->lpVtbl->Release(tiemuOLE);OleUninitialize();puts("OLE error (#7).");return 7;}
  } while (!ready);
  Sleep(10000); // give the emulated calculator time to react
  fprintf(stdout, "Done !\n");

  fprintf(stdout, "Turning calc on... ");
  if (tiemuOLE->lpVtbl->turn_calc_on(tiemuOLE,&ready) != S_OK || !ready)
    {tiemuOLE->lpVtbl->Release(tiemuOLE);OleUninitialize();puts("OLE error (#8).");return 8;}
  Sleep(3000); // give the emulated calculator time to react
  fprintf(stdout, "Done !\n");

  fprintf(stdout, "Sending command... ");
    command=SysAllocString(L"2+3");
  if (!command)
    {tiemuOLE->lpVtbl->Release(tiemuOLE);OleUninitialize();puts("OLE error (#9).");return 9;}

  if (tiemuOLE->lpVtbl->execute_command(tiemuOLE,command,&ready) != S_OK || !ready)
    {SysFreeString(command);tiemuOLE->lpVtbl->Release(tiemuOLE);
     OleUninitialize();puts("OLE error (#10).");return 10;}
  SysFreeString(command);
  fprintf(stdout, "Done !\n");

  fprintf(stdout, "Releasing...");
  tiemuOLE->lpVtbl->Release(tiemuOLE);
  OleUninitialize();
  fprintf(stdout, "Done !\n");

  return 0;
}
Esempio n. 21
0
/*****************************************************************************
 * データベースに接続します。
 *****************************************************************************/
int DbSqlCeClient::open()
{
	HRESULT hr;
	ULONG  count = 0;
	ULONG i, j;

	IDBProperties *pProp = NULL;
	// CompactのConnectionStringの指定可能なオプション数は、3が最大なので固定で確保します。
	DBPROPSET arInitPropSet[PROPSET_MAX] = {0};
	DBPROP    arProp1[4]= {0}, arProp2[10] = {0};

	//
	try{
		// インタフェースの生成
		hr = CoCreateInstance( m_sqlceVerGUID, NULL, CLSCTX_INPROC_SERVER,
				IID_IDBInitialize, (LPVOID*)&m_pDBinit);
		if( FAILED( hr ) )		throw(1);

		// プロパティの取得
		hr = m_pDBinit->QueryInterface(IID_IDBProperties, (void **)&pProp);
		if( FAILED( hr ) )		throw(2);

		// 最大数とDBPROPの配列を設定。
		arInitPropSet[0].cProperties = ARRAYSIZE(arProp1);
		arInitPropSet[0].rgProperties = arProp1;
		arInitPropSet[0].guidPropertySet = DBPROPSET_DBINIT;
		for( i = 0; i < ARRAYSIZE(arProp1); i ++ ){
			VariantInit( &(arProp1[i].vValue) );
		}

		arInitPropSet[1].cProperties = ARRAYSIZE(arProp2);
		arInitPropSet[1].rgProperties = arProp2;
		arInitPropSet[1].guidPropertySet = DBPROPSET_SSCE_DBINIT;
		for( i = 0; i < ARRAYSIZE(arProp2); i ++ ){
			VariantInit( &(arProp2[i].vValue) );
		}

		// プロパティの作成
		count = create_open_prop( arInitPropSet, ARRAYSIZE(arInitPropSet) );
		if( 0 == count ){
			throw(3);
		}
		else{
			hr = pProp->SetProperties( count, arInitPropSet );
			// プロパティのメモリ開放
			for( i = 0; i < count; i ++ ){
				for( j = 0; j < arInitPropSet[i].cProperties; j ++ ){
					if( VT_BSTR == arInitPropSet[i].rgProperties[j].vValue.vt ){
						SysFreeString( arInitPropSet[i].rgProperties[j].vValue.bstrVal );
					}
				}
			}
			pProp->Release();

			if( FAILED( hr ) )		throw(4);
		}

		// データベースに接続します。
		hr = m_pDBinit->Initialize();
        if( FAILED( hr ) ){
            throw(5);
        }

		m_IsOpened = true;

		// 次に必要なインタフェースを取得します。
		hr = m_pDBinit->QueryInterface( IID_IDBCreateSession, (void**)&m_pSession);
		if( FAILED( hr ) )		throw(6);

		//
		hr = m_pSession->CreateSession( NULL, IID_IDBCreateCommand,(IUnknown**) &m_pCrtCmd);
		if( FAILED( hr ) )		throw(7);

		//
		hr = m_pCrtCmd->CreateCommand( NULL, IID_ICommandText,(IUnknown**) &m_pCmdtext );
		if( FAILED( hr ) )		throw(8);
	}
	catch(const int err){
		if( m_IsOpened ){
			m_pDBinit->Uninitialize();
            m_IsOpened = false;
		}
		if( m_pCmdtext ){
			m_pCmdtext->Release();
			m_pCmdtext =NULL;
		}
		if( m_pCrtCmd ){
			m_pCrtCmd->Release();
			m_pCrtCmd = NULL;
		}
		if( m_pSession ){
			m_pSession->Release();
			m_pSession = NULL;
		}
		if( pProp ){
			pProp->Release();
			pProp = NULL;
		}
		if( m_pDBinit ){
			m_pDBinit->Release();
			m_pDBinit = NULL;
		}

		return err;
	}

	return 0;
}