void IDisposable.Dispose()
        {
            if (!_disposed)
            {
                _disposed = true;

                if (this != _current)
                {
                    throw new InvalidOperationException("Disposed out of order.");
                }

                try
                {
                    // attempt to terminate the session
                    TerminateSession();
                }
                finally
                {
                    // even if it fails, we are still disposing of this scope, so we set the head
                    // to point to the parent and revert the Thread.CurrentPrincipal
                    _current = _parent;
                    Thread.CurrentPrincipal = _previousPrincipal;
                }
            }
        }
        /// <summary>
        /// Creates a new user session based on specified credentials, and constructs an instance of this
        /// class for that user session.
        /// </summary>
        /// <remarks>
        /// The user session is terminated when this instance is disposed.
        /// </remarks>
        /// <param name="userName"></param>
        /// <param name="application"></param>
        /// <param name="hostName"></param>
        /// <param name="password"></param>
        public AuthenticationScope(string userName, string application, string hostName, string password)
        {
            _userName    = userName;
            _application = application;
            _hostName    = hostName;

            _principal = InitiateSession(password);

            // if the session was successfully initiated (no exception thrown), then
            // set the thread principal and establish this as the current scope
            _previousPrincipal      = Thread.CurrentPrincipal;
            Thread.CurrentPrincipal = _principal;
            _parent  = _current;
            _current = this;
        }