예제 #1
1
void CChildView::OnFileSave()
{
	CString strFilter;
	CSimpleArray<GUID> aguidFileTypes;
	CImage *pImage;
	CString fmt;
	HRESULT hResult;
	INT_PTR nResult;

	pImage = m_pSurface->GetImage();
	ASSERT(pImage != NULL);
	hResult = pImage->GetExporterFilterString( strFilter, aguidFileTypes );
	if(FAILED(hResult)) {
		fmt.Format(IDS_ERROR_GETEXPORTERFILTER, hResult, _com_error(hResult).ErrorMessage());
		::AfxMessageBox(fmt);
		return;
	}

	CFileDialog dlg(FALSE, NULL, NULL, 
		OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, strFilter);
	dlg.m_ofn.nFilterIndex = m_nFilterSave;

	nResult = dlg.DoModal();
	if( nResult != IDOK ) {
		return;
	}
	m_nFilterSave = dlg.m_ofn.nFilterIndex;
	GUID guid = m_nFilterSave > 0 ? aguidFileTypes[m_nFilterSave-1] : GUID(GUID_NULL);
	CString strFileName = dlg.GetPathName();
	if (dlg.GetFileExt().IsEmpty()) {
		if (strFileName[strFileName.GetLength()-1] == '.') {
			strFileName = strFileName.Left(strFileName.GetLength()-1);
		}
		CString strExt;
		if (m_nFilterSave == 0) {
			strExt = _T(".jpg"); // default to JPEG
		}
		else {
			// Look up the first extension in the filters
			int nCount = (m_nFilterSave*2)-1;
			int nLeft = 0;
			while (nCount) {
				if (strFilter[nLeft++] == '|') {
					nCount--;
				}
			}
			ASSERT(nLeft < strFilter.GetLength());
			strExt = strFilter.Tokenize(_T(";|"), nLeft).MakeLower();
			strExt = ::PathFindExtension(strExt);
		}
		strFileName += strExt;
	}

	hResult = pImage->Save(strFileName, guid);
	if(FAILED(hResult)) {
		fmt.Format(IDS_ERROR_SAVE, hResult, _com_error(hResult).ErrorMessage());
		::AfxMessageBox(fmt);
	}
}
예제 #2
0
static void GetGUIDs(IXMLDOMElement* e, std::vector<GUID>& v)
{
	HRESULT hr;
	IXMLDOMNodeListPtr children;
	long listlength;

	hr = e->get_childNodes(&children);
	if(hr!=S_OK) throw _com_error(hr);
	hr = children->get_length(&listlength);
	if(hr!=S_OK) throw _com_error(hr);

	for(size_t n=0;n<listlength;n++)
	{
		IXMLDOMElementPtr item;
		IXMLDOMNodePtr itemnode;
		_variant_t var;
		GUID guid;

		hr = children->get_item(n,&itemnode);
		if(hr!=S_OK) throw _com_error(hr);
		item = itemnode;

		hr = item->getAttribute(_bstr_t(L"name"),&var);
		if(hr!=S_OK) throw _com_error(hr);
		string_to_guid((LPCWSTR)(_bstr_t)var,&guid);
		v.push_back(guid);
	}
}
예제 #3
0
static void GetULongs(IXMLDOMElement* e,std::vector<unsigned long>& v)
{
	HRESULT hr;
	IXMLDOMNodeListPtr children;
	long listlength;

	hr = e->get_childNodes(&children);
	if(hr!=S_OK) throw _com_error(hr);
	hr = children->get_length(&listlength);
	if(hr!=S_OK) throw _com_error(hr);

	for(size_t n=0;n<listlength;n++)
	{
		IXMLDOMElementPtr item;
		IXMLDOMNodePtr itemnode;
		_variant_t var;
		unsigned long val;

		hr = children->get_item(n,&itemnode);
		if(hr!=S_OK) throw _com_error(hr);
		item = itemnode;

		hr = item->getAttribute(_bstr_t(L"val"),&var);
		if(hr!=S_OK) throw _com_error(hr);
		val = (unsigned long)var;
		v.push_back(val);
	}
}
예제 #4
0
static void GetGUIDLists(IXMLDOMElement* e,std::map<unsigned long,std::vector<GUID> >& v)
{
	HRESULT hr;
	IXMLDOMNodeListPtr children;
	long listlength;

	hr = e->get_childNodes(&children);
	if(hr!=S_OK) throw _com_error(hr);
	hr = children->get_length(&listlength);
	if(hr!=S_OK) throw _com_error(hr);

	for(size_t n=0;n<listlength;n++)
	{
		IXMLDOMElementPtr item;
		IXMLDOMNodePtr itemnode;
		_variant_t var;

		hr = children->get_item(n,&itemnode);
		if(hr!=S_OK) throw _com_error(hr);
		item = itemnode;

		hr = item->getAttribute(_bstr_t(L"id"),&var);
		if(hr!=S_OK) throw _com_error(hr);
		GetGUIDs(item,v[(unsigned long)var]);

	}
}
예제 #5
0
static void GetTopology(IXMLDOMElement* e,TOPOLOGY& v)
{
	HRESULT hr;
	IXMLDOMElementPtr categories, connection, name, nodes;
	IXMLDOMNodePtr  categories_node, connection_node, name_node, nodes_node;

	hr = e->selectSingleNode(_bstr_t(L"ksproperty_topology_categories"),&categories_node);
	if(hr!=S_OK) throw _com_error(hr);
	hr = e->selectSingleNode(_bstr_t(L"ksproperty_topology_connections"),&connection_node);
	if(hr!=S_OK) throw _com_error(hr);
	hr = e->selectSingleNode(_bstr_t(L"ksproperty_topology_name"),&name_node);
	if(hr!=S_OK) throw _com_error(hr);
	hr = e->selectSingleNode(_bstr_t(L"ksproperty_topology_nodes"),&nodes_node);
	if(hr!=S_OK) throw _com_error(hr);

	categories=categories_node;
	connection=connection_node;
	name=name_node;
	nodes=nodes_node;

	GetGUIDs(categories,v.categories);
	GetTopologyConnections(connection,v.connection);
	GetStrings(name,v.name);
	GetGUIDs(nodes,v.nodes);
}
예제 #6
0
static void GetStrings(IXMLDOMElement* e, std::vector<std::wstring>& v)
{
	HRESULT hr;
	IXMLDOMNodeListPtr children;
	long listlength;

	hr = e->get_childNodes(&children);
	if(hr!=S_OK) throw _com_error(hr);
	hr = children->get_length(&listlength);
	if(hr!=S_OK) throw _com_error(hr);

	for(size_t n=0;n<listlength;n++)
	{
		IXMLDOMElementPtr item;
		IXMLDOMNodePtr itemnode;
		_variant_t var;
		std::wstring str;

		hr = children->get_item(n,&itemnode);
		if(hr!=S_OK) throw _com_error(hr);
		item = itemnode;

		hr = item->getAttribute(_bstr_t(L"value"),&var);
		if(hr!=S_OK) throw _com_error(hr);
		str = (LPCWSTR)(_bstr_t)var;
		v.push_back(str);
	}
}
예제 #7
0
void IEToolbar::acquireSiteWindow(IUnknownPtr site) {
  // Query IOleWindow interface from specified site.
  IOleWindowPtr siteOLEWindow;
  const HRESULT getOleWindowResult =
      site.QueryInterface(IID_IOleWindow, &siteOLEWindow);
  if (FAILED(getOleWindowResult)) {
    throw _com_error(getOleWindowResult);
  }

  // Retrieve handle of site window.
  HWND siteWindowHandle = 0;
  const HRESULT getWindowResult = siteOLEWindow->GetWindow(&siteWindowHandle);
  if (FAILED(getWindowResult)) {
    throw _com_error(getWindowResult);
  }

  // Attach MFC-wrapper to site window.
  const BOOL attachResult = siteWindow_.Attach(siteWindowHandle);
  if (FALSE == attachResult) {
    throw Error("Failed to attach to site window handle\n");
  }

  // Subclass site window to retrieve its messages.
  subclassWindow(siteWindow_.GetSafeHwnd());
}
예제 #8
0
COMError::COMError(HRESULT hr)
{
	_com_error e(hr);
	IErrorInfo *pIErrorInfo = NULL;
	GetErrorInfo(0, &pIErrorInfo);

	if (pIErrorInfo == NULL)
	{
		e = _com_error(hr);
		message = e.ErrorMessage();
	}
	else
	{
		e = _com_error(hr, pIErrorInfo);
		message = e.ErrorMessage();
		IErrorInfo *ptrIErrorInfo = e.ErrorInfo();
		if (ptrIErrorInfo != NULL)
		{
			// IErrorInfo Interface located
			description = (WCHAR *)e.Description();
			source = (WCHAR *)e.Source();
			GUID tmpGuid = e.GUID();
			RPC_WSTR guidStr = NULL;
			// must link in Rpcrt4.lib for UuidToString
			UuidToString(&tmpGuid, &guidStr);
			uuid = (WCHAR*)guidStr;
			RpcStringFree(&guidStr);

			ptrIErrorInfo->Release();
		}
	}
}
예제 #9
0
static void GetDeviceList(IXMLDOMElement* e, DEVICELIST& d)
{
	HRESULT hr;
	IXMLDOMNodeListPtr list;
	long listlength;

	hr = e->get_childNodes(&list);
	if(hr!=S_OK) throw _com_error(hr);

	hr = list->get_length(&listlength);
	if(hr!=S_OK) throw _com_error(hr);
	for(size_t n=0;n<listlength;n++)
	{
		IXMLDOMNodePtr itemnode;
		IXMLDOMElementPtr itemlement;

		hr = list->get_item(n,&itemnode);
		if(hr!=S_OK) throw _com_error(hr);
		itemlement = itemnode;

		DEVICE device;
		GetDevice(itemlement,device);
		d.push_back(device);

	}
}
예제 #10
0
void NiashLibUsbWriteBulk(const int iHandle, SANE_Byte* const pabData, const int iSize)
{
	assert(iHandle==1);
	assert(s_hWinUSB);
	assert(s_Pipes.BulkOut);

	//Send setup packet
	SANE_Byte abSetup[8] = { 0x01, 0x01, 0x00, 0x00, (iSize) & 0xFF, (iSize >> 8) & 0xFF, 0x00, 0x00 };
	WINUSB_SETUP_PACKET Packet;
	Packet.RequestType = BMREQUEST_HOST_TO_DEVICE<<7|BMREQUEST_VENDOR<<5; //Vendor type request, PC to device
	Packet.Request = 0x04; //Send multiple bytes
	Packet.Value = static_cast<USHORT>(USB_SETUP);
	Packet.Index = 0x00;	
	Packet.Length = 0x08;
	SendControlTransfer(Packet,abSetup);

	ULONG LengthTransferred;
	if(!WinUsb_WritePipe(s_hWinUSB, s_Pipes.BulkOut, pabData, iSize, &LengthTransferred, nullptr))
	{
		wprintf_s(L"WinUsb_WritePipe: %s\n", _com_error(GetLastError()).ErrorMessage());		
		return;
	}
}

