// Displays a property assumed to be in string form.
void DisplayStringProperty(
    IPortableDeviceValues*  pProperties,
    REFPROPERTYKEY          key,
    PCWSTR                  pszKey)
{
    PWSTR   pszValue = NULL;
    HRESULT hr = pProperties->GetStringValue(key,&pszValue);
    if (SUCCEEDED(hr))
    {
        // Get the length of the string value so we
        // can output <empty string value> if one
        // is encountered.
        CAtlStringW strValue;
        strValue = pszValue;
        if (strValue.GetLength() > 0)
        {
            printf("%ws: %ws\n",pszKey, pszValue);
        }
        else
        {
            printf("%ws: <empty string value>\n", pszKey);
        }
    }
    else
    {
        printf("%ws: <Not Found>\n", pszKey);
    }

    // Free the allocated string returned from the
    // GetStringValue method
    CoTaskMemFree(pszValue);
    pszValue = NULL;
}
Beispiel #2
0
bool
CDeviceView::EnableSelectedDevice(
    _In_ bool Enable,
    _Out_ bool &NeedsReboot
    )
{
    CDeviceNode *Node = dynamic_cast<CDeviceNode *>(GetSelectedNode());
    if (Node == nullptr) return false;

    if (Enable == false)
    {
        CAtlStringW str;
        if (str.LoadStringW(g_hThisInstance, IDS_CONFIRM_DISABLE))
        {
            if (MessageBoxW(m_hMainWnd,
                str,
                Node->GetDisplayName(),
                MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) != IDYES)
            {
                return false;
            }
        }
    }

    return Node->EnableDevice(Enable, NeedsReboot);
}
Beispiel #3
0
// Initialize the enumeration context
VOID WpdObjectEnumerator::InitializeEnumerationContext(
    WpdObjectEnumeratorContext* pEnumeratorContext,
    CAtlStringW                 strParentObjectID)
{
    if (pEnumeratorContext == NULL)
    {
        return;
    }

    // Initialize the enumeration context with the parent object identifier
    pEnumeratorContext->m_strParentObjectID = strParentObjectID;

    // Our sample driver has a very simple object structure where we know
    // how many children are under each parent.
    // The eumeration context is initialized below with this information.
    if (strParentObjectID.CompareNoCase(L"") == 0)
    {
        // Clients passing an 'empty' string for the parent are asking for the
        // 'DEVICE' object.  We should return 1 child in this case.
        pEnumeratorContext->m_TotalChildren = 1;
    }
    else if (strParentObjectID.CompareNoCase(WPD_DEVICE_OBJECT_ID) == 0)
    {
        // The device object contains 1 child (the storage object).
        pEnumeratorContext->m_TotalChildren = 1;
    }
    // If the sensor objects have children, add them here...
    else 
    {
        // The sensor object contains 0 children.
        pEnumeratorContext->m_TotalChildren = 0;
    }
}
Beispiel #4
0
CNetRequestImpl::CNetRequestImpl(const char* method, const String& strUrl)
{
    pszErrFunction = NULL;
    hInet = NULL, hConnection = NULL, hRequest = NULL;
    memset(&uri, 0, sizeof(uri) );
    m_pInstance = this;

    CAtlStringW strUrlW(strUrl.c_str());

    do 
    {
        if ( !isLocalHost(strUrl.c_str()) && !SetupInternetConnection(strUrlW) )
        {
            pszErrFunction = L"SetupInternetConnection";
            break;
        }

        hInet = InternetOpen(_T("rhodes-wm"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL );
        if ( !hInet ) 
        {
            pszErrFunction = L"InternetOpen";
            break;
        }

        DWORD dwUrlLength = 1024;
        CAtlStringW strCanonicalUrlW;
        if ( !InternetCanonicalizeUrl( strUrlW, strCanonicalUrlW.GetBuffer(dwUrlLength), &dwUrlLength, 0) )
        {
            pszErrFunction = _T("InternetCanonicalizeUrl");
            break;
        }
        strCanonicalUrlW.ReleaseBuffer();

		alloc_url_components( &uri, strCanonicalUrlW );
        if( !InternetCrackUrl( strCanonicalUrlW, strCanonicalUrlW.GetLength(), 0, &uri ) ) 
        {
			pszErrFunction = L"InternetCrackUrl";
			break;
		}

        hConnection = InternetConnect( hInet, uri.lpszHostName, uri.nPort, _T("anonymous"), NULL, 
          INTERNET_SERVICE_HTTP, 0, 0 );
        if ( !hConnection ) 
        {
            pszErrFunction = L"InternetConnect";
            break;
        }

        strReqUrlW = uri.lpszUrlPath;
        strReqUrlW += uri.lpszExtraInfo;
        hRequest = HttpOpenRequest( hConnection, CAtlStringW(method), strReqUrlW, NULL, NULL, NULL, 
          INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE, NULL );
        if ( !hRequest ) 
        {
            pszErrFunction = L"HttpOpenRequest";
            break;
        }

    }while(0);
}
Beispiel #5
0
HRESULT CDBHistory::UpdateHistory(HDBCONNECTION hDBConnection,
									int nIndex,
									LPCWSTR lpszComment,
									BSTR* pbstrResult)
{
	HRESULT hr = E_FAIL;

	IMT::CDBConnection* pDBConnection = reinterpret_cast<IMT::CDBConnection*>(hDBConnection);
	if (pDBConnection != NULL)
	{
		ATL::CCommand<ATL::CDynamicAccessor> Command;

		ATL::CDBPropSet _DBPropSet(DBPROPSET_ROWSET);
		pDBConnection->GetRowsetProperties(&_DBPropSet);

		CAtlStringW strCommand;

		strCommand.Format(QUERY_HISTORY_UPDATE, lpszComment, nIndex);

		hr = Command.Open(ATL::CSession(*pDBConnection), strCommand, &_DBPropSet);
		if (hr != S_OK)
		{
			if (pbstrResult != NULL)
				IMT::GetDBErrorString(hr, pbstrResult);
		}
		else
		{
			TRACE(_T(":::[CDBHistory]-[UPDATE] SUCCEEDED :::\n"));
		}
	}

	return hr;
}
Beispiel #6
0
HRESULT CDBConnection::OpenDataSource(LPCWSTR lpszPathFileName, LPCWSTR lpszUserName, LPCWSTR lpszPassword)
{
	_ASSERTE(lpszPathFileName != NULL);
	_ASSERTE(lpszUserName != NULL);
	_ASSERTE(lpszPassword != NULL);

	USES_CONVERSION;

	HRESULT hr = E_FAIL;

	if (lpszPathFileName != NULL && lpszUserName != NULL && lpszPassword != NULL)
	{
		if (::PathFileExists(lpszPathFileName))
		{
			CAtlStringW strConnection;

			strConnection.Format(
#if defined(USES_JET_OLEDB_DRIVER)
				L"Provider=Microsoft.Jet.OLEDB.4.0;"
#else
				L"Provider=Microsoft.ACE.OLEDB.12.0;"
#endif
				L"Data Source=%s;"
				L"User ID=%s;"
				L"Mode=Share Deny None;"
				L"Extended Properties=\"\";"
				L"Jet OLEDB:System database=\"\";"
				L"Jet OLEDB:Registry Path=\"\";"
				L"Jet OLEDB:Database Password=\"%s\";"
				L"Jet OLEDB:Engine Type=5;"
				L"Jet OLEDB:Database Locking Mode=1;"
				L"Jet OLEDB:Global Partial Bulk Ops=2;"
				L"Jet OLEDB:Global Bulk Transactions=1;"
				L"Jet OLEDB:New Database Password=\"\";"
				L"Jet OLEDB:Create System Database=False;"
				L"Jet OLEDB:Encrypt Database=False;"
				L"Jet OLEDB:Don't Copy Locale on Compact=False;"
				L"Jet OLEDB:Compact Without Replica Repair=False;"
				L"Jet OLEDB:SFP=False"
				, lpszPathFileName, lpszUserName, lpszPassword);

			hr = Open(LPCWSTR(strConnection));

			if (FAILED(hr))
			{
#ifdef _DEBUG
				ATL::AtlTraceErrorRecords(hr);
#endif
			}
		}
		else
			hr = HRESULT_FROM_WIN32(::GetLastError());
	}
	else
		hr = E_POINTER;


	return hr;
}
LRESULT CPropertyEditWindow::OnAdd(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
    CPropertyAddDialog dialog;

    // Add the property categories
    for(size_t i = 0; i < m_arrPropertyInfo.GetCount(); i++)
    {
        if(m_arrPropertyInfo.GetAt(i)->IsWriteable() == S_OK)
        {
            LPWSTR szPropertyCategory;
            TED_ATTRIBUTE_CATEGORY Category;
            m_arrPropertyInfo.GetAt(i)->GetPropertyInfoName(&szPropertyCategory, &Category);
        
            dialog.AddPropertyCategory(szPropertyCategory, Category, (DWORD) i);
        
            CoTaskMemFree(szPropertyCategory);
        }
    }
    
    // Fill dialog properties
    if(dialog.DoModal() == IDOK)
    {
        DWORD dwIndex = dialog.GetChosenCategory();
        CAtlStringW strName = dialog.GetChosenProperty();
        CAtlStringW strValue = dialog.GetValue();
        ITedPropertyInfo* pPropertyInfo = m_arrPropertyInfo.GetAt(dwIndex);
        
        for(DWORD i = 0; i < TEDGetAttributeListLength(); i++)
        {
            if(TEDGetAttributeName(i) == strName)
            {
                DWORD dwPropertyCount;
                
                pPropertyInfo->GetPropertyCount(&dwPropertyCount);
                pPropertyInfo->SetProperty(dwPropertyCount, strName.GetBuffer(), TEDGetAttributeType(i), strValue.GetBuffer());

                RECT clientRect;
                GetClientRect(&clientRect);
                DWORD dwViewWidth = clientRect.right - clientRect.left - 5;
        
                RECT rectNextLabel;
                rectNextLabel.top = 5 + (ms_LabelHeight * dwPropertyCount);
                rectNextLabel.left = 5;
                rectNextLabel.right = rectNextLabel.left + dwViewWidth / 2;
                rectNextLabel.bottom = rectNextLabel.top + ms_LabelHeight;
                
                CreatePropertyInterfaceForIndex(dwIndex, dwPropertyCount, rectNextLabel);
                ResizeChildren();

                break;
            }
        }
    }

    return 0;
}
Beispiel #8
0
DWORD IGFrame::GetImageType (LPCWSTR lpPicturePath)
{
	CAtlStringW cstrExtension (lpPicturePath);
	if (cstrExtension.GetLength() < 5)
		return CXIMAGE_FORMAT_UNKNOWN;	
	cstrExtension = cstrExtension.Right (4);
	// supported file extenstion length may be 2, 3 or 4
	if (cstrExtension.GetAt (0) == L'.')
		cstrExtension = cstrExtension.Right (3);
	else if (cstrExtension.GetAt (1) == L'.')
		cstrExtension = cstrExtension.Right (2);		
	cstrExtension.MakeUpper();
	if (cstrExtension == L"BMP")
		return CXIMAGE_FORMAT_BMP;
	else if (cstrExtension == L"JPG")
		return CXIMAGE_FORMAT_JPG;
	else if (cstrExtension == L"PNG")
		return CXIMAGE_FORMAT_PNG;
	else if (cstrExtension == L"ICO")
		return CXIMAGE_FORMAT_ICO;
	else if (cstrExtension == L"GIF")
		return CXIMAGE_FORMAT_GIF;
	else if (cstrExtension == L"TIF")
		return CXIMAGE_FORMAT_TIF;
	else if (cstrExtension == L"IG")
		return CXIMAGE_FORMAT_IG;
	return CXIMAGE_FORMAT_UNKNOWN;
}
HRESULT CDefaultRecordGraphBuilder::CreateAudioSrcFilter(IBaseFilter** ppSrcFilter)
{
	CHECK_POINTER_RETURN_VALUE_IF_FAIL(ppSrcFilter, E_POINTER);
	HRESULT hr = E_FAIL;

	CFSharePtr<FTL::CFDShowHardwareMgr> spAudioCaptureHardwareMgr(new FTL::CFDShowHardwareMgr());

	DX_VERIFY_EXCEPT1(spAudioCaptureHardwareMgr->Refresh(&CLSID_AudioInputDeviceCategory), S_FALSE);
	if (S_OK == hr)
	{
		CAtlStringW	wstrAudioInputString;
		if (m_Param.strAudioInputName.IsEmpty())
		{
			//get first -- TODO: use enum
			FTL::HardwareMonikerInfoContainer&	rHardwares = spAudioCaptureHardwareMgr->GetAllHardwares();
			if (!rHardwares.empty())
			{
				wstrAudioInputString = (*rHardwares.begin())->wachFriendlyName;
				//m_spAudioCaptureHardwareMgr->GetDefault
			}
		}
		else
		{
			//User Save audio
			wstrAudioInputString = CT2W(m_Param.strAudioInputName);
		}

		if (!wstrAudioInputString.IsEmpty())
		{
			CComPtr<IBaseFilter>	spAudioSrcFilter;
			DX_VERIFY(spAudioCaptureHardwareMgr->GetBindObject(wstrAudioInputString, IID_IBaseFilter, (void **)&spAudioSrcFilter));
			if (SUCCEEDED(hr)) 
			{
				DX_VERIFY(m_spGraphBuilder->AddFilter(spAudioSrcFilter, wstrAudioInputString));
				if (SUCCEEDED(hr))
				{
					*ppSrcFilter = spAudioSrcFilter.Detach();
					//(*ppSrcFilter)->AddRef();
				}
			}
			else
			{
				//maybe user change audio device ?
			}
		}
	}
	return hr;

}
Beispiel #10
0
HRESULT CDBHistory::AddHistory(HDBCONNECTION hDBConnection, 
								DB_HISTORY_COMMON dbHistory,
								BSTR* pbstrResult)
{
	HRESULT hr = E_FAIL;

	IMT::CDBConnection* pDBConnection = reinterpret_cast<IMT::CDBConnection*>(hDBConnection);
	if (pDBConnection != NULL)
	{
		ATL::CCommand<ATL::CDynamicAccessor> Command;

		ATL::CDBPropSet _DBPropSet(DBPROPSET_ROWSET);
		pDBConnection->GetRowsetProperties(&_DBPropSet);

		CAtlStringW strCommand;

		strCommand.Format(QUERY_HISTORY_INSERT,
							dbHistory.dateTime.year,
							dbHistory.dateTime.month,
							dbHistory.dateTime.day,
							dbHistory.dateTime.hour,
							dbHistory.dateTime.minute,
							dbHistory.dateTime.second,
							dbHistory.nLRUIdx,
							dbHistory.wszSerialNum,
							dbHistory.wszSRUName,
							dbHistory.nInspectType,
							dbHistory.wszItem,
							dbHistory.nBIT,
							dbHistory.lPresentedResult,
							dbHistory.wszID,
							dbHistory.wszComment,
							dbHistory.l_Index);

		hr = Command.Open(ATL::CSession(*pDBConnection), strCommand, &_DBPropSet);
		if (hr != S_OK)
		{
			if (pbstrResult != NULL)
				IMT::GetDBErrorString(hr, pbstrResult);
		}
		else
		{
			TRACE(_T(":::[CDBHistory]-[INSERT] SUCCEEDED :::\n"));
		}
	}

	return hr;
}
Beispiel #11
0
HRESULT CDBHistroy_BIT::AddHistoryBIT(HDBCONNECTION hDBConnection, 
									DB_BIT dbBIT,
									BSTR* pbstrResult)
{
	HRESULT hr = E_FAIL;

	IMT::CDBConnection* pDBConnection = reinterpret_cast<IMT::CDBConnection*>(hDBConnection);
	if (pDBConnection != NULL)
	{
		ATL::CCommand<ATL::CDynamicAccessor> Command;

		ATL::CDBPropSet _DBPropSet(DBPROPSET_ROWSET);
		pDBConnection->GetRowsetProperties(&_DBPropSet);

		CAtlStringW strCommand;

		strCommand.Format(QUERY_H_BIT_INSERT,
							dbBIT.dbHistory.dateTime.year,
							dbBIT.dbHistory.dateTime.month,
							dbBIT.dbHistory.dateTime.day,
							dbBIT.dbHistory.dateTime.hour,
							dbBIT.dbHistory.dateTime.minute,
							dbBIT.dbHistory.dateTime.second,
							dbBIT.wszInstrumentName,
							dbBIT.dbHistory.nBIT,
							dbBIT.wszInspectionItem,
							dbBIT.dbHistory.lPresentedResult,
							dbBIT.dbHistory.wszComment,
							dbBIT.bMainSection);

		hr = Command.Open(ATL::CSession(*pDBConnection), strCommand, &_DBPropSet);
		if (hr != S_OK)
		{
			if (pbstrResult != NULL)
				IMT::GetDBErrorString(hr, pbstrResult);
		}
		else
		{
			TRACE(_T(":::[CDBHistroy_BIT]-[INSERT] SUCCEEDED :::\n"));
		}
	}

	/*SELECT MAX(rowId) FROM property */

	return hr;
}
Beispiel #12
0
HRESULT CDBHistroy_External::AddHistoryExternal(HDBCONNECTION hDBConnection, 
									DB_EXTERNAL dbExternal,
									BSTR* pbstrResult)
{
	HRESULT hr = E_FAIL;

	IMT::CDBConnection* pDBConnection = reinterpret_cast<IMT::CDBConnection*>(hDBConnection);
	if (pDBConnection != NULL)
	{
		ATL::CCommand<ATL::CDynamicAccessor> Command;

		ATL::CDBPropSet _DBPropSet(DBPROPSET_ROWSET);
		pDBConnection->GetRowsetProperties(&_DBPropSet);

		CAtlStringW strCommand;

		strCommand.Format(QUERY_H_EXTERNAL_INSERT,
						dbExternal.dbHistory.dateTime.year,
						dbExternal.dbHistory.dateTime.month,
						dbExternal.dbHistory.dateTime.day,
						dbExternal.dbHistory.dateTime.hour,
						dbExternal.dbHistory.dateTime.minute,
						dbExternal.dbHistory.dateTime.second,
						dbExternal.wszInspectionItem,
						dbExternal.wszLRUPort,
						dbExternal.wszCable,
						dbExternal.wszInspectionSignal,
						dbExternal.wszInterlockPort,
						dbExternal.dbHistory.bResult,
						dbExternal.dbHistory.wszID,
						dbExternal.dbHistory.wszComment);

		hr = Command.Open(ATL::CSession(*pDBConnection), strCommand, &_DBPropSet);
		if (hr != S_OK)
		{
			if (pbstrResult != NULL)
				IMT::GetDBErrorString(hr, pbstrResult);
		}
		else
		{
			TRACE(_T(":::[CDBHistroy_External]-[INSERT] SUCCEEDED :::\n"));
		}
	}

	return hr;
}
LRESULT CPropertyEditWindow::OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
    bool fAllSucceeded = true;
    
    for(size_t i = 0; i < m_arrPropertyInfo.GetCount(); i++)
    {
        ITedPropertyInfo* pPropertyInfo = m_arrPropertyInfo.GetAt(i);
        PropertyInfoDisplay* pDisplay = m_arrPropertyInfoDisplay.GetAt(i);
        for(size_t j = 0; j < pDisplay->m_arrLabels.GetCount(); j++)
        {
            VARTYPE vt = pDisplay->m_arrVartypes.GetAt(j);
            
            if(vt == VT_EMPTY || vt == VT_UNKNOWN || vt == (VT_VECTOR | VT_UI1)) continue;
        
            LPWSTR strName, strValue;

            // Get label text (property name)
            int nameLen = pDisplay->m_arrLabels.GetAt(j)->GetWindowTextLength();
            strName = new WCHAR[nameLen + 1];
            if(NULL == strName) continue;
            pDisplay->m_arrLabels.GetAt(j)->GetWindowText(strName, nameLen + 1);

            // Get edit text (property value)
            int valueLen = pDisplay->m_arrEdits.GetAt(j)->GetWindowTextLength();
            strValue = new WCHAR[valueLen + 1];
            if(NULL == strValue) { delete[] strName; continue; }
            pDisplay->m_arrEdits.GetAt(j)->GetWindowText(strValue, valueLen + 1);

            HRESULT hr = pPropertyInfo->SetProperty((DWORD) j, strName, vt, strValue);
            if( FAILED(hr) && fAllSucceeded)
            {
                CAtlStringW strError;
                strError.FormatMessage(IDS_E_SAVE_PROP, hr);
                MessageBox(strError, LoadAtlString(IDS_ERROR), MB_OK);
                
                fAllSucceeded = false;
            }

            delete[] strName;
            delete[] strValue;
        }
    }
    
    return 0;
}
Beispiel #14
0
HRESULT WpdService::CheckRequestFilename(
    _In_    LPCWSTR pszRequestFilename)
{
    HRESULT     hr                 = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
    CAtlStringW strRequestFilename = pszRequestFilename;

    // For simplicity, the request filename happens to be the same as the service object ID
    if (strRequestFilename.CompareNoCase(m_pGattService->GetRequestFilename()) == 0)
    {
        hr = S_OK;
    }
    else
    {
        CHECK_HR(hr, "Unknown request filename %ws received", pszRequestFilename);
    }

    return hr;
}
Beispiel #15
0
HRESULT CDBHistory::QueryHistory(HDBCONNECTION hDBConnection, 
						LPCWSTR lpszSerialNum,
						LPDB_HISTORY_COMMON pRecord,
						BSTR* pbstrResult)

