//------------------------------------------------------------------*
HRESULT CFCMessageSessionThread::ConnectThread()
{
    HRESULT hr = CoGetInterfaceAndReleaseStream(m_pMsgSessionStream, IID__FCMessageSessionNotificationInternal,
                                                (void **)&m_pMsgSession);
    m_pMsgSessionStream = NULL;
    if (FAILED(hr))
      return hr;

    while(!m_bShutdownRequest) {
        hr = DoConnect();
        if (FAILED(hr)) {
            m_pMsgSession->OnStateChanged(m_cookie, interrupted, hr);
            WaitForSingleObject(m_hShutdownRequest, 20000);
            continue;
        }
        m_pMsgSession->OnStateChanged(m_cookie, RW_established, S_OK);
        while (!m_bShutdownRequest) {
            if (WAIT_TIMEOUT == WaitForSingleObject(m_hShutdownRequest, 10000)) {
                hr = DoCheckConnection();
                if (FAILED(hr)) {
                  m_pMsgSession->OnStateChanged(m_cookie, interrupted, hr);
                  break;
                }
            }
        }
    }

    DoDisconnect();
    m_pMsgSession->Release();
    m_pMsgSession = NULL;
    return S_OK;
}
JNIEXPORT jobject JNICALL Java_com_jacob_com_DispatchProxy_MarshalFromStream
  (JNIEnv *env, jobject _this)
{
  IStream *ps = extractStream(env, _this);
  if (!ps) 
  {
    ThrowComFail(env, "Could not get IStream from DispatchProxy", -1);
    return NULL;
  }
  IDispatch *pD;
  HRESULT hr = CoGetInterfaceAndReleaseStream(ps, IID_IDispatch, (void **)&pD);
  // zero out the stream pointer on the object
  // since the stream can only be read once
  jclass argClass = env->GetObjectClass(_this);
  jfieldID ajf = env->GetFieldID( argClass, "m_pStream", "I");
  env->SetIntField(_this, ajf, (unsigned int)0);

  if (!SUCCEEDED(hr))
  {
    ThrowComFail(env, "Could not Marshal Dispatch from IStream", hr);
    return NULL;
  }
  jclass autoClass = env->FindClass("com/jacob/com/Dispatch");
  jmethodID autoCons = env->GetMethodID(autoClass, "<init>", "(I)V");
  // construct a Dispatch object to return
  // I am copying the pointer to java
  if (pD) pD->AddRef();
  jobject newAuto = env->NewObject(autoClass, autoCons, pD);
  return newAuto;
}
Exemple #3
0
DWORD WINAPI PyCOMTestSessionThreadEntry(void* pv)
{
	// Init COM for the thread.
	CoInitializeEx(NULL, COINIT_MULTITHREADED);
	CPyCOMTest::PyCOMTestSessionData* pS = (CPyCOMTest::PyCOMTestSessionData*)pv;
	// Unmarshal the interface pointer.
	IPyCOMTest *pi;
	HRESULT hr = CoGetInterfaceAndReleaseStream(pS->pStream, IID_IPyCOMTest, (void **)&pi);
	CComPtr<IPyCOMTest> p(pi);
	while (WaitForSingleObject(pS->m_hEvent, 0) != WAIT_OBJECT_0)
		p->Fire(pS->m_nID);
	p.Release();
	CoUninitialize();
	return 0;
}
Exemple #4
0
/*
 * Wait for the stream to be initialized before allowing any calls on pScript.
 */
