Listing 6: The EnsureSession() method.

HRESULT CUltraMaxService::EnsureSession()
{
    // Check session ID in SOAP header
    if ( CString(m_Header.m_SessionID) != "" )
    {
        // Session cookie found: get current session
        if ( FAILED(m_spSessionSvc->GetSession(
                CString(m_Header.m_SessionID), &m_spSession)) )
            return E_FAIL;
       // Make sure that session has not yet expired
        if ( m_spSession->IsExpired() == S_OK )
            return E_FAIL;
    }
    else
    {
        // No session cookie: create a new session
        const size_t nCharacters = 64;
        CHAR szID[nCharacters + 1] = "\0";
        DWORD dwCharacters = nCharacters;
        if ( FAILED(m_spSessionSvc->CreateNewSession(szID, &dwCharacters,
                &m_spSession)) )
            return E_FAIL;
        // Store session ID in SOAP header
        m_Header.m_SessionID = CComBSTR(szID).Detach();
    }
    return S_OK;
}