{
	HRESULT hr = E_FAIL;

	IMT::CDBConnection* pDBConnection = reinterpret_cast<IMT::CDBConnection*>(hDBConnection);
	if (pDBConnection != NULL)
	{
		ATL::CCommand<ATL::CAccessor<IMT::CDBHistory>> Command;

		ATL::CDBPropSet _DBPropSet(DBPROPSET_ROWSET);
		pDBConnection->GetRowsetProperties(&_DBPropSet);

		CAtlStringW strCommand;
		CAtlStringW strTemp;
		strCommand.Format(QUERY_HISTORY_SELECT L" WHERE ");

		BOOL isExist = FALSE;

		strTemp.Format(L"SerialNum = '%s'", lpszSerialNum);//L"SerialNum = '%s'", lpszSerial);//
		strCommand += strTemp;

		hr = Command.Open(ATL::CSession(*pDBConnection), strCommand, &_DBPropSet);
		if (hr != S_OK)
		{
			if (pbstrResult != NULL)
				IMT::GetDBErrorString(hr, pbstrResult);
		}
		else
		{
			TRACE(_T(":::[CDBUser]-[QUERY] SUCCEEDED :::\n"));

			hr = Command.MoveNext();
			if (hr == S_OK)
				::CopyMemory(pRecord, LPDB_HISTORY_COMMON(Command), sizeof(DB_HISTORY_COMMON));
		}
	}

	return hr;
}
Beispiel #16
0
void CNetRequestImpl::ErrorMessage(LPCTSTR pszFunction)
{ 
    // Retrieve the system error message for the last-error code
    LPTSTR pszMessage = NULL;
    DWORD dwLastError = GetLastError(); 

    DWORD dwLen = FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        //FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_FROM_HMODULE|
        FORMAT_MESSAGE_IGNORE_INSERTS,
        GetModuleHandle( _T("wininet.dll") ),
        dwLastError,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&pszMessage,
        0, NULL );

    CAtlStringW strExtError;
    if ( dwLastError == ERROR_INTERNET_EXTENDED_ERROR )
    {
        DWORD  dwInetError =0, dwExtLength = 0;
        InternetGetLastResponseInfo( &dwInetError, NULL, &dwExtLength );

        if ( dwExtLength > 0 )
        {
            InternetGetLastResponseInfo( &dwInetError, strExtError.GetBuffer(dwExtLength+1), &dwExtLength );
            strExtError.ReleaseBuffer();
        }
    }

    rho::LogMessage oLogMsg(__FILE__, __LINE__, L_ERROR, LOGCONF(), getLogCategory() );
    oLogMsg + "Call " + pszFunction + " failed. With code : " + dwLastError;

    if ( pszMessage ) 
        oLogMsg + ".Message: " + pszMessage;
    if ( strExtError.GetLength() )
        oLogMsg + ".Extended info: " + strExtError.GetString();

    if ( pszMessage )
        LocalFree(pszMessage);
}
Beispiel #17
0
ACCESS_SCOPE FakeDevice::GetAccessScope(
    _In_    IPortableDeviceValues* pParams)
{
    ACCESS_SCOPE Scope      = FULL_DEVICE_ACCESS;
    LPWSTR       pszFileName = NULL;

    // For simplicity, our request filename is the same as the the service object ID
    if (pParams && (pParams->GetStringValue(PRIVATE_SAMPLE_DRIVER_REQUEST_FILENAME, &pszFileName) == S_OK))
    {
        CAtlStringW strRequestFilename = pszFileName;
        // For simplicity, our request filename is the same as the the service object ID
        // Case-insensitive comparison is required
        if (strRequestFilename.CompareNoCase(m_ContactsService.GetRequestFilename()) == 0)
        {
            Scope = CONTACTS_SERVICE_ACCESS;
        }
    }

    CoTaskMemFree(pszFileName);
    return Scope;
}
Beispiel #18
0
bool
CDeviceView::UninstallSelectedDevice(
    )
{
    CDeviceNode *Node = dynamic_cast<CDeviceNode *>(GetSelectedNode());
    if (Node == nullptr) return false;

    CAtlStringW str;
    if (str.LoadStringW(g_hThisInstance, IDS_CONFIRM_UNINSTALL))
    {
        if (MessageBoxW(m_hMainWnd,
            str,
            Node->GetDisplayName(),
            MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) != IDYES)
        {
            return false;
        }
    }

    return Node->UninstallDevice();
}
HRESULT CIIS7XMLConfigHelper::RemoveModuleNodes(IXMLDOMDocument* pDoc, LPCSTR pszModuleName)
{
	if (pDoc == NULL || pszModuleName == NULL)
		return E_POINTER;

	CAtlStringW sQuery;
	sQuery.Format(L"//add[@name='%hs']", pszModuleName);	

	CComBSTR bsQuery(sQuery);

	CComPtr<IXMLDOMNodeList> pModuleNodes;
	HRESULT hr = pDoc->selectNodes(bsQuery, &pModuleNodes);

	if (hr == S_OK)
	{
		LONG nModules = 0;
		hr = pModuleNodes->get_length(&nModules);

		for (LONG i = 0; i < nModules; i++)
		{
			CComPtr<IXMLDOMNode> pModuleNode;
			hr = pModuleNodes->get_item(i, &pModuleNode);
			if (hr != S_OK || pModuleNode == NULL)
				continue;

			CComPtr<IXMLDOMNode> pParentNode;
			hr = pModuleNode->get_parentNode(&pParentNode);
			if (hr != S_OK || pParentNode == NULL)
				continue;

			CComPtr<IXMLDOMNode> pTemp;
			hr = pParentNode->removeChild(pModuleNode, &pTemp);
			if (hr != S_OK)
				break;
		}
	}

	return hr;
}
Beispiel #20
0
HRESULT CDBHistroy_BIT::QueryHistoryBIT_InspRecord(HDBCONNECTION hDBConnection,
													long l_Index,
													LPDB_BIT pRecord,
													BSTR* pbstrResult)
{
	HRESULT hr = E_FAIL;

	IMT::CDBConnection* pDBConnection = reinterpret_cast<IMT::CDBConnection*>(hDBConnection);
	if (pDBConnection != NULL)
	{
		ATL::CCommand<ATL::CAccessor<IMT::CDBHistroy_BIT>> Command;

		ATL::CDBPropSet _DBPropSet(DBPROPSET_ROWSET);
		pDBConnection->GetRowsetProperties(&_DBPropSet);

		CAtlStringW strCommand;
		CAtlStringW strTemp;

		strCommand.Format(QUERY_H_BIT_SELECT L" WHERE Index = %d", l_Index);
		
		hr = Command.Open(ATL::CSession(*pDBConnection), strCommand, &_DBPropSet);
		if (hr != S_OK)
		{
			if (pbstrResult != NULL)
				IMT::GetDBErrorString(hr, pbstrResult);
		}
		else
		{
			TRACE(_T(":::[CDBHistroy_BIT]-[QUERY] SUCCEEDED :::\n"));
			hr = Command.MoveNext();
			if (hr == S_OK)
				::CopyMemory(pRecord, LPDB_BIT(Command), sizeof(DB_BIT));
		}
	}

	return hr;
}
Beispiel #21
0
String CNetRequestImpl::makeClientCookie()
{
    DWORD nIndex = 0;
    String cookie;
    while(true)
    {
        CAtlStringW strCookie;
        DWORD dwLen = 0;
        if( !HttpQueryInfo( hRequest, HTTP_QUERY_SET_COOKIE, null, &dwLen, &nIndex) )
        {   
            DWORD dwErr = ::GetLastError();
            if ( dwErr == ERROR_HTTP_HEADER_NOT_FOUND  )
                break;

            if ( dwErr != ERROR_INSUFFICIENT_BUFFER )
            {
                pszErrFunction = L"HttpQueryInfo";
                break;
            }
        }
        if( !HttpQueryInfo( hRequest, HTTP_QUERY_SET_COOKIE, strCookie.GetBuffer(dwLen), &dwLen, &nIndex) )
        {
            pszErrFunction = L"HttpQueryInfo";
            break;
        }
        strCookie.ReleaseBuffer();

        URI::parseCookie(common::convertToStringA(strCookie.GetString()).c_str(), cookie);
    }
    if (pszErrFunction)
        return "";

//    if ( cookie.strAuth.length() > 0 || cookie.strSession.length() >0 )
//        return cookie.strAuth + ";" + cookie.strSession + ";";

    return cookie;
}
Beispiel #22
0
/**
 *  This method is called to populate PROPERTYKEYs found on objects.
 *
 *  The parameters sent to us are:
 *  wszObjectID - the object whose supported resource keys are being requested
 *  pKeys - An IPortableDeviceKeyCollection to be populated with supported PROPERTYKEYs
 *
 *  The driver should:
 *  Add PROPERTYKEYs pertaining to the specified object.
 */