void NiashLibUsbReadBulk (const int iHandle, SANE_Byte* const pabData, const int iSize)
{
	assert(iHandle==1);
	assert(s_hWinUSB);
	assert(s_Pipes.BulkIn);

	//Send setup packet
	SANE_Byte abSetup[8] = { 0x00, 0x00, 0x00, 0x00, (iSize) & 0xFF, (iSize >> 8) & 0xFF, 0x00, 0x00 };
	WINUSB_SETUP_PACKET Packet;
	Packet.RequestType = BMREQUEST_HOST_TO_DEVICE<<7|BMREQUEST_VENDOR<<5; //Vendor type request, PC to device
	Packet.Request = 0x04; //Send multiple bytes
	Packet.Value = static_cast<USHORT>(USB_SETUP);
	Packet.Index = 0x00;	
	Packet.Length = 0x08;
	SendControlTransfer(Packet,abSetup);

	ULONG LengthTransferred;
	if(!WinUsb_ReadPipe(s_hWinUSB, s_Pipes.BulkIn, pabData, iSize, &LengthTransferred, nullptr))
	{
		wprintf_s(L"WinUsb_WritePipe: %s\n", _com_error(GetLastError()).ErrorMessage());		
		return;
	}
}

void NiashLibUsbWaitForInterrupt()
{
	assert(s_hWinUSB);
	assert(s_Pipes.Interrupt);
	BYTE buf[1];
	ULONG LengthTransferred;
	if(!WinUsb_ReadPipe(s_hWinUSB,s_Pipes.Interrupt,buf,_countof(buf),&LengthTransferred,nullptr))
	{
		wprintf_s(L"WinUsb_ReadPipe: %s\n", _com_error(GetLastError()).ErrorMessage());		
		return;
	}
}
예제 #11
0
int NiashLibUsbOpen(char const * const pszName, EScannerModel* const peModel)
{
	//Open a handle to the device (FILE_FLAG_OVERLAPPED for WinUSB)
	
	s_hDevice = CreateFileA(pszName, GENERIC_READ|GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, NULL);
	if(s_hDevice == INVALID_HANDLE_VALUE)
	{
		wprintf_s(L"CreateFile: %s\n", _com_error(GetLastError()).ErrorMessage());
		return -1;
	}

	DEVICE_DESCRIPTOR dd;
	DWORD dwBytesReturned;
	if(!DeviceIoControl(s_hDevice,static_cast<DWORD>(IOCTL_GET_DEVICE_DESCRIPTOR),nullptr,0,&dd,sizeof(dd),&dwBytesReturned,nullptr))
	{
		wprintf_s(L"DeviceIoControl: %s\n", _com_error(GetLastError()).ErrorMessage());
		return -1;
	}

	//Report device to niash
	TScannerModel* pModel;
	MatchUsbDevice(dd.usVendorId,dd.usProductId,&pModel);
	*peModel = pModel->eModel;

	return 1;
}
예제 #12
0
void StreamFileReader::Read(CStdString sStreamName, int iOffset, int iCount, void* pData)
{
	CComPtr<IStream> pStream;

	HRESULT hr = m_pRootStorage->OpenStream(CStdStringW(sStreamName), NULL, STGM_DIRECT|STGM_READ|STGM_SHARE_EXCLUSIVE,
		NULL, &pStream);

	if (FAILED(hr))
		throw _com_error(hr);

	if (pStream==NULL)
		throw _com_error(E_FAIL);

	ULARGE_INTEGER ulPos;
	LARGE_INTEGER iSeek;
	iSeek.QuadPart = iOffset;
	hr = pStream->Seek(iSeek, STREAM_SEEK_SET, &ulPos);
	if (FAILED(hr))
		throw _com_error(hr);
	if (ulPos.LowPart != iOffset)
		throw std::exception("Seek to position in stream failed - beyond end ?");

	ULONG ulRead;
	hr = pStream->Read(pData, iCount, &ulRead);
	if (FAILED(hr))
		throw _com_error(hr);
	if (ulRead != iCount)
		throw std::exception("Failed to read number of bytes requested from stream - asked for too many?");
}
예제 #13
0
bstr_t CCommonUtils::CreateRelativeURL(bstr_t baseURL, bstr_t relURL)
{
    WCHAR ret[INTERNET_MAX_URL_LENGTH];
    DWORD dwLen = INTERNET_MAX_URL_LENGTH;
    HRESULT hr = E_FAIL;

    if(PathIsURL(baseURL))
    {
        hr = UrlCombine(baseURL, relURL, ret, &dwLen, 0);
        if(FAILED(hr))
        {
            throw _com_error(hr);
        }
    }
    else
    {
        hr = StringCchCopyW(ret, sizeof(ret)/sizeof(WCHAR), relURL);
        if(FAILED(hr))
        {
            throw _com_error(hr);
        }
    }

    return ret;
}
예제 #14
0
int NiashLibUsbOpen(char const * const pszName, EScannerModel* const peModel)
{
	//Open a handle to the device (FILE_FLAG_OVERLAPPED for WinUSB)
	s_hDevice = CreateFileA(pszName, GENERIC_READ|GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
	//s_hDevice = CreateFileA("\\\\.\\Usbscan0", GENERIC_READ|GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
	if(s_hDevice == INVALID_HANDLE_VALUE)
	{
		wprintf_s(L"CreateFile: %s\n", _com_error(GetLastError()).ErrorMessage());
		return -1;
	}

	//Open a WinUSB handle
	if(!WinUsb_Initialize(s_hDevice,&s_hWinUSB))
	{		
		wprintf_s(L"WinUsb_Initialize: %s\n", _com_error(GetLastError()).ErrorMessage());
		return -1;
	}

	//Get interface descriptor
	USB_INTERFACE_DESCRIPTOR USBInterfaceDescriptor;
	if(!WinUsb_QueryInterfaceSettings(s_hWinUSB,0,&USBInterfaceDescriptor))
	{
		wprintf_s(L"WinUsb_QueryInterfaceSettings: %s\n", _com_error(GetLastError()).ErrorMessage());
		return -1;
	}

	//Find pipes
	for(UCHAR i = 0;i < USBInterfaceDescriptor.bNumEndpoints;i++)
	{
		WINUSB_PIPE_INFORMATION Pipe;
		WinUsb_QueryPipe(s_hWinUSB,0,i,&Pipe);
		if(Pipe.PipeType == UsbdPipeTypeInterrupt)
		{
			s_Pipes.Interrupt = Pipe.PipeId;
		}
		else if(Pipe.PipeType == UsbdPipeTypeBulk)
		{
			if(USB_ENDPOINT_DIRECTION_IN(Pipe.PipeId))
			{
				s_Pipes.BulkIn = Pipe.PipeId;
			}
			else
			{
				s_Pipes.BulkOut = Pipe.PipeId;				
			}
		}
	}

	if(!s_Pipes.Interrupt || !s_Pipes.BulkIn || !s_Pipes.BulkOut)
	{
		puts("Not all required pipes found.");
		return -1;
	}

	assert(s_pScannerModel);
	*peModel = s_pScannerModel->eModel;

	return 1;
}
예제 #15
0
CComPtr<IWinRobotSession> CWinRobotJNIAdapter::GetActiveConsoleSession()
{
	if(!m_pService) throw _com_error(E_UNEXPECTED);
	CComQIPtr<IWinRobotSession> pQI = m_pService->GetActiveConsoleSession();
	if (!pQI)
	{
		throw _com_error(E_UNEXPECTED);
	}
	return pQI;
}
예제 #16
0
void StreamFileReader::Open(CStdStringW sDocFileName)
{
	HRESULT hr = StgOpenStorage(sDocFileName ,NULL, STGM_DIRECT_SWMR|STGM_READ|STGM_SHARE_DENY_NONE,
		NULL, 0, &m_pRootStorage);

	if (FAILED(hr))
		throw _com_error(hr);

	if (m_pRootStorage == NULL)
		throw _com_error(E_FAIL);
}
void SMNetworkAdapterSettings::_FingSetupInfo(HDEVINFO* devInfo, SP_DEVINFO_DATA* devInfoData) const
{
	SM_ASSERT( !_hardwareId.IsEmpty() );

	SMString hwID(_hardwareId);
	hwID.MakeUpper();

	*devInfo = ::SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT);
	if( INVALID_HANDLE_VALUE == *devInfo )
		throw SMRuntimeException(::GetLastError());

	::ZeroMemory(devInfoData, sizeof(SP_DEVINFO_DATA));
	devInfoData->cbSize = sizeof(SP_DEVINFO_DATA);

	PTSTR buf = NULL;
	DWORD bufSize = 0;
	DWORD reqSize = 0;

	for(int i=0; SetupDiEnumDeviceInfo(*devInfo,i, devInfoData); i++)
	{
		if ( !SetupDiGetDeviceInstanceId(*devInfo, devInfoData, buf, bufSize, &reqSize) )
		{
			if ( bufSize < reqSize )
			{
				if ( NULL != buf )
				{
					delete[] buf;
					buf = NULL;
					bufSize = 0;
				}
				buf = new TCHAR[reqSize];
				if ( NULL == buf )
				{
					SM_LOG(1, E_FAIL, SMString("Insufficient memory : ") + _com_error(GetLastError()).ErrorMessage());
					break;
				}
				bufSize = reqSize;
				if ( !SetupDiGetDeviceInstanceId(*devInfo, devInfoData, buf, bufSize, &reqSize) )
					throw SMRuntimeException(::GetLastError());
			}
			else
			{
				SM_LOG(1, E_FAIL, SMString("SetupDiGetDeviceInstanceId(): ") + _com_error(GetLastError()).ErrorMessage());
				break;
			}
		}

		SMString szBuf = buf;
		szBuf.MakeUpper();

		if ( szBuf.Find(hwID.DataW()) != -1 )
			return;
	}
}
예제 #18
0
LPVOID CCommonUtils::ReadFileData(LPCTSTR lpFileName, DWORD& dwLength)
{
    FILE* fp = NULL;
    LPVOID lpRet = NULL;

    try
    {
        if(_tfopen_s(&fp, lpFileName, _T("rb")) != 0)
        {
            throw _com_error(E_FAIL);
        }

        if(fseek(fp, 0, SEEK_END) != 0)
        {
            throw _com_error(E_FAIL);
        }

        dwLength = ftell(fp);

        if(fseek(fp, 0, SEEK_SET) != 0)
        {
            throw _com_error(E_FAIL);
        }
    
        lpRet = malloc(dwLength);
        if(lpRet == NULL)
        {
            throw _com_error(E_OUTOFMEMORY);
        }

        if(fread(lpRet, 1, dwLength, fp) != dwLength)
        {
            throw _com_error(E_FAIL);
        }
    }
    catch(_com_error& err)
    {
        DEBUG_PRINTF(L"Error in reading file 0x%08X\n", err.Error());
        if(lpRet)
        {
            free(lpRet);
            lpRet = NULL;
        }
    }

    if(fp)
    {
        fclose(fp);
        fp = NULL;
    }

    return lpRet;
}
예제 #19
0
static void AddAttribute(IXMLDOMDocument* pDoc,LPCWSTR name, _variant_t& value,IXMLDOMElement* pParent)
{
	HRESULT hr;
	IXMLDOMAttributePtr Attribute, AttributeOut;

	hr = pDoc->createAttribute(_bstr_t(name),&Attribute);
	if(hr!=S_OK) throw _com_error(hr);
	hr = Attribute->put_value(value);
	if(hr!=S_OK) throw _com_error(hr);
	hr = pParent->setAttributeNode(Attribute,&AttributeOut);
	if(hr!=S_OK) throw _com_error(hr);
}
예제 #20
0
int NetAppender::open(void *host)
{
    //初始化数据
    if (host == NULL) {
        _sendsvr = NetAppenderSvr::getServer(_device.host);
        if (_sendsvr == NULL || _sendsvr->registAppender(this) != 0) {
            _com_error("sorry get server err[%s] or regist appender err", _device.host);
            return -1;
        }
        _core_debug("sendsvr[%lx] _layout[%lx]", _sendsvr, _layout);
        _com_debug("get sendserver[%s]", _device.host);
    } else {
        //建立新的连接
        _req.loghead.log_id  = 123;
        _req.loghead.body_len = sizeof(_req.req);
        snprintf(_req.req.filename, sizeof(_req.req.filename), "%s", _device.file);
        snprintf(_req.req.auth, sizeof(_req.req.auth), "%s", _device.auth);
        if (_device.compress) {
            _req.req.compress = COMLOG_COMPRESS;
        } else {
            _req.req.compress = COMLOG_UNCOMPRESS;
        }
        _req.loghead.reserved = COMLOG_CREATE;
        //发送
        //NetAppenderSvr::nowsd_t *sd = (NetAppenderSvr::nowsd_t *)host;
        int sd = ((SendSvr::server_t *)host)->sock;
        snprintf(_req.req.path, sizeof(_req.req.path), "%s", ((SendSvr::server_t *)host)->path);

        _com_debug("create auth[%s] fn[%s] mod[%s]", _req.req.auth, _req.req.filename, _req.req.path);
        int ret = loghead_write(sd, (loghead_t *)&_req, NETTALKTIMEOUT);
        if (ret != 0) {
            _com_error("open:write netappend fd[%d] err[%m]", sd);
            return -1;
        }
        ret = loghead_read(sd, (loghead_t *)&_res, sizeof(_res), NETTALKTIMEOUT);
        if (ret != 0) {
            _com_error("open:read netappend fd[%d] err[%m]", sd);
            return -1;
        }

        if (_res.res.error_code != 0) {
            _com_error("open log err[%s %s] errno[%d]", _device.auth, _device.file, _res.res.error_code);
            return -1;
        }
        _id = _res.res.handle;
        _com_debug("get handle id[%d]", _id);
        //if (_id < 0) {
        //	_com_error("invalid id[%d]", _id);
        //}
    }
    return 0;
}
예제 #21
0
__declspec(noreturn) void ThrowComError(HRESULT hr, LPOLESTR err)
{
	ICreateErrorInfoPtr errCreate;
	if (SUCCEEDED(CreateErrorInfo(&errCreate))
		&& SUCCEEDED(errCreate->SetDescription(const_cast<wchar_t*>(err)))
		&& SUCCEEDED(errCreate->SetSource(const_cast<wchar_t*>(g_COCLASS_PROGIDW)))
		)
	{
		IErrorInfoPtr errorInfo = errCreate;
		throw _com_error(hr, errorInfo.Detach());
	}
	throw _com_error(hr);
}
예제 #22
0
//*****************************************************************************
//* Function Name: ThrowComErrorException
//*   Description: 
//*****************************************************************************
void ThrowComErrorException (
	LPCTSTR			p_lpszFile,
	UINT			p_uLine,
	HRESULT			p_hr,
	const _bstr_t&	p_sbstrDescription)
{
	USES_CONVERSION;

	CLSID	l_clsid = GUID_NULL;
	IID		l_iid   = GUID_NULL;

	CActiveMethodGUIDs::Get (l_clsid, l_iid);

	// AtlReportError() creates and populates a standard COM error object
	// and calls SetErrorInfo() to pass the COM error object to the COM
	// run-time.

	(void) AtlReportError (	l_clsid,									// rclsid
							p_sbstrDescription.operator LPCOLESTR (),	// lpszDesc
							l_iid,										// riid
							p_hr);										// hRes

	// At this point, the COM run-time has the only reference to the error object.

	IErrorInfoPtr l_spErrorInfo;

	// From MSDN re GetErrorInfo():
	//
	//	"This function returns a pointer to the most recently set IErrorInfo
	//	 pointer in the current logical thread. It transfers ownership of the
	//	 error object to the caller, and clears the error state for the thread."
	if (SUCCEEDED (::GetErrorInfo (0 /* dwReserved */, &l_spErrorInfo))) {

		// At this point, the COM run-time's reference to the error object has
		// been transferred to l_spErrorInfo. Specify true for the last parameter
		// of the _com_error constructor to make sure that it calls AddRef() on
		// the error object. This last parameter is optional and defaults to
		// false. If true is *not* specified then the _com_error constructor
		// won't call AddRef() so the only reference will be the one in
		// l_spErrorInfo which will be released when l_spErrorInfo goes out of
		// scope i.e. when the _com_error exception is thrown. This will result
		// in the error object being prematurely destroyed. By passing true,
		// the only outstanding reference to the error object will be inside
		// the _com_error exception object which is as it should be.

		throw _com_error (p_hr, l_spErrorInfo, true /* fAddRef */);
	}

	// There was no rich error information so just use the HRESULT.
	throw _com_error (p_hr);
}
예제 #23
0
HRESULT  MethodInfo::Create(ICorProfilerInfo* profilerInfo, FunctionID functionId)
{
   CComPtr<IMetaDataImport> metadataImport;

   HRESULT hr = profilerInfo->GetTokenAndMetaDataFromFunction(functionId, IID_IMetaDataImport, reinterpret_cast<IUnknown**>(&metadataImport), &token);
   if (FAILED(hr)) 
   {
      Trace_f(L"Failed to query IMetaDataImport interface (%s)", _com_error(hr).ErrorMessage());
      return hr;
   }

   mdTypeDef typeDefinition = mdTokenNil;
   ULONG methodNameLength = 0;
   ULONG classNameLength = 0;
   DWORD attributes = 0;

   signatureLength = 0;
   signature = NULL;

   hr = metadataImport->GetMethodProps(token, &typeDefinition, NULL, 0, &methodNameLength, &attributes, NULL, NULL, NULL, NULL);
   if (FAILED(hr)) 
   {
      Trace_f(L"Failed to query method name length (%s)", _com_error(hr).ErrorMessage());
      return hr;
   }

   methodName.resize(methodNameLength - 1);
   hr = metadataImport->GetMethodProps(token, &typeDefinition, (WCHAR*)methodName.c_str(), methodNameLength, &methodNameLength, &attributes, &signature, &signatureLength, NULL, NULL);
   if (FAILED(hr)) 
   {
      Trace_f(L"Failed to query method name (%s)", _com_error(hr).ErrorMessage());
      return hr;
   } 

   hr = metadataImport->GetTypeDefProps(typeDefinition, NULL, 0, &classNameLength, NULL, NULL);
   if (FAILED(hr)) 
   {
      Trace_f(L"Failed to query class name length (%s)", _com_error(hr).ErrorMessage());
      return hr;
   }

   className.resize(classNameLength - 1);
   hr = metadataImport->GetTypeDefProps(typeDefinition, (WCHAR*)className.c_str(), classNameLength, &classNameLength, NULL, NULL);
   if (FAILED(hr)) 
   {
      Trace_f(L"Failed to query class name (%s)", _com_error(hr).ErrorMessage());
      return hr;
   }

   return S_OK;
}
예제 #24
0
// Initialize necessary parameters prior to perform matching.
void CFMDoc::MatchingInitialization()
{
	HRESULT hResult;

	// If the template image is not yet defined, bring up the dialog for the user to browse.
	while (theApp.m_Setting.m_strTemplateFile == "")
	{
		theApp.OnToolsTemplate();
	}

	// If the matching is performed based on grayscale, we need to construct the object for grayscale.
	if (true == theApp.m_Setting.m_bEnableGrayscale)
	{
		// Convert the base image to grayscale.

		if (NULL == m_pBaseGrayImage)	
			m_pBaseGrayImage = new CFMImage;			// Create an instance of CFMImage

		hResult = m_pBaseGrayImage->Load(m_strImageFile); // Load the image specified by lpszPathName
		if (FAILED(hResult))
		{
			CString strError;
			strError.Format("Error: Unable to open the specified image:\n%x - %s",
							hResult, _com_error(hResult).ErrorMessage());
			::AfxMessageBox(strError);

			// exit?
		}

		m_pBaseGrayImage->ConvertToGrayscale();

		// Convert the template image to grayscale.

		if (NULL == m_pTemplateGrayImage)	
			m_pTemplateGrayImage = new CFMImage;			// Create an instance of CFMImage

		hResult = m_pTemplateGrayImage->Load(theApp.m_Setting.m_strTemplateFile); // Load the image specified by lpszPathName
		if (FAILED(hResult))
		{
			CString strError;
			strError.Format("Error: Unable to open the specified image:\n%x - %s",
							hResult, _com_error(hResult).ErrorMessage());
			::AfxMessageBox(strError);

			// exit?
		}

		m_pTemplateGrayImage->ConvertToGrayscale();
	}
}
예제 #25
0
BSTR CCommonUtils::BinaryToHex(LPVOID lpData, ULONG ulSize)
{
    LPWSTR lpString = NULL;
    BSTR   bstrRet = NULL;
    LPBYTE lpBytes = (LPBYTE)lpData;
    DWORD dwSize = 0;

    dwSize = ulSize*2*sizeof(WCHAR)+sizeof(WCHAR);
    // Alloc enough for two chars per byte plus NUL
    lpString = (LPWSTR)LocalAlloc(LPTR, dwSize);
    if(!lpString)
    {
        throw _com_error(E_OUTOFMEMORY);
    }

    memset(lpString, 0, dwSize);
    for(UINT pos = 0; pos < ulSize; pos++)
    {
        lpString[pos*2] = IntToHex(lpBytes[pos] >> 4);
        lpString[pos*2+1] = IntToHex(lpBytes[pos] & 0xF);
    }

    bstrRet = ::SysAllocString(lpString);
    LocalFree(lpString);

    return bstrRet;
}
예제 #26
0
bool DispatchObj::PutProp(OLECHAR *name, OLECHAR *val)
{
    DISPID dispid;
    if (!GetDispatchId(&dispid, name))
        return false;

    BSTR bs = SysAllocString(val);
    VARIANTARG rgvarg[1];
    rgvarg[0].vt = VT_BSTR;
    rgvarg[0].bstrVal = bs;
    DISPID dispidNamed = DISPID_PROPERTYPUT;
    DISPPARAMS dispParms;
    dispParms.cArgs = 1;
    dispParms.rgvarg = rgvarg;
    dispParms.cNamedArgs = 1;
    dispParms.rgdispidNamedArgs = &dispidNamed;
    Variant res;
    HRESULT hr = m_idisp->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispParms, &res, &m_excep, NULL);
    SysFreeString(bs);

    if (FAILED(hr))
        Debug.AddLine(wxString::Format("putprop: [%x] %s", hr, _com_error(hr).ErrorMessage()));

    return SUCCEEDED(hr);
}
예제 #27
0
bool DispatchClass::dispid(DISPID *ret, IDispatch *idisp, OLECHAR *wname)
{
    HRESULT hr = idisp->GetIDsOfNames(IID_NULL, &wname, 1, LOCALE_USER_DEFAULT, ret);
    if (FAILED(hr))
        Debug.AddLine(wxString::Format("dispid(%s): [%x] %s", wname, hr, _com_error(hr).ErrorMessage()));
    return SUCCEEDED(hr);
}
예제 #28
0
bool CCommonUtils::RunProcess(LPWSTR bstrName, BOOL bWait)
{
    STARTUPINFO startInfo = {0};
    PROCESS_INFORMATION procInfo = {0};
    bool bRet = false;

    try
    {
        if(bstrName)
        {
            if(!CreateProcess(NULL, bstrName, NULL, NULL, FALSE, NULL, NULL, NULL, &startInfo, &procInfo))
            {
                throw _com_error(HRESULT_FROM_WIN32(GetLastError()));
            }
            else
            {
                if(bWait)
                {
                    WaitForSingleObject(procInfo.hProcess, INFINITE);
                }

                bRet = true;
                CloseHandle(procInfo.hProcess);
                CloseHandle(procInfo.hThread);
            }
        }
    }
    catch(_com_error& err)
    {
        DEBUG_PRINTF(L"Error 0x%08X\n", err.Error());
        bRet = false;
    }

    return bRet;
}
예제 #29
0
static void GetUserFromProcess(_bstr_t& strUser, _bstr_t& strdomain)
{
    HANDLE hProcess = GetCurrentProcess();
    HANDLE hToken = NULL;

	try {
		try {
			if( !OpenProcessToken( hProcess, TOKEN_QUERY, &hToken ) ) {
				throw _com_error(HRESULT_FROM_WIN32(GetLastError()));
			}
		    
			GetLogonFromToken (hToken, strUser,  strdomain);

			CloseHandle(hToken);
			hToken = NULL;
			
			throw 0;
		}
		catch(...) {	// finally
			if (hToken != NULL) {
				CloseHandle(hToken);
				hToken = NULL;
			}
			throw;
		}
	}
	catch(int) {}
}
예제 #30
0
extern "C" BOOL RegisterComServers (char *modulePath)
{
	BOOL ret = TRUE;
	wchar_t mainModule[1024], formatModule[1024];
	CComPtr<ITypeLib> tl, tl2;

	wsprintfW (mainModule, L"%hsGostCrypt.exe", modulePath);
	wsprintfW (formatModule, L"%hsGostCrypt Format.exe", modulePath);

	UnRegisterTypeLib (LIBID_GostCryptMainCom, GST_MAIN_COM_VERSION_MAJOR, GST_MAIN_COM_VERSION_MINOR, 0, SYS_WIN32);
	UnRegisterTypeLib (LIBID_GostCryptFormatCom, GST_FORMAT_COM_VERSION_MAJOR, GST_FORMAT_COM_VERSION_MINOR, 0, SYS_WIN32);

	wchar_t setupModule[MAX_PATH];
	GetModuleFileNameW (NULL, setupModule, sizeof (setupModule) / sizeof (setupModule[0]));

	CRegObject ro;
	HRESULT r;

	if (!SUCCEEDED (r = ro.FinalConstruct ())
		|| !SUCCEEDED (r = ro.AddReplacement (L"MAIN_MODULE", mainModule))
		|| !SUCCEEDED (r = ro.AddReplacement (L"FORMAT_MODULE", formatModule))
		|| !SUCCEEDED (r = ro.ResourceRegister (setupModule, IDR_COMREG, L"REGISTRY"))
		|| !SUCCEEDED (r = LoadTypeLib (mainModule, &tl))
		|| !SUCCEEDED (r = RegisterTypeLib (tl, mainModule, 0))
		|| !SUCCEEDED (r = LoadTypeLib (formatModule, &tl2))
		|| !SUCCEEDED (r = RegisterTypeLib (tl2, formatModule, 0)))
	{
		MessageBox (MainDlg, _com_error (r).ErrorMessage(), GST_APP_NAME, MB_ICONERROR);
		ret = FALSE;
	}

	ro.FinalRelease ();
	return ret;
}