IScriptController *ScriptThread::getScript()
{
	if (WaitForSingleObject(hScriptEvent, INFINITE) == WAIT_OBJECT_0)
	{
		if (!pScript)
		{
			HRESULT hr = CoGetInterfaceAndReleaseStream(scriptStream, IID_IScriptController, (void**)&pScript);
			pScript->AddRef();
		}

		return pScript;
	}

	return NULL;
}
Exemple #5
0
ISession* CCoolInet2::GetSession()
{
	IStream *pStream = NULL;
	SessionMarshaling(&pStream);
	if(pStream==NULL) return NULL;

	ISession* pSession = NULL;

	HRESULT hr = CoGetInterfaceAndReleaseStream(pStream,__uuidof(ISession),(LPVOID*)&pSession);

	//pSession->AddRef();

	if(SUCCEEDED(hr))
		return pSession;

	return NULL;
}
Exemple #6
0
JNIEXPORT jobject JNICALL Java_org_racob_com_DispatchProxy_MarshalFromStream
  (JNIEnv *env, jobject _this, jint pointer)
{
  IStream *ps = (IStream *) pointer;
  if (!ps) {
    ThrowComFail(env, "Could not get IStream from DispatchProxy", -1);
    return NULL;
  }
  
  IDispatch *pD;
  HRESULT hr = CoGetInterfaceAndReleaseStream(ps, IID_IDispatch, (void **)&pD);

  if (!SUCCEEDED(hr)) {
    ThrowComFail(env, "Could not Marshal Dispatch from IStream", hr);
    return NULL;
  }
  jclass autoClass = env->FindClass("org/racob/com/Dispatch");
  jmethodID autoCons = env->GetMethodID(autoClass, "<init>", "(I)V");
  // construct a Dispatch object to return
  // I am copying the pointer to java
  if (pD) pD->AddRef();
  jobject newAuto = env->NewObject(autoClass, autoCons, pD);
  return newAuto;
}
int lo_rio_requests(LightOPCServer *cli)
{
 loRequest *rq;
 loService *se = cli->se;

 while(rq = cli->q_req.req)
   {
    int operation = rq->operation;
    loTrid trid;

    if (loThrControl_outof01(&cli->async)) return -1;
    cli->q_req.req = rq->rq_next;
    if (operation & loRQ_OPER_IO)
      cli->q_req.metric_overload = 0;
    lw_mutex_unlock(&cli->async.lk);

    UL_TRACE((LOGID, "REQUEST Retreived %x / %x", operation, rq->upl.trqid));

    switch(operation & (loRQ_OPER_MASK | loRQ_DEVICE))
      {
#if LO_USE_BOTHMODEL
    case loRQ_OP_ADVISE:
      {
       void *aconn = 0;
       if (rq->conn_stream)
         {
          rq->upl.master_err = CoGetInterfaceAndReleaseStream(rq->conn_stream,
                                                             *rq->conn_iface,
                                                              &aconn);
          rq->conn_stream = 0;
         }
       else rq->upl.master_err = S_OK;
       if (SUCCEEDED(rq->upl.master_err))
         rq->upl.master_err = cli->sync_advise(operation, &aconn, rq->group_key);
       if (aconn) ((IUnknown*)aconn)->Release();
       if (operation & loRQ_SYNC)
         lo_req_put_bcast(&cli->q_ret, rq);
       else lo_req_free(rq);
      }
       break;

    case loRQ_OP_REMOVE_GROUP:
       rq->upl.master_err = cli->internalRemoveGroup(rq->group_key,
                                  operation & loRQ_OF_REMOVE_FORCE);
       if (operation & loRQ_SYNC)
         lo_req_put_bcast(&cli->q_ret, rq);
       else lo_req_free(rq);
       break;
#endif
/********************************************/

    case loRQ_OP_WRITE|loRQ_DEVICE:
       if (se->driver.ldWriteTags)
         {
          int rv;
          loLOCK_DRIVER(se);
          rv = se->driver.ldWriteTags(&rq->upl.rctx.cactx, rq->upl.used,
                                      rq->upl.tagpair, rq->upl.variant,
                                      rq->upl.errors, &rq->upl.master_err,
                                      rq->upl.rctx.cta.vc_lcid);
          loUNLOCK_DRIVER(se);
          if (rv == loDW_ALLDONE)
            {
             if (operation & loRQ_SYNC)
               lo_req_put_bcast(&cli->q_ret, rq);
             else
               {
                cli->send_callback(0, rq->group_key, &rq->upl, operation);
                lo_req_free(rq);
               }
             break;
            }
         }
// UL_ERROR((LOGID, "DEV WRITE failed"));
    case loRQ_OP_WRITE:
       rio_cache_write(se, &rq->upl);
       if (operation & loRQ_SYNC)
         lo_req_put_bcast(&cli->q_ret, rq);
       else
         {
          cli->send_callback(0, rq->group_key, &rq->upl, operation);
          lo_req_free(rq);
         }
       break;
/********************************************/

    case loRQ_OP_READ|loRQ_DEVICE:
       if (se->driver.ldReadTags /*&&
           !(cli->access_mode & (loAM_NOREAD_DEV |
                                 loAM_ERREAD_DEV))*/)
         {
          HRESULT m_err = rq->upl.master_err,
                  m_qual = rq->upl.master_qual;
          loLOCK_DRIVER(se);
          trid = se->driver.ldReadTags(&rq->upl.rctx.cactx, rq->upl.used,
                                       rq->upl.tagpair, rq->upl.variant, rq->upl.quality,
                                       rq->upl.timestamp, rq->upl.errors, &m_err, &m_qual,
                                       rq->upl.vartype, rq->upl.rctx.cta.vc_lcid);
          loUNLOCK_DRIVER(se);
          if (loDR_STORED == trid)
            {
             if (S_OK != m_err) rq->upl.master_err = S_FALSE;
             if (S_OK != m_qual) rq->upl.master_qual = S_FALSE;
             if (operation & loRQ_SYNC)
               lo_req_put_bcast(&cli->q_ret, rq);
             else
               {
                cli->send_callback(0, rq->group_key, &rq->upl, operation);
                lo_req_free(rq);
               }
             break;
            }
          else if (loDR_CACHED != trid) loTridWait(se, trid);
         }
    case loRQ_OP_READ:
       rio_cache_read(se, &rq->upl);
       if (operation & loRQ_SYNC)
         lo_req_put_bcast(&cli->q_ret, rq);
       else
         {
          cli->send_callback(0, rq->group_key, &rq->upl, operation);
          lo_req_free(rq);
         }
       break;
/********************************************/

    case loRQ_OP_REFRESH|loRQ_DEVICE:
       if (se->driver.ldReadTags /*&&
          !(cli->access_mode & (loAM_NOREAD_DEV |
                                loAM_ERREAD_DEV))*/)
         {
          loLOCK_DRIVER(se);
          trid = se->driver.ldReadTags(&rq->upl.rctx.cactx, 
                                       rq->upl.used, rq->upl.tagpair,
                                       0, 0, 0, 0, 0, 0, 0, 0
                                     /*rq->upl.variant, rq->upl.quality,
                                       rq->upl.timestamp, rq->upl.errors,
                                       &master_err, &master_qual,
                                       rq->upl.vartype, rq->upl.gr_lcid*/);
          loUNLOCK_DRIVER(se);
          if (loDR_CACHED != trid) loTridWait(se, trid);
         }
    case loRQ_OP_REFRESH:
       if (operation & loRQ_SYNC)
         UL_ERROR((LOGID, "SYNC REFRESH is invalid %x / %x", rq->operation, rq->upl.trqid));
       rio_refresh(cli, rq);
       break;
/********************************************/

    case loRQ_OP_CANCEL:
       cli->send_callback(0, rq->group_key, &rq->upl, operation);
       lo_req_free(rq);
       break;
/********************************************/

    default:
       UL_ERROR((LOGID, "BAD REQUEST %x / %x", rq->operation, rq->upl.trqid));
       lo_req_free(rq);
       break;
      }
#if 0
    if (rq) /*??*/
      {
       if (operation & loRQ_SYNC)
         lo_req_put_bcast(&cli->q_ret, rq);
       else
         {
          if (operation & loRQ_OPER_IO)
            cli->send_callback(0, rq->group_key, &rq->upl, operation);
          lo_req_free(rq);
         }
      }
#endif
    lw_mutex_lock(&cli->async.lk);
   }

 return 0;
}
Exemple #8
0
// Function name	: RedirectInputThread
// Description	    : 
// Return type		: void 
// Argument         : RedirectInputThreadArg *arg
void RedirectInputThread(RedirectInputThreadArg *arg)
{
	IRemoteShell *pLaunch=NULL;
	HRESULT hr=S_OK;
	HANDLE hObject[2];
	long error=0;
	BSTR berror_msg;
	DWORD ret_val;

	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

	berror_msg = SysAllocString(L"");
	CoGetInterfaceAndReleaseStream (*arg->ppStream, IID_IRemoteShell, (void**) &pLaunch);
	delete arg->ppStream;

	DWORD dwThreadID;
	HANDLE hRSIThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReadStdinThread, NULL, 0, &dwThreadID);

	hObject[0] = arg->hEvent;
	hObject[1] = g_hBufferEvent1;

	berror_msg = SysAllocString(L"");
	while (true)
	{
		ret_val = WaitForMultipleObjects(2, hObject, FALSE, INFINITE);
		if (ret_val == WAIT_OBJECT_0+1)
		{
			if (g_num_read > 0)
			{
				SAFEARRAYBOUND bound;
				VARIANT vInput;
				void *pBuf;

				VariantInit(&vInput);
				bound.lLbound = 0;
				bound.cElements = g_num_read;
				vInput.vt = VT_UI1 | VT_ARRAY;
				vInput.parray = SafeArrayCreate(VT_UI1, 1, &bound);

				SafeArrayAccessData(vInput.parray, &pBuf);
				memcpy(pBuf, g_pBuffer, g_num_read);
				SafeArrayUnaccessData(vInput.parray);

				error = 0;
				hr = pLaunch->PutProcessInput(vInput, &error, &berror_msg);
				if (FAILED(hr))
				{
					VariantClear(&vInput);
					printf("PutInteractiveInput failed: %d\n", hr);
					PrintError(hr);
					break;
				}
				if (error)
				{
					VariantClear(&vInput);
					if (wcslen(berror_msg) < 1)
						wprintf(L"PutInteractiveInput failed: %d %s\n", error, berror_msg);
					else
						wprintf(L"PutInteractiveInput failed: %s\n", berror_msg);
					break;
				}
				VariantClear(&vInput);
			}
			ResetEvent(g_hBufferEvent1);
			SetEvent(g_hBufferEvent2);
		}
		else
		{
			//printf("g_hFinishedEvent signalled\n");
		    TerminateThread(hRSIThread, 0);
			break;
		}
	}

	pLaunch->Release();
	CoUninitialize();
}
// HandleMessageForBuyThread runs in the context of the buy thread.
HRESULT HandleMessageForBuyThread(
   MSG* pMsg,
   CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx, 
   CComPtr<IWMPContentPartnerCallback> spCallback)
{
   BUY_CONTEXT* pBuyCtx = NULL;
   HRESULT hr = S_OK; 
   CComPtr<IWMPContentContainerList> spContainerList = NULL;
   ULONG numContainers = 0;

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

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

      ATLTRACE2("%x: HandleMessageForBuyThread: Received message to buy.\n", GetCurrentThreadId());     

      pBuyCtx = reinterpret_cast<BUY_CONTEXT*>(pMsg->lParam);

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

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

      // Get a pointer to an IWMPContentContainerList interface.

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

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

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

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

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

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

      ATLTRACE2("%x: HandleMessageForBuyThread: numContainers = %d.\n", GetCurrentThreadId(), numContainers);

      for(ULONG j = 0; j < numContainers; ++j)
      {
         ULONG numItems = 0;
         CComPtr<IWMPContentContainer> spContainer;

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

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

         if(FAILED(hr))
         {
            // Make sure we don't enter the for-k loop.
            numItems = 0;
         }    

         for(ULONG k = 0; k < numItems; ++k)
         {
            ULONG itemID = 0;

            hr = spContainer->GetContentID(k, &itemID);

            if(FAILED(hr))
            {
               break;  // Break out of the for-k loop.
            }

            // ToDo: Update records to reflect the purchase of this item.

            ATLTRACE2("%x: HandleMessageForBuyThread: Buying item %d.\n",GetCurrentThreadId(), itemID);

         } // for k
      } // for j   

      // Tell Windows Media Player that we have finished 
      // processing the purchase request.

      hr = spCallback->BuyComplete(S_OK, pBuyCtx->cookie);

      if(FAILED(hr))
      {
         ATLTRACE2("%x: HandleMessageForBuyThread: Failed to notify Windows Media Player that a purchase is complete. %x\n", GetCurrentThreadId(), hr);
         goto cleanup;
      }
   } // buy message

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

   if(NULL != pThreadCtx && NULL != pMsg)
   {

      if(pThreadCtx->buyThreadContext.msgBuy == pMsg->message)
      {
         // The thread that posted this message allocated a 
         // BUY_CONTEXT structure.
         // We must free that memory here.

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

            delete pBuyCtx;
            pBuyCtx = NULL;
         }
      }
   }
   return hr;
}
Exemple #10
0
HRESULT CWordObject::Release()
{
	HRESULT hr;
	
	if (m_pUnknown == NULL) 
		return S_OK;

	LPUNKNOWN lpUnk = NULL;
	
	if (m_pStrUnknown != NULL)
	{
		hr = CoGetInterfaceAndReleaseStream(m_pStrUnknown, IID_IUnknown, (void**) &lpUnk);
		if (FAILED(hr))
		{
			LOG_WS_ERROR(_T("CoGetInterfaceAndReleaseStream FAILED."));	
		}
	}
	else
	{
		lpUnk = m_pUnknown;
		m_pWordCreator->AddRef(lpUnk);
	}


	try
	{
		m_pUnknown->Release();
		m_pUnknown = NULL;
	}
	catch(...)
	{
		m_pUnknown = NULL;
		LOG_WS_ERROR(_T("m_pUnknown Failed to release"));
	}

	
	if (NULL == lpUnk)
	{
		LOG_WS_ERROR(_T("lpUnk == NULL"));
		return E_FAIL;
	}



	if (m_bUsingCurrentInstance)
	{	
		hr = S_FALSE;
	}
	else if (!IsVisible(lpUnk))
	{
		hr = Quit(lpUnk);
	}
	else
	{
		// If Word is visible, then only quit the cached Word instance if we are sure that
		// there aren't any manually opened documents.  i.e. if the user has opened a document,
		// so that there is a visible instance of Word open while DeltaVw is still open.
		Word::_ApplicationPtr pApp = GetApplicationPtr();

		if( pApp )
		{
			long lNumDocs = pApp->Documents->Count;

			if( lNumDocs <= 0 )
			{
				LOG_WS_INFO(L"No open documents found for the current Word instance.  Quitting Word");

				SetVisible(false);
				hr = Quit(lpUnk);
			}
			else
			{
				LOG_WS_INFO(L"Documents are still open in the current Word instance.  NOT quitting Word");
			}
		}
	}

	if (IsCachingWordEnabled())
		m_pGit->RevokeInterfaceFromGlobal(m_dwSessionCookie);

	try
	{
		if (lpUnk)
		{
			lpUnk->Release();
			lpUnk = NULL;			
		}
	}
	catch(...)
	{
		lpUnk = NULL;	
		LOG_WS_ERROR(_T("m_pUnknown Failed to release"));
	}

	// This is required to stop the DeltaView app tests from hanging
	Sleep(125);
	
	return hr;
}
DWORD WINAPI ContentPartnerThreadProc(LPVOID lpParameter)
{
   CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx = NULL;
   CComPtr<IWMPContentPartnerCallback> spCallback;
   MSG msg = {0};
   HRESULT hr = S_OK;
   BOOL comInitialized = FALSE;

   if(NULL == lpParameter)
   {
      hr = E_INVALIDARG;
      goto cleanup;
   }

   pThreadCtx = static_cast<CONTENT_PARTNER_THREAD_CONTEXT*>(lpParameter);

   if(NULL == pThreadCtx->pIStream)
   {
      hr = E_INVALIDARG;
      goto cleanup;
   }

   hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

   if(FAILED(hr))
   {
      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): CoInitializeEx failed. %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);
      goto cleanup;
   }  

   comInitialized = TRUE;

   // Get a pointer to an IWMPContentPartnerCallback interface.

   hr = CoGetInterfaceAndReleaseStream(
      pThreadCtx->pIStream,
      __uuidof(IWMPContentPartnerCallback),
      reinterpret_cast<LPVOID*>(&spCallback) );

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

   if(FAILED(hr))
   {
      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Failed to get IWMPContentPartnerCallback interface. %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);
      goto cleanup;
   }

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

   ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Succeeded in getting IWMPContentPartnerCallback interface.\n", GetCurrentThreadId(), pThreadCtx->threadType);

   // Make sure we have a message queue.
   PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);

   // Tell the main thread that we are ready to receive messages.
   SetEvent(pThreadCtx->hInitialized);

   hr = ContentPartnerMessageLoop(pThreadCtx, spCallback);

