Exemplo n.º 1
0
STDMETHODIMP TCUtilImpl::CreateObject(BSTR bstrProgID, BSTR bstrComputer,
  IUnknown** ppUnk)
{
  // Initialize the [out] parameter
  CLEAROUT(ppUnk, (IUnknown*)NULL);

  // Convert the specified ProgID to a CLSID
  CLSID clsid;
  if (!BSTRLen(bstrProgID))
    return E_INVALIDARG;
  RETURN_FAILED(CLSIDFromProgID(bstrProgID, &clsid));

  // Initialize the COSERVERINFO and MULTI_QI structures
  COSERVERINFO csi   = {0, bstrComputer, NULL, 0};
  MULTI_QI     mqi[] =
  {
    {&IID_IUnknown                 , NULL, S_OK},
    {&IID_IDispatch                , NULL, S_OK},
    {&IID_IConnectionPointContainer, NULL, S_OK},
  };
  const static ULONG cMQI = sizeofArray(mqi);

  // Determine if the specified computer name is definitely local
  bool bLocalForSure = true;
  if (BSTRLen(bstrComputer))
  {
    TCHAR szLocal[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD cchLocal = sizeofArray(szLocal);
    GetComputerName(szLocal, &cchLocal);
    USES_CONVERSION;
    bLocalForSure = !_tcsicmp(szLocal, OLE2CT(bstrComputer));
  }
  DWORD dwClsCtx = bLocalForSure ? CLSCTX_SERVER : CLSCTX_REMOTE_SERVER;

  // Attempt to create the instance
  HRESULT hr = CoCreateInstanceEx(clsid, NULL, dwClsCtx, &csi, cMQI, mqi);
  if (FAILED(hr))
  {
    _TRACE_BEGIN
      _TRACE_PART1("TCCreateObject failed: hr=0x%08X", hr);
      _TRACE_PART1(", dwClsCtx=%hs", (CLSCTX_SERVER == dwClsCtx) ?
        "CLSCTX_SERVER" : "CLSCTX_REMOTE_SERVER");
      _TRACE_PART1(", ProgID=\"%ls\"", bstrProgID);
      _TRACE_PART1(", Computer= \"%ls\"\n", bstrComputer ?
        bstrComputer : L"");
    _TRACE_END
    return hr;
  }

  // Copy the IUnknown interface pointer to the [out] parameter
  *ppUnk = mqi[0].pItf;

  // Release each interface not being returned
  for (ULONG i = 1; i < cMQI; ++i)
    if (mqi[i].pItf)
      mqi[i].pItf->Release();

  // Return the result of the QI for IUnknown
  return mqi[0].hr;
}
Exemplo n.º 2
0
QString TrManager::GetDamageString(const damage_kinds damage_kind) {
    static const QString damageNames[] = {
        QCoreApplication::translate("Global", "mining"   ),
        QCoreApplication::translate("Global", "digging"  ),
        QCoreApplication::translate("Global", "cutting"  ),
        QCoreApplication::translate("Global", "thrusting"),
        QCoreApplication::translate("Global", "crushing" ),
        QCoreApplication::translate("Global", "heating"  ),
        QCoreApplication::translate("Global", "freezing" ),
        QCoreApplication::translate("Global", "electricity"),
        QCoreApplication::translate("Global", "corrode"  ),
        QCoreApplication::translate("Global", "hunger"   ),
        QCoreApplication::translate("Global", "breathing"),
        QCoreApplication::translate("Global", "biting"   ),
        QCoreApplication::translate("Global", "time"     ),
        QCoreApplication::translate("Global", "pushing"  )
    };
    QStringList result;
    for (int i = 1, c = 0; i < DAMAGE_PUSH_UP; i <<= 1, ++c) {
        if (damage_kind & i) {
            result.append(damageNames[c]);
        }
    }
    if (damage_kind & DAMAGE_PUSH_ANYWHERE) {
        result.append(damageNames[sizeofArray(damageNames) - 1]);
    }
    return result.join(Str(", "));
}
Exemplo n.º 3
0
void RegisterMonolithicDPlay()
{
	HKEY hKey = NULL;
	const char * szKey = "CLSID\\{DA9CABC6-C724-4265-A61D-6E78EB2042B4}\\InprocServer32";
	// check to see if it's already registered, and if so, do nothing, otherwise register it
	if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_CLASSES_ROOT, szKey, 0, KEY_READ, &hKey))
	{
		// Get the module path
		TCHAR szFilePath[_MAX_PATH * 2], szDrive[_MAX_DRIVE], szDir[_MAX_DIR * 2];
		::GetModuleFileName(NULL, szFilePath, sizeofArray(szFilePath));
		_tsplitpath(szFilePath, szDrive, szDir, NULL, NULL);
		_tmakepath(szFilePath, szDrive, szDir, NULL, NULL);
		int cch = _tcslen(szFilePath);
		if (TEXT('\\') == szFilePath[cch - 1])
			szFilePath[cch - 1] = TEXT('\0');

		// Update the registry from the DPMono.rgs
		USES_CONVERSION;
		_ATL_REGMAP_ENTRY regmap[] =
		{
		  {L"MODULE_PATH", T2COLE(szFilePath)},
		  {NULL          ,               NULL},
		};
		_Module.UpdateRegistryFromResource(IDR_DPMONO, true, regmap);
	}
	else
	{
		RegCloseKey(hKey);
	}
}
HRESULT CTCPropBagOnRegKey::_SaveObject(const _bstr_t& strName,
  IUnknown* punkObj, BOOL bClearDirty, BOOL bSaveAllProperties)
{
  // Validate the specified parameters
  if (IsBadReadPtr(punkObj))
    return E_POINTER;

  // Create a subkey with the specified name
  CRegKey subkey;
  if (!strName.length())
    subkey = m_key;
  else
  {
    m_key.DeleteValue(strName);
    m_key.RecurseDeleteKey(strName);
    if (!subkey.Open(m_key, strName))
      return HRESULT_FROM_WIN32(GetLastError());
  }

  // QueryInterface for IPersistPropertyBag
  IPersistPropertyBagPtr pppb;
  HRESULT hr = punkObj->QueryInterface(__uuidof(pppb), (void**)&pppb);
  if (FAILED(hr))
    return hr;

  // Get the object's CLSID
  CLSID clsid;
  hr = pppb->GetClassID(&clsid);
  if (FAILED(hr))
    return hr;

  // Attempt first to convert the object's CLSID to a ProgID
  LPOLESTR pszProgID = NULL;
  if (SUCCEEDED(ProgIDFromCLSID(clsid, &pszProgID)))
  {
    subkey.WriteString(m_szProgID, pszProgID);
    CoTaskMemFree(pszProgID);
  }
  else
  {
    // Convert the object's CLSID to a string
    OLECHAR szClassID[64];
    StringFromGUID2(clsid, szClassID, sizeofArray(szClassID));
    subkey.WriteString(m_szCLSID, szClassID);
  }

  // Write the variant type value
  subkey.WriteDWord(m_szVariantType, DWORD(VarTypeFromUnknown(punkObj)));

  // Save the persistent properties of the object
  CComObjectStack<CTCPropBagOnRegKey> bag;
  bag.Init(subkey, strName, this);
  hr = pppb->Save(&bag, bClearDirty, bSaveAllProperties);

  // Return the last HRESULT
  return hr;
}
Exemplo n.º 5
0
/////////////////////////////////////////////////////////////////////////////
// Description: Creates a relative path name, if possible.
//
// Parameters:
//   bBeginWithDot - Prepends the relative path with the a period and
// backslash. While possibly rendundant, this may be useful for some contexts
// of relative pathnames. If a relative path cannot be resolved, this
// parameter is ignored.
//
bool TCMakeRelativePath(LPCTSTR pszPath, LPCTSTR pszFrom, LPTSTR pszDest,
  int cchMaxDest, bool bBeginWithDot)
{
  // Ensure that input paths are absolute
  TCHAR szPathCopy[_MAX_PATH], szFromCopy[_MAX_PATH];
  if (!_tfullpath(szPathCopy, pszPath, sizeofArray(szPathCopy)))
    return false;
  if (!_tfullpath(szFromCopy, pszFrom, sizeofArray(szFromCopy)))
    return false;

  // Replace (in-place) forward slashes with backslashes in input paths
  TCReplaceText(szPathCopy, TEXT("/"), TEXT("\\"), szPathCopy, -1);
  TCReplaceText(szFromCopy, TEXT("/"), TEXT("\\"), szFromCopy, -1);

  // The From path MUST be a directory, not a filename, so append backslash
  if (TEXT('\\') != szFromCopy[_tcslen(szFromCopy) - 1])
    _tcscat(szFromCopy, TEXT("\\"));

  // Use COM monikers to create a relative path
  HRESULT hr;
  IBindCtxPtr pbc;
  IMonikerPtr pmkFrom, pmkPath, pmkRelative;
  LPOLESTR pszRelative = NULL;
  if (SUCCEEDED(hr = CreateFileMoniker(_bstr_t(szFromCopy), &pmkFrom))
    && SUCCEEDED(hr = CreateFileMoniker(_bstr_t(szPathCopy), &pmkPath))
    && S_OK == (hr = pmkFrom->RelativePathTo(pmkPath, &pmkRelative))
    && SUCCEEDED(hr = CreateBindCtx(0, &pbc))
    && SUCCEEDED(hr = pmkRelative->GetDisplayName(pbc, NULL, &pszRelative)))
  {
    if (bBeginWithDot)
    {
      TC_tcscpyn(pszDest, TEXT(".\\"), cchMaxDest);
      cchMaxDest -= 2;
      pszDest += 2;
    }
    TC_tcscpyn(pszDest, _bstr_t(pszRelative), cchMaxDest);
    CoTaskMemFree(pszRelative);
    return true;
  }

  // Could not make a relative path, copy the absolute path
  TC_tcscpyn(pszDest, szPathCopy, cchMaxDest);
  return false;
}
Exemplo n.º 6
0
HRESULT CPigEngine::EnsureScriptsAreLoaded()
{
  // Return immediately if this initialization has already completed
  XLock lock(this);
  if (!m_hDirChange.IsNull() && m_pth)
    return S_OK;

  // Open the registry key of the AppID
  CRegKey key;
  RETURN_FAILED(_Module.OpenAppIDRegKey(key, KEY_READ));

  // Initialize the art path
  TCHAR szArtPath[_MAX_PATH];
  DWORD cch = sizeofArray(szArtPath);
  long lr = key.QueryValue(szArtPath, TEXT("ArtPath"), &cch);
  if (ERROR_SUCCESS != lr)
    return HRESULT_FROM_WIN32(lr);
  UTL::SetArtPath(szArtPath);

  // Convert the directory name to ANSI
  USES_CONVERSION;
  LPSTR pszScriptDir = OLE2A(m_bstrScriptDir);

  // Remove the whack at the end of the string
  cch = strlen(pszScriptDir);
  assert('\\' == pszScriptDir[cch - 1]);
  pszScriptDir[cch - 1] = '\0';

  // Ensure that the directory exists
  WIN32_FIND_DATA ffd;
  TCFileFindHandle hff = FindFirstFile(pszScriptDir, &ffd);
  if(hff.IsNull() || INVALID_HANDLE_VALUE == hff)
    return HRESULT_FROM_WIN32(GetLastError());

  // Initialize our record of the directory contents
  ProcessScriptDirChanges();

  // Create a directory change notification object
  const DWORD dwFilter = FILE_NOTIFY_CHANGE_FILE_NAME |
    FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_LAST_WRITE;
  m_hDirChange = FindFirstChangeNotification(pszScriptDir, false, dwFilter);
  if (INVALID_HANDLE_VALUE == m_hDirChange)
    return HRESULT_FROM_WIN32(GetLastError());

  // Create the thread that monitors the ProfileScriptDir folder
  m_pth = TCThread::BeginMsgThread(ScriptDirThunk, this,
    THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
  if (!m_pth)
    return E_FAIL;
  m_pth->ResumeThread();

  // TODO: Create the thread that monitors the CLSID registry key

  // Indicate success
  return S_OK;
}
Exemplo n.º 7
0
bool ZVersionInfo::Load(HINSTANCE hinstance)
{
  // Get the module name of the specified instance
  TCHAR szModule[_MAX_PATH];
  if (!GetModuleFileName(hinstance, szModule, sizeofArray(szModule)))
    return false;

  // Pass on to the string overload of this function
  return Load(szModule);
}
Exemplo n.º 8
0
STDMETHODIMP CPigShip::InterfaceSupportsErrorInfo(REFIID riid)
{
    static const IID* arr[] =
    {
        &IID_IPigShip,
    };
    for (int i = 0; i < sizeofArray(arr); ++i)
    {
        if (InlineIsEqualGUID(*arr[i], riid))
            return S_OK;
    }
    return S_FALSE;
}
HKEY CTCPropBagOnRegKey::RootKeyFromString(BSTR bstrRegKey, DWORD* cchEaten)
{
  // Define a static lookup table
  struct XRootKeys
  {
    LPCOLESTR pszName;
    DWORD     cchName;
    HKEY      hkey;
  };
  const static XRootKeys s_table[] =
  {
    {L"HKCR\\"                 ,  5, HKEY_CLASSES_ROOT    },
    {L"HKCU\\"                 ,  5, HKEY_CURRENT_USER    },
    {L"HKLM\\"                 ,  5, HKEY_LOCAL_MACHINE   },
    {L"HKCC\\"                 ,  5, HKEY_CURRENT_CONFIG  },
    {L"HKPD\\"                 ,  5, HKEY_PERFORMANCE_DATA},
    {L"HKDD\\"                 ,  5, HKEY_DYN_DATA        },

    {L"HKEY_CLASSES_ROOT\\"    , 18, HKEY_CLASSES_ROOT    },
    {L"HKEY_CURRENT_USER\\"    , 18, HKEY_CURRENT_USER    },
    {L"HKEY_LOCAL_MACHINE\\"   , 19, HKEY_LOCAL_MACHINE   },
    {L"HKEY_CURRENT_CONFIG\\"  , 20, HKEY_CURRENT_CONFIG  },
    {L"HKEY_PERFORMANCE_DATA\\", 22, HKEY_PERFORMANCE_DATA},
    {L"HKEY_DYN_DATA\\"        , 14, HKEY_DYN_DATA        },
  };
  const static long s_cEntries = sizeofArray(s_table);

  // Search for an allowed root key name
  if (BSTRLen(bstrRegKey))
  {
    for (long i = 0; i < s_cEntries; ++i)
    {
      if (!wcsnicmp(s_table[i].pszName, bstrRegKey, s_table[i].cchName))
      {
        *cchName = s_table[i].cchName;
        return s_table[i].hkey;
      }
    }
  }

  // Could not find the specified string
  *cchName = 0;
  return NULL;
}
Exemplo n.º 10
0
/*-------------------------------------------------------------------------
 * get_ProductVersion()
 *-------------------------------------------------------------------------
 * Purpose:
 *    Determine the version number of AllSrv
 *
 */
STDMETHODIMP CAdminSession::get_Version(IAGCVersionInfo** ppVersion)
{
	// Initialize the [out] parameter
	CLEAROUT(ppVersion, (IAGCVersionInfo*)NULL);

	// Create an instance of the version object
	IAGCVersionInfoPtr spVersion;
	RETURN_FAILED(spVersion.CreateInstance(CLSID_AGCVersionInfo));

	// Initialize the version object
	TCHAR szModule[_MAX_PATH];
	GetModuleFileName(_Module.GetModuleInstance(), szModule, sizeofArray(szModule));
	RETURN_FAILED(spVersion->put_FileName(CComBSTR(szModule)));

	// Detach the object to the [out] parameter
	*ppVersion = spVersion.Detach();

	// Indicate success
	return S_OK;
}
Exemplo n.º 11
0
HRESULT CPigEngine::get_ArtPath(BSTR* pbstrArtPath)
{
  // Initialize the [out] parameter
  CLEAROUT(pbstrArtPath, (BSTR)NULL);

  // Open the registry key of the AppID
  CRegKey key;
  RETURN_FAILED(_Module.OpenAppIDRegKey(key, KEY_READ));

  // Read the value
  TCHAR szArtPath[_MAX_PATH];
  DWORD cch = sizeofArray(szArtPath);
  long lr = key.QueryValue(szArtPath, TEXT("ArtPath"), &cch);
  if (ERROR_SUCCESS != lr)
    szArtPath[0] = TEXT('\0');

  // Create a BSTR
  USES_CONVERSION;
  *pbstrArtPath = SysAllocString(T2COLE(szArtPath));

  // Indicate success
  return S_OK;
}
STDMETHODIMP CAdminEventLoggerHook::LogEvent(IAGCEvent* pEvent, VARIANT_BOOL bSynchronous)
{
  // Do nothing if SQLCore has not been initialized
  if (!g.sql.GetNotifyThreadID())
    return S_OK;

  // Get the fields of the specified event object
  AGCEventID idEvent;
  long       idSubject;
  CComBSTR   bstrComputerName, bstrSubjectName, bstrContext;
  ZSucceeded(pEvent->get_ID(&idEvent));
  ZSucceeded(pEvent->get_SubjectID   (&idSubject       ));
  ZSucceeded(pEvent->get_ComputerName(&bstrComputerName));
  ZSucceeded(pEvent->get_SubjectName (&bstrSubjectName ));
  ZSucceeded(pEvent->get_Context     (&bstrContext     ));

  // Use a callback if event is synchronous
  void (*pfnDataReady)(CQLogEvent* pquery) = bSynchronous ? EventLogged : NULL;

  // Create the database update query
  CQLogEvent*  pquery = new CQLogEvent(pfnDataReady);
  CQLogEventData* pqd = pquery->GetData();

  // Ensure that the callback does NOT go through the message queue
  pquery->SetCallbackOnMainThread(false);

  // Populate the query parameters from the event fields
  USES_CONVERSION;
	pqd->nEvent   = idEvent;
	pqd->nSubject = idSubject;
  if (bstrComputerName.Length())
    lstrcpyn(pqd->szComputerName, OLE2CT(bstrComputerName), sizeofArray(pqd->szComputerName));
  else
    pqd->szComputerName[0] = TEXT('\0');
  if (bstrSubjectName.Length())
    lstrcpyn(pqd->szSubjectName, OLE2CT(bstrSubjectName), sizeofArray(pqd->szSubjectName));
  else
    pqd->szSubjectName[0] = TEXT('\0');
  if (bstrContext.Length())
    lstrcpyn(pqd->szContext, OLE2CT(bstrContext), sizeofArray(pqd->szContext));
  else
    pqd->szContext[0] = TEXT('\0');

  // Get the event object as a string
  assert(IPersistStreamInitPtr(pEvent) != NULL || IPersistStreamPtr(pEvent) != NULL);
  assert(IMarshalPtr(pEvent) != NULL);
  CComBSTR bstrTemp;
  ZSucceeded(pEvent->SaveToString(&bstrTemp));
  WideCharToMultiByte(CP_ACP, 0, bstrTemp, -1,
    pqd->szObjectRef, sizeof(pqd->szObjectRef), 0, 0);

  // Create an event upon which to wait, if event is synchronous
  TCHandle shevt;
  if (bSynchronous)
    shevt = ::CreateEvent(NULL, false, false, NULL);
  pqd->hevt = shevt.GetHandle();

  // Post the query for async completion
  g.sql.PostQuery(pquery);

  // Wait for the event, if event is synchronous
  if (!shevt.IsNull())
    ::WaitForSingleObject(shevt, INFINITE);

  // Indicate that we handled it
  return S_OK;
}
void CPagePlayers::LoadFromRegistry()
{
  // Open/create the registry key
  CRegKey key;
  key.Create(HKEY_LOCAL_MACHINE, HKLM_AllSrvUI);

  // PlayerListColumnOrder
  CComBSTR bstrColumnOrder;
  LoadRegString(key, TEXT("PlayerListColumnOrder"), bstrColumnOrder);
  m_spStrings->RemoveAll();
  m_spStrings->AddDelimited(CComBSTR(L","), bstrColumnOrder);
  long cOrderedColumns = 0;
  m_spStrings->get_Count(&cOrderedColumns);
  if (c_cColumns == cOrderedColumns)
  {
    int vecOrder[c_cColumns];
    for (CComVariant i(0L); V_I4(&i) < c_cColumns; ++V_I4(&i))
    { 
      bstrColumnOrder.Empty();
      m_spStrings->get_Item(&i, &bstrColumnOrder);
      vecOrder[V_I4(&i)] = _wtoi(bstrColumnOrder);
    }
    m_listPlayers.SetColumnOrderArray(c_cColumns, vecOrder);
  }

  // PlayerListColumnWidths
  CComBSTR bstrColumnWidths;
  LoadRegString(key, TEXT("PlayerListColumnWidths"), bstrColumnWidths);
  m_spStrings->RemoveAll();
  m_spStrings->AddDelimited(CComBSTR(L","), bstrColumnWidths);
  long cWidthColumns = 0;
  m_spStrings->get_Count(&cWidthColumns);
  if (c_cColumns == cWidthColumns)
  {
    for (CComVariant i(0L); V_I4(&i) < c_cColumns; ++V_I4(&i))
    { 
      bstrColumnWidths.Empty();
      m_spStrings->get_Item(&i, &bstrColumnWidths);
      m_listPlayers.SetColumnWidth(V_I4(&i), _wtoi(bstrColumnWidths));
    }
  }
  else
  {
    for (int i = 0; i < c_cColumns; ++i)
    {
      TCHAR szColumn[_MAX_PATH];
      LVCOLUMN lvc = {LVCF_TEXT, 0, 0, szColumn, sizeofArray(szColumn)};
      m_listPlayers.GetColumn(i, &lvc);
      int cx = m_listPlayers.GetStringWidth(CString(szColumn) + TEXT("    "));
      m_listPlayers.SetColumnWidth(i, cx);
    }
  }

  // SendChatMRU
  m_comboSendChat.ResetContent();
  CRegKey keyMRU;
  if (ERROR_SUCCESS == keyMRU.Create(key, TEXT("SendChatMRU")))
  {
    // Read the count of strings
    DWORD cStrings = 0;
	// mdvalley: Former QueryDWORDValue(cStr, TEXT);
    keyMRU.QueryValue(cStrings, TEXT(".Count"));

    // Read each string and add it to the combo box
    for (DWORD i = 0; i < cStrings; ++i)
    {
      TCHAR szInt[16];
      CString strMRUItem;
      LoadRegString(keyMRU, _itot(i, szInt, 10), strMRUItem);
      strMRUItem.TrimLeft();
      strMRUItem.TrimRight();
      if (!strMRUItem.IsEmpty())
        m_comboSendChat.InsertString(i, strMRUItem);
    }
  }
}
Exemplo n.º 14
0
ZString ZVersionInfo::GetStringValue(LPCTSTR pszKey, bool* pbExists) const
{
  // Initialize the [out] parameter
  if (pbExists)
    *pbExists = false;

  // Ensure that we have a non-NULL key
  if (!pszKey)
  {
    SetLastError(ERROR_INVALID_PARAMETER);
    return ZString();
  }

  // Determine if a LANGID was specified
  LANGID wLangID = LANGID((LANGID(-1) == GetLanguageID()) ?
    MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US) : GetLanguageID());

  // Determine if a code page was specified
  WORD rgwCodePages[] =
  {
    1200,  // Unicode
    1252,  // Windows Multilingual
    0000,  // Neutral
  };
  int cCodePages = sizeofArray(rgwCodePages);
  if (WORD(-1) != m_wCodePage)
  {
    rgwCodePages[0] = m_wCodePage;
    cCodePages = 1;
  }

  // Format the base sub-block string
  TCHAR szBase[32];
  _stprintf_s(szBase, 32, TEXT("\\StringFileInfo\\%04X"), wLangID);

  // Loop thru each code page
  for (int iCP = 0; iCP < cCodePages; ++iCP)
  {
    // Format a sub-block string
    TCHAR szSubBlock[_MAX_PATH * 2];
    _stprintf_s(szSubBlock, _MAX_PATH * 2, TEXT("%s%04X\\%s"), szBase, rgwCodePages[iCP], pszKey);

    // Query the value
    UINT cbValue = 0;
    LPCTSTR pszValue = NULL;
    if (VerQueryValue(m_pVerInfo, szSubBlock, (void**)&pszValue, &cbValue))
    {
      // Indicate that the key exists
      if (pbExists)
        *pbExists = true;

      // Indicate success
      SetLastError(0);
      return ZString(pszValue);
    }
  }

  // Indicate success
  SetLastError(0);
  return ZString();  
}
Exemplo n.º 15
0
HRESULT CPigEngine::Construct()
{
  // Get the path name of the module
  TCHAR szModule[_MAX_PATH];
  _VERIFYE(GetModuleFileName(_Module.GetModuleInstance(), szModule,
    sizeofArray(szModule)));

  // Break the path name of the module into pieces
  TCHAR szDrive[_MAX_DRIVE], szDir[_MAX_DIR], szName[_MAX_FNAME];
  _tsplitpath(szModule, szDrive, szDir, szName, NULL);

  // Open the registry key of the AppID
  CRegKey key;
  RETURN_FAILED(_Module.OpenAppIDRegKey(key, KEY_READ));

  // Create the event logger object
  RETURN_FAILED(m_spEventLogger.CreateInstance("AGC.EventLogger"));

  // Initialize the event logger object
  CComBSTR bstrEventSource(L"PigSrv");
  CComBSTR bstrRegKey(L"HKCR\\AppID\\{F132B4E3-C6EF-11D2-85C9-00C04F68DEB0}");
  IAGCEventLoggerPrivatePtr spPrivate(m_spEventLogger);
  RETURN_FAILED(spPrivate->Initialize(bstrEventSource, bstrRegKey));

  // Load the MissionServer registry value
  LoadRegString(key, TEXT("MissionServer"), m_bstrMissionServer);

  // Load the AccountServer registry value
  LoadRegString(key, TEXT("AccountServer"), m_bstrAccountServer);

  // Load the ZoneAuthServer registry value
  LoadRegString(key, TEXT("ZoneAuthServer"), m_bstrZoneAuthServer);

  // Load the ZoneAuthTimeout registry value
  DWORD dwZoneAuthTimeout;
  if (ERROR_SUCCESS == key.QueryValue(dwZoneAuthTimeout, TEXT("ZoneAuthTimeout")))
    m_nZoneAuthTimeout = static_cast<long>(dwZoneAuthTimeout);

  // Load the LobbyMode registry value
  DWORD dwLobbyMode;
  if (ERROR_SUCCESS == key.QueryValue(dwLobbyMode, TEXT("LobbyMode")))
    m_eLobbyMode =
      (PigLobbyMode_Club <= dwLobbyMode && dwLobbyMode <= PigLobbyMode_Free) ?
        static_cast<PigLobbyMode>(dwLobbyMode) : PigLobbyMode_Club;

  // Attempt to read the ScriptDir value from the registry
  ZString strScriptDir;
  LoadRegString(key, TEXT("ScriptDir"), strScriptDir);

  // Create a directory name from the root directory, by default
  if (strScriptDir.IsEmpty())
  {
    TCHAR szScriptDir[_MAX_PATH + 1];
    _tmakepath(szScriptDir, szDrive, szDir, TEXT("Scripts"), NULL);
    strScriptDir = szScriptDir;
  }

  // Ensure that m_bstrScriptDir ends with a whack
  int nLastChar = strScriptDir.GetLength() - 1;
  if (TEXT('\\') != strScriptDir[nLastChar])
    strScriptDir += ZString("\\");

  // Save the directory name
  m_bstrScriptDir = strScriptDir;

  // Create the pigs collection object with a ref count
  assert(!m_pPigs);
  CComObject<CPigs>* pPigs = NULL;
  RETURN_FAILED(pPigs->CreateInstance(&pPigs));
  (m_pPigs = pPigs)->AddRef();

  // Indicate success
  return S_OK;
}
Exemplo n.º 16
0
void CPigEngine::ScriptDirMonitor(HANDLE hevtExit)
{
  assert(m_hDirChange && INVALID_HANDLE_VALUE != m_hDirChange);

  // Enter this thread into the MTA
  _SVERIFYE(CoInitializeEx(NULL, COINIT_MULTITHREADED));

  // Declare an enum and an array of objects on which to wait
  enum {e_DirChange = WAIT_OBJECT_0, e_Exit, e_Msg};
  HANDLE hObjs[] = {m_hDirChange, hevtExit};
  const int cObjs = sizeofArray(hObjs);

  // Process change notification until exit
  UINT idTimer = 0;
  DWORD dwWait = MsgWaitForMultipleObjects(cObjs, hObjs, false, INFINITE,
    QS_ALLINPUT);
  while (e_Exit != dwWait)
  {
    if (e_DirChange == dwWait)
    {
      // Reset the timer
      if (idTimer)
        KillTimer(NULL, idTimer);
      idTimer = SetTimer(NULL, 0, 2000, NULL);

      // Continue waiting for change notifications
      if (!FindNextChangeNotification(m_hDirChange))
      {
        #ifdef _DEBUG
          DWORD dwLastError = ::GetLastError();
          debugf("\nCPigEngine::ScriptDirMonitor(): "
            "FindNextChangeNotification Failed : "
            "GetLastError() = 0x%08X, m_hDirChange = 0x%08X\n",
            dwLastError, m_hDirChange);
        #endif // _DEBUG
        Sleep(1000);
      }
    }
    else // (e_Msg == dwWait)
    {
      MSG msg;
      while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
      {
        if (WM_TIMER == msg.message)
        {
          assert(msg.wParam == idTimer);

          // Kill the timer
          KillTimer(NULL, idTimer);
          idTimer = 0;

          // Process the files in the directory
          ProcessScriptDirChanges();
        }
        else if (WM_QUIT == msg.message)
        {
          dwWait = e_Exit;
          break;
        }
      }
    }

    // Continue waiting
    dwWait = MsgWaitForMultipleObjects(cObjs, hObjs, false, INFINITE,
      QS_ALLINPUT);
  }

  // Remove this thread from the MTA
  CoUninitialize();

  // Clear the thread pointer
  InterlockedExchange((long*)&m_pth, 0);
}
void CPagePlayers::PopulatePlayersList()
{
  CWaitCursor wait;
  LPCSTR pszContext = "retrieving collection of players in game";

  // Clear the contents of the list
  m_listPlayers.DeleteAllItems();

  // Do nothing else if there is no game in progress
  if (NULL == GetSheet()->GetGame())
    return;

  // Get the collection of users in the game
  IAdminUsersPtr spUsers;
  HRESULT hr = GetSheet()->GetGame()->get_Users(&spUsers);
  if (FAILED(hr))
  {
    GetSheet()->HandleError(hr, pszContext, true);
    return;
  }

  // Get the enumerator object from the collection
  IUnknownPtr spEnumUnk;
  if (FAILED(hr = spUsers->get__NewEnum(&spEnumUnk)))
  {
    GetSheet()->HandleError(hr, pszContext, true);
    return;
  }
  IEnumVARIANTPtr spEnum(spEnumUnk);
  if (NULL == spEnum)
  {
    GetSheet()->HandleError(E_NOINTERFACE, pszContext, true);
    return;
  }

  // Iterate through each player from the enumerator
  int iIndex = 0;
  CComVariant players[32];
  do
  {
    // Fetch the next block of players from the enumerator
    ULONG cFetched;
    if (FAILED(hr = spEnum->Next(sizeofArray(players), players, &cFetched)))
    {
      GetSheet()->HandleError(hr, pszContext, true);
      return;
    }

    // Add each player to the list
    for (ULONG i = 0; i < cFetched; ++i)
    {
      // Convert the VARIANT to IDispatch, if not already
      VARTYPE vt = V_VT(&players[i]);
      if (VT_DISPATCH != vt && VT_UNKNOWN != vt)
      {
        GetSheet()->HandleError(DISP_E_TYPEMISMATCH, pszContext, true);
        return;
      }

      // Ensure that the IDispatch supports IAdminUser
      IAdminUserPtr spUser(V_DISPATCH(&players[i]));
      if (NULL == spUser)
      {
        GetSheet()->HandleError(E_NOINTERFACE, pszContext, true);
        return;
      }

      // Clear the VARIANT in the array
      players[i].Clear();

      // Get the ship object of the user
      IAdminShipPtr spShip;
      if (FAILED(hr = spUser->get_Ship(&spShip)))
      {
        GetSheet()->HandleError(hr, pszContext, true);
        return;
      }

      // Get the interesting properties of the User
      CComBSTR bstrName, bstrTeam, bstrSector;
      // Model Name
      spShip->get_Name(&bstrName);
      // Team
      IAGCTeamPtr spTeam;
      spShip->get_Team(&spTeam);
      if (NULL != spTeam)
        spTeam->get_Name(&bstrTeam);
      // Sector
      IAGCSectorPtr spSector;
      spShip->get_Sector(&spSector);
      if (NULL != spSector)
        spSector->get_Name(&bstrSector);

      // Add the ship to the list
      USES_CONVERSION;
      m_listPlayers.InsertItem(iIndex, OLE2CT(bstrName));
      m_listPlayers.SetItemText(iIndex, c_iColumnTeam, OLE2CT(bstrTeam));
      m_listPlayers.SetItemText(iIndex, c_iColumnSector, OLE2CT(bstrSector));
      m_listPlayers.SetItemData(iIndex, reinterpret_cast<DWORD>(spShip.Detach()));
      ++iIndex;
    }

  } while (S_FALSE != hr);

}