HRESULT WpdObjectResources::GetSupportedResourcesForObject(
    _In_ LPCWSTR                       wszObjectID,
    _In_ IPortableDeviceKeyCollection* pKeys)
{
    HRESULT     hr = S_OK;
    CAtlStringW strObjectID;

    if ((wszObjectID == NULL) ||
        (pKeys       == NULL))
    {
        hr = E_INVALIDARG;
        return hr;
    }

    strObjectID = wszObjectID;

    if (strObjectID.CompareNoCase(README_FILE_OBJECT_ID) == 0)
    {
        hr = pKeys->Add(WPD_RESOURCE_DEFAULT);
        CHECK_HR(hr, "Failed to set WPD_RESOURCE_DEFAULT");
    }

    return hr;
}
    void ProcessSolution(UI& ui, const doctor_dump::HaveSolutionResponse& solution)
    {
        m_log.Info(_T("Process solution..."));
        switch (solution.type)
        {
        case ns4__HaveSolutionResponse_SolutionType__Url:
            if (!solution.askConfirmation || ui.AskGetSolution(CSolutionDlg::Read))
            {
                CAtlStringW url = solution.url.c_str();
                url.Replace(L"{ClientID}", solution.clientID.c_str());
                url.Replace(L"{ProblemID}", ToString(solution.problemID));
                url.Replace(L"{DumpGroupID}", ToString(solution.dumpGroupID));
                url.Replace(L"{DumpID}", ToString(solution.dumpID));
                if (url.Find(L"http://") == 0 || url.Find(L"https://") == 0)
                    ShellExecute(NULL, _T("open"), CW2CT(url), NULL, NULL, SW_SHOWNORMAL);
            }
            break;
#ifdef REMOTE_CODE_DOWNLOAD_AND_EXECUTION
        case ns4__HaveSolutionResponse_SolutionType__Exe:
            if (!solution.askConfirmation || ui.AskGetSolution(CSolutionDlg::Install))
            {
                CAtlFile hFile(CreateFile(m_patch, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL));
                if (hFile == INVALID_HANDLE_VALUE)
                    throw runtime_error("failed to create solution.exe file");
                if (FAILED(hFile.Write(&solution.exe[0], static_cast<DWORD>(solution.exe.size()))))
                    throw runtime_error("failed to write solution.exe file");
                hFile.Close();

                STARTUPINFO si = {};
                si.cb = sizeof(si);
                PROCESS_INFORMATION pi = {};
                if (!CreateProcess(NULL, m_patch.GetBuffer(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
                    throw runtime_error("failed to start solution.exe");
                CloseHandle(pi.hThread);
                CloseHandle(pi.hProcess);
            }
            break;
#endif
        default:
            throw runtime_error("Unknown SolutionType");
        }
    }
void CVisualNode::Draw(CVisualDrawContext & Ctx)
{
    RECT rect;
    size_t n;

    Ctx.SelectSmallFont();

    if(IsSelected())
    {
        Ctx.SelectPen(m_clrSelectedBorder, 2);
    }
    else
    {
        Ctx.SelectPen(m_clrLine, 1);
    }

    // select colors
    Ctx.SelectSolidBrush(m_clrFill);

    // draw rect
    Ctx.MapRect(m_Rect, rect);
    Rectangle(Ctx.DC(), rect.left, rect.top, rect.right, rect.bottom);

    if(!m_strLabel.IsEmpty()) 
    {
        COLORREF oldColor = SetTextColor(Ctx.DC(), m_clrLine);
        Ctx.SelectSolidBrush(RGB(0, 0, 0));
        SetBkColor(Ctx.DC(), m_clrFill);

        rect.left += 5;
        rect.right -= 5;
        rect.top +=5;
        
        DrawText(Ctx.DC(), m_strLabel, m_strLabel.GetLength(), &rect, DT_WORDBREAK);

        SetTextColor(Ctx.DC(), oldColor);
    }

    if(m_fTopoError)
    {
        COLORREF oldColor = SetTextColor(Ctx.DC(), m_clrErrorText);
        rect.top += 10;

        CAtlStringW errString = LoadAtlString(IDS_E_TOPO_RESOLUTION);
        DrawText(Ctx.DC(), errString, errString.GetLength(), &rect, DT_WORDBREAK);

        SetTextColor(Ctx.DC(), oldColor);
    }

    Ctx.PushState();

    Ctx.ShiftCoordinates(m_Rect.x(), m_Rect.y());
    
    // draw pins
    for(n = 0; n < m_InputPins.GetCount(); n++)
    {
        m_InputPins.GetAt(n)->Draw(Ctx);
    }

    for(n = 0; n < m_OutputPins.GetCount(); n++)
    {
        m_OutputPins.GetAt(n)->Draw(Ctx);
    }
    
    Ctx.PopState();

    Ctx.DeselectSmallFont();
}
Beispiel #25
0
HRESULT CDBHistory::QueryHistory_InspectionRecord(HDBCONNECTION hDBConnection, 
													SYSTEMTIME sysTimeFrom,
													SYSTEMTIME sysTimeTo,
													long l_LRUIndex,
													LPCWSTR lpszSerial,
													long	lResult,
													LPCWSTR lpszUserID,
													long	l_Index,
													LPDB_HISTORY_COMMON pRecord,
													BSTR* pbstrResult)
{
	HRESULT hr = E_FAIL;

	IMT::CDBConnection* pDBConnection = reinterpret_cast<IMT::CDBConnection*>(hDBConnection);
	if (pDBConnection != NULL)
	{
		ATL::CCommand<ATL::CAccessor<IMT::CDBHistory>> Command;

		ATL::CDBPropSet _DBPropSet(DBPROPSET_ROWSET);
		pDBConnection->GetRowsetProperties(&_DBPropSet);

		CAtlStringW strCommand;
		CAtlStringW strTemp;
		strCommand.Format(QUERY_USER_BY_VALID_CONDITIONS, sysTimeFrom.wYear,
														  sysTimeFrom.wMonth,
														  sysTimeFrom.wDay,
														  sysTimeTo.wYear,
														  sysTimeTo.wMonth,
														  sysTimeTo.wDay);

		BOOL isExist = FALSE;

		strTemp = strCommand;
		strCommand += L"AND ";

		if(l_LRUIndex != 0)
		{
			strTemp.Format(L"(LRU_Index = %d) ", l_LRUIndex);
			strCommand += strTemp;
			strTemp = strCommand;
			strCommand += L"AND ";
		}
		else
			TRACE(L"");

		if(::lstrcmpi(lpszSerial, L"Àüü") != 0)
		{
			strTemp.Format(L"(SerialNum = '%s') ", lpszSerial);
			strCommand += strTemp;
			strTemp = strCommand;
			strCommand += L"AND ";
		}
		else
			TRACE(L"");

		if(lResult != dfRESULT_ALL)
		{
			strTemp.Format(L"(State = %d) ", lResult);
			strCommand += strTemp;
			strTemp = strCommand;
			strCommand += L"AND ";
		}
		else
			TRACE(L"");

		if(::lstrcmpi(lpszUserID, L"Àüü") != 0)
		{
			strTemp.Format(L"(User = '******') ", lpszUserID);
			strCommand += strTemp;
			strTemp = strCommand;
			strCommand += L"AND ";
		}
		else
			TRACE(L"");

		if(::lstrcmpi(strCommand.Right(4), L"AND ") == 0)
		{
			strCommand = strTemp;
		}
		else
			TRACE(L"");


		hr = Command.Open(ATL::CSession(*pDBConnection), strCommand, &_DBPropSet);
		if (hr != S_OK)
		{
			if (pbstrResult != NULL)
				IMT::GetDBErrorString(hr, pbstrResult);
		}
		else
		{
			TRACE(_T(":::[CDBHistory]-[QUERY] SUCCEEDED :::\n"));
			for(long i = 0; i < l_Index; i++)
			{
				hr = Command.MoveNext();
			}
			if (hr == S_OK)
				::CopyMemory(pRecord, LPDB_HISTORY_COMMON(Command), sizeof(DB_HISTORY_COMMON));
		}
	}

	return hr;
}
CAtlStringW ToString(int n)
{
    CAtlStringW result;
    result.Format(L"%i", n);
    return result;
}
Beispiel #27
0
void
CDeviceView::BuildActionMenuForNode(
    _In_ HMENU OwnerMenu,
    _In_ CNode *Node,
    _In_ bool MainMenu
    )
{
    // Create a seperator structure 
    MENUITEMINFOW MenuSeperator = { 0 };
    MenuSeperator.cbSize = sizeof(MENUITEMINFOW);
    MenuSeperator.fType = MFT_SEPARATOR;

    // Setup the 
    MENUITEMINFOW MenuItemInfo = { 0 };
    MenuItemInfo.cbSize = sizeof(MENUITEMINFOW);
    MenuItemInfo.fMask = MIIM_ID | MIIM_STRING | MIIM_DATA | MIIM_SUBMENU;
    MenuItemInfo.fType = MFT_STRING;

    CAtlStringW String;
    int i = 0;

    // Device nodes have extra data
    if (Node->GetNodeType() == DeviceNode)
    {
        CDeviceNode *DeviceNode = dynamic_cast<CDeviceNode *>(Node);

        if (DeviceNode->CanUpdate())
        {
            String.LoadStringW(g_hThisInstance, IDS_MENU_UPDATE);
            MenuItemInfo.wID = IDC_UPDATE_DRV;
            MenuItemInfo.dwTypeData = String.GetBuffer();
            InsertMenuItemW(OwnerMenu, i, TRUE, &MenuItemInfo);
            i++;
        }

        if (DeviceNode->IsDisabled())
        {
            String.LoadStringW(g_hThisInstance, IDS_MENU_ENABLE);
            MenuItemInfo.wID = IDC_ENABLE_DRV;
            MenuItemInfo.dwTypeData = String.GetBuffer();
            InsertMenuItemW(OwnerMenu, i, TRUE, &MenuItemInfo);
            i++;
        }

        if (DeviceNode->CanDisable() && !DeviceNode->IsDisabled())
        {
            String.LoadStringW(g_hThisInstance, IDS_MENU_DISABLE);
            MenuItemInfo.wID = IDC_DISABLE_DRV;
            MenuItemInfo.dwTypeData = String.GetBuffer();
            InsertMenuItemW(OwnerMenu, i, TRUE, &MenuItemInfo);
            i++;
        }

        if (DeviceNode->CanUninstall())
        {
            String.LoadStringW(g_hThisInstance, IDS_MENU_UNINSTALL);
            MenuItemInfo.wID = IDC_UNINSTALL_DRV;
            MenuItemInfo.dwTypeData = String.GetBuffer();
            InsertMenuItemW(OwnerMenu, i, TRUE, &MenuItemInfo);
            i++;
        }

        InsertMenuItemW(OwnerMenu, i, TRUE, &MenuSeperator);
        i++;
    }

    // All nodes have the scan option
    String.LoadStringW(g_hThisInstance, IDS_MENU_SCAN);
    MenuItemInfo.wID = IDC_SCAN_HARDWARE;
    MenuItemInfo.dwTypeData = String.GetBuffer();
    InsertMenuItemW(OwnerMenu, i, TRUE, &MenuItemInfo);
    i++;

    if ((Node->GetNodeType() == RootNode) || (MainMenu == true))
    {
        String.LoadStringW(g_hThisInstance, IDS_MENU_ADD);
        MenuItemInfo.wID = IDC_ADD_HARDWARE;
        MenuItemInfo.dwTypeData = String.GetBuffer();
        InsertMenuItemW(OwnerMenu, i, TRUE, &MenuItemInfo);
        i++;
    }

    if (Node->HasProperties())
    {
        InsertMenuItemW(OwnerMenu, i, TRUE, &MenuSeperator);
        i++;

        String.LoadStringW(g_hThisInstance, IDS_MENU_PROPERTIES);
        MenuItemInfo.wID = IDC_PROPERTIES;
        MenuItemInfo.dwTypeData = String.GetBuffer();
        InsertMenuItemW(OwnerMenu, i, TRUE, &MenuItemInfo);
        i++;

        SetMenuDefaultItem(OwnerMenu, IDC_PROPERTIES, FALSE);
    }
}
    bool Process(Params& params)
    {
        HANDLE hProcess = params.Process;
        DWORD dwProcessId = params.ProcessId;
        MINIDUMP_EXCEPTION_INFORMATION* pExceptInfo = &params.ExceptInfo;
        bool wasAssert = !!params.WasAssert;

        m_dumpWriter.Init(m_config.DbgHelpPath);

        // we need to get CrashInfo before writing the dumps, since dumps writing will change WorkingSet
        m_crashInfo.reset(new CrashInfo(hProcess));

        InitPathes();

        UI ui(m_config);

        ui.ShowInitialProgressWindow(wasAssert);

        PrepareMiniDump(hProcess, dwProcessId, pExceptInfo);
        if (m_config.ServiceMode)
        {
            PrepareFullDump(hProcess, dwProcessId, pExceptInfo, true);
            TerminateProcess(hProcess, E_FAIL); // It is necessary for DUMPPARSER to terminate app, because it should process our dump, and it could not do it since it crashes.
            CloseHandle(hProcess);
            hProcess = NULL;
        }

        doctor_dump::Application app;
        app.applicationGUID = m_config.ApplicationGUID;
        app.v[0] = m_config.V[0];
        app.v[1] = m_config.V[1];
        app.v[2] = m_config.V[2];
        app.v[3] = m_config.V[3];
        app.hotfix = m_config.Hotfix;
        app.processName = m_config.ProcessName;
        m_log.Info(_T("App %d.%d.%d.%d %ls"), app.v[0], app.v[1], app.v[2], app.v[3], app.applicationGUID);

        doctor_dump::DumpAdditionalInfo addInfo;
        addInfo.crashDate = time(NULL);
        addInfo.PCID = GetUserPCID();
        addInfo.submitterID = m_config.SubmitterID;
        addInfo.group = CA2W(params.Group);
        addInfo.description = m_config.CustomInfo;

        std::unique_ptr<doctor_dump::Response> response = m_dumpUploader.Hello(app, (LPCWSTR)m_config.AppName, (LPCWSTR)m_config.Company, addInfo);
        while (1)
        {
            switch (response->GetResponseType())
            {
            case doctor_dump::Response::HaveSolutionResponseType:
                ProcessSolution(ui, static_cast<doctor_dump::HaveSolutionResponse&>(*response));
                goto finish;

            case doctor_dump::Response::NeedMiniDumpResponseType:
                response = m_dumpUploader.UploadMiniDump(response->context, app, addInfo, (LPCWSTR)m_miniDumpZipFile);
                break;

            case doctor_dump::Response::NeedFullDumpResponseType:
                if (!ui.AskSendFullDump())
                {
                    response = m_dumpUploader.RejectedToSendAdditionalInfo(response->context, app, response->dumpID);
                    break;
                }

                ui.ShowFullDumpUploadProgressWindow();

                if (!m_config.ServiceMode)
                {
                    auto& resp = static_cast<doctor_dump::NeedFullDumpResponse&>(*response);
                    m_config.FullDumpType = m_config.FullDumpType & (~resp.restrictedDumpType);
                    PrepareFullDump(hProcess, dwProcessId, pExceptInfo, resp.attachUserInfo);
                    CloseHandle(hProcess);
                    hProcess = NULL;
                }
                SetEvent(params.ReportReady);
                response = m_dumpUploader.UploadFullDump(response->context, app, response->dumpID, (LPCWSTR)m_fullDumpZipFile, &ui);
                break;

            case doctor_dump::Response::NeedMoreInfoResponseType:
                if (!ui.AskSendFullDump())
                {
                    response = m_dumpUploader.RejectedToSendAdditionalInfo(response->context, app, response->dumpID);
                    break;
                }

                ui.ShowFullDumpUploadProgressWindow();

                PrepareAdditionalInfo(static_cast<doctor_dump::NeedMoreInfoResponse&>(*response), hProcess, dwProcessId);
                response = m_dumpUploader.UploadAdditionalInfo(response->context, app, response->dumpID, (LPCWSTR)m_infoFile, &ui);
                break;

            case doctor_dump::Response::ErrorResponseType:
                throw runtime_error((const char*)CW2A(static_cast<doctor_dump::ErrorResponse&>(*response).error.c_str()));

            case doctor_dump::Response::StopResponseType:
            default:
                goto finish;
            }
        }
finish:
        if (!m_config.ServiceMode && !response->urlToProblem.empty() && m_config.OpenProblemInBrowser)
        {
            CAtlStringW url = response->urlToProblem.c_str();
            if (url.Find(L"http://") == 0 || url.Find(L"https://") == 0)
                ShellExecuteW(NULL, _T("open"), url, NULL, NULL, SW_SHOWNORMAL);
        }

        return true;
    }
Beispiel #29
0
/**
 *  This method is called when we receive a WPD_COMMAND_OBJECT_RESOURCES_OPEN
 *  command.
 *
 *  The parameters sent to us are:
 *  - WPD_PROPERTY_OBJECT_RESOURCES_OBJECT_ID: the object identifier of the
 *      object which contains the specified resource
 *
 *  - WPD_PROPERTY_OBJECT_RESOURCES_RESOURCE_KEYS: the specified resource
 *      to open
 *
 *  - WPD_PROPERTY_OBJECT_RESOURCES_ACCESS_MODE: the access mode to which to
 *      open the specified resource
 *
 *  The driver should:
 *  - Create a new context for this resource operation.
 *  - Return an identifier for the context in WPD_PROPERTY_OBJECT_RESOURCES_CONTEXT.
 *  - Set the optimal transfer size in WPD_PROPERTY_OBJECT_RESOURCES_OPTIMAL_TRANSFER_BUFFER_SIZE
 *
 */
HRESULT WpdObjectResources::OnOpenResource(
    _In_ IPortableDeviceValues*  pParams,
    _In_ IPortableDeviceValues*  pResults)
{
    HRESULT     hr              = S_OK;
    LPWSTR      wszObjectID     = NULL;
    PROPERTYKEY Key             = WPD_PROPERTY_NULL;
    DWORD       dwMode          = STGM_READ;
    CAtlStringW strStrObjectID;
    CAtlStringW strResourceContext;
    ContextMap* pContextMap     = NULL;

    // Get the Object identifier of the object which contains the specified resource
    hr = pParams->GetStringValue(WPD_PROPERTY_OBJECT_RESOURCES_OBJECT_ID, &wszObjectID);
    if (hr != S_OK)
    {
        hr = E_INVALIDARG;
        CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_RESOURCES_OBJECT_ID");
    }

    // Get the resource key
    if (hr == S_OK)
    {
        hr = pParams->GetKeyValue(WPD_PROPERTY_OBJECT_RESOURCES_RESOURCE_KEYS, &Key);
        CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_RESOURCES_RESOURCE_KEYS");
    }

    // Get the access mode
    if (hr == S_OK)
    {
        hr = pParams->GetUnsignedIntegerValue(WPD_PROPERTY_OBJECT_RESOURCES_ACCESS_MODE, &dwMode);
        CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_RESOURCES_ACCESS_MODE");
    }

    // Validate whether the params given to us are correct.  In this case, we need to check that the object
    // supports the resource requested, and can be opened in the requested access mode.
    if (hr == S_OK)
    {
        // In this sample, we only have one object (README_FILE_OBJECT_ID) which supports a
        // resource (WPD_RESOURCE_DEFAULT) for reading only.
        // So if any other Object ID or any other resource is specified, it must be invalid.
        strStrObjectID = wszObjectID;
        if(strStrObjectID.CompareNoCase(README_FILE_OBJECT_ID) != 0)
        {
            hr = E_INVALIDARG;
            CHECK_HR(hr, "Object [%ws] does not support resources", wszObjectID);
        }
        if (hr == S_OK)
        {
            if (!IsEqualPropertyKey(Key, WPD_RESOURCE_DEFAULT))
            {
                hr = E_INVALIDARG;
                CHECK_HR(hr, "Only WPD_RESOURCE_DEFAULT is supported in this sample driver");
            }
        }
        if (hr == S_OK)
        {
            if ((dwMode & STGM_WRITE) != 0)
            {
                hr = E_ACCESSDENIED;
                CHECK_HR(hr, "This resource is not available for write access");
            }
        }
    }

    // Get the context map which the driver stored in pParams for convenience
    if (hr == S_OK)
    {
        hr = pParams->GetIUnknownValue(PRIVATE_SAMPLE_DRIVER_CLIENT_CONTEXT_MAP, (IUnknown**)&pContextMap);
        CHECK_HR(hr, "Failed to get PRIVATE_SAMPLE_DRIVER_CLIENT_CONTEXT_MAP");
    }

    // Create a new resource operation context, initialize it, and add it to the client context map.
    if (hr == S_OK)
    {
        WpdObjectResourceContext* pResourceContext = new WpdObjectResourceContext();
        if (pResourceContext != NULL)
        {
            // Initialize the resource context with ...
            pResourceContext->m_strObjectID      = wszObjectID;
            pResourceContext->m_Resource         = Key;
            pResourceContext->m_BytesTransferred = 0;
            pResourceContext->m_BytesTotal       = GetObjectSize(wszObjectID);

            // Add the resource context to the context map
            pContextMap->Add(pResourceContext, strResourceContext);

            // Release the resource context because it has been AddRef'ed during Add()
            SAFE_RELEASE(pResourceContext);
        }
        else
        {
            hr = E_OUTOFMEMORY;
            CHECK_HR(hr, "Failed to allocate resource context");
        }
    }

    if (hr == S_OK)
    {
        hr = pResults->SetStringValue(WPD_PROPERTY_OBJECT_RESOURCES_CONTEXT, strResourceContext);
        CHECK_HR(hr, "Failed to set WPD_PROPERTY_OBJECT_RESOURCES_CONTEXT");
    }

    // Set the optimal buffer size
    if (hr == S_OK)
    {
        hr = pResults->SetUnsignedIntegerValue(WPD_PROPERTY_OBJECT_RESOURCES_OPTIMAL_TRANSFER_BUFFER_SIZE, FILE_OPTIMAL_READ_BUFFER_SIZE_VALUE);
        CHECK_HR(hr, "Failed to set WPD_PROPERTY_OBJECT_RESOURCES_OPTIMAL_TRANSFER_BUFFER_SIZE value");
    }

    // Free the memory.  CoTaskMemFree ignores NULLs so no need to check.
    CoTaskMemFree(wszObjectID);

    SAFE_RELEASE(pContextMap);

    return hr;
}
Beispiel #30
0
/**
 *  This method is called to populate resource attributes found on a particular object
 *  resource.
 *
 *  The parameters sent to us are:
 *  wszObjectID - the object whose resource attributes are being requested
 *  Key - the resource on the specified object whose attributes are being returned
 *  pAttributes - An IPortableDeviceValues to be populated with resource attributes.
 *
 *  The driver should:
 *  Add attributes pertaining to the resource on the specified object.
 */
HRESULT WpdObjectResources::GetResourceAttributesForObject(
    _In_ LPCWSTR                wszObjectID,
    _In_ REFPROPERTYKEY         Key,
    _In_ IPortableDeviceValues* pAttributes)
{
    HRESULT     hr = S_OK;
    CAtlStringW strObjectID;

    if ((wszObjectID == NULL) ||
        (pAttributes == NULL))
    {
        hr = E_INVALIDARG;
        return hr;
    }

    strObjectID = wszObjectID;

    if ((strObjectID.CompareNoCase(README_FILE_OBJECT_ID) == 0) && (IsEqualPropertyKey(Key, WPD_RESOURCE_DEFAULT)))
    {
        if (hr == S_OK)
        {
            hr = pAttributes->SetBoolValue(WPD_RESOURCE_ATTRIBUTE_CAN_DELETE, FALSE);
            CHECK_HR(hr, "Failed to set WPD_RESOURCE_ATTRIBUTE_CAN_DELETE");
        }

        if (hr == S_OK)
        {
            hr = pAttributes->SetUnsignedLargeIntegerValue(WPD_RESOURCE_ATTRIBUTE_TOTAL_SIZE, GetObjectSize(strObjectID));
            CHECK_HR(hr, "Failed to set WPD_RESOURCE_ATTRIBUTE_TOTAL_SIZE");
        }

        if (hr == S_OK)
        {
            hr = pAttributes->SetBoolValue(WPD_RESOURCE_ATTRIBUTE_CAN_READ, TRUE);
            CHECK_HR(hr, "Failed to set WPD_RESOURCE_ATTRIBUTE_CAN_READ");
        }

        if (hr == S_OK)
        {
            hr = pAttributes->SetBoolValue(WPD_RESOURCE_ATTRIBUTE_CAN_WRITE, FALSE);
            CHECK_HR(hr, "Failed to set WPD_RESOURCE_ATTRIBUTE_CAN_WRITE");
        }

        if (hr == S_OK)
        {
            hr = pAttributes->SetBoolValue(WPD_RESOURCE_ATTRIBUTE_CAN_DELETE, FALSE);
            CHECK_HR(hr, "Failed to set WPD_RESOURCE_ATTRIBUTE_CAN_DELETE");
        }

        if (hr == S_OK)
        {
            hr = pAttributes->SetGuidValue(WPD_RESOURCE_ATTRIBUTE_FORMAT, GetObjectFormat(strObjectID));
            CHECK_HR(hr, "Failed to set WPD_RESOURCE_ATTRIBUTE_FORMAT");
        }

        if (hr == S_OK)
        {
            hr = pAttributes->SetUnsignedIntegerValue(WPD_RESOURCE_ATTRIBUTE_OPTIMAL_READ_BUFFER_SIZE, FILE_OPTIMAL_READ_BUFFER_SIZE_VALUE);
            CHECK_HR(hr, "Failed to set WPD_RESOURCE_ATTRIBUTE_OPTIMAL_READ_BUFFER_SIZE");
        }

        if (hr == S_OK)
        {
            hr = pAttributes->SetUnsignedIntegerValue(WPD_RESOURCE_ATTRIBUTE_OPTIMAL_WRITE_BUFFER_SIZE, FILE_OPTIMAL_WRITE_BUFFER_SIZE_VALUE);
            CHECK_HR(hr, "Failed to set WPD_RESOURCE_ATTRIBUTE_OPTIMAL_WRITE_BUFFER_SIZE");
        }
    }

    return hr;
}