cleanup:

   if(NULL != pThreadCtx)
   {
      // Set this event here, just in case there was a "goto cleanup"
      // before the event was set.
      SetEvent(pThreadCtx->hInitialized);

      // The thread that started this thread allocated a
      // CONTENT_PARTNER_THREAD_CONTEXT structure.
      // We must free that memory here.
   
     if(NULL != pThreadCtx->pIStream)
      {
         // For some reason, CoGetInterfaceAndReleaseStream never got called.
         // So release the stream here.
         pThreadCtx->pIStream->Release();
         pThreadCtx->pIStream = NULL;
      }

      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Returning %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);

      delete pThreadCtx;
      pThreadCtx = NULL;
   }
                   
   if(comInitialized)
   {
      CoUninitialize();
   } 

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

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

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

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

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

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

      // Get a pointer to an IWMPContentContainerList interface.

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

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

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

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

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

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

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

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

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

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

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

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

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

            bstrUrl = SysAllocString(url);

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

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

            // Ignore hr.

            SysFreeString(bstrUrl);

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

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

cleanup:

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

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

   return hr;    
     
} // HandleMessageForDownloadThread
Exemple #13
0
void CSaveDataBase::WorkFunction()
{
	IComHistIntPtr  pHistory = NULL;
	IMessagesPtr    pMessagesList = NULL;
	/// UnMarshaling ...
	if(SUCCEEDED(hr))
		hr = CoGetInterfaceAndReleaseStream(pHistoryStream,__uuidof(IComHistInt),(LPVOID*)&pHistory);
	if(SUCCEEDED(hr))
		hr = CoGetInterfaceAndReleaseStream(pMessagesStream,__uuidof(IMessages),(LPVOID*)&pMessagesList);
	
	if(SUCCEEDED(hr))
	{
		/// Save To History ...
		bstr_t SID, MID, Body; 
		long   Time, ToId , FromId, RecipientSize; 
		IMessagePtr pMessage;
		IUsersPtr pUserList;
		
		try
		{
			long Size = pMessagesList->GetCount();
			SID = LoadSID;
			
			for(int i=1;i<=Size;i++)
			{
				if(bExit)
				{
					SetEvent(hExitEvent);
					return;
				}
				pMessage = pMessagesList->GetItem(i);
				
				MID  = pMessage->GetMID(); 
				Body = pMessage->GetBody();
				Time = pMessage->Getdate_time(); 
				pUserList = pMessage->GetRecipients();
				RecipientSize = pUserList->GetCount();
				FromId = CUser(pMessage->GetSender()).GetGlobalID();
				
				for(int j=0;j<RecipientSize;j++)
				{
					ToId   = CUser(pUserList->GetItem(j)).GetGlobalID();
					try
					{
						hr = pHistory->AddMessage(FromId,ToId,SID, MID,Time,TRUE,Body,VARIANT_FALSE);
					}
					catch(...)
					{}
				}
			}
		}
		
		catch(...)
		{
			ASSERT(FALSE);
		}
	}

	/// PostMessage About Ok
	if(::IsWindow(hWindow))
		PostMessage(hWindow,dwMessage,(WPARAM)hr,(LPARAM)this);
	else
		delete this;		
	/// End 
	SetEvent(hExitEvent);
}