/// <summary>
        /// Constructs the session for the given user and transaction to the
        /// given database.
        /// </summary>
        /// <param name="transaction">A transaction that handles the commands issued by
        /// the user during the session.</param>
        /// <param name="userName"></param>
        /// <seealso cref="ITransaction"/>
        public Session(ITransaction transaction, string userName)
            : base(transaction as IEventSource)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException("transaction");
            }

            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException("userName");
            }

            if (String.Equals(userName, User.SystemName, StringComparison.OrdinalIgnoreCase) ||
                String.Equals(userName, User.PublicName, StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException(String.Format("Cannot open a session for user '{0}'.", userName));
            }

            Transaction = transaction;
            Context     = transaction.Context.CreateSessionContext();
            Context.RegisterInstance(this);

            Transaction.Context.Route <QueryEvent>(OnQueryCommand);

            Transaction.GetTableManager().AddInternalTables(new SessionTableContainer(this));

            access = new SessionAccess(this);

            if (!transaction.Database.Sessions.Add(this))
            {
                throw new InvalidOperationException("The session was already in the database session list");
            }

            User      = new User(this, userName);
            startedOn = DateTimeOffset.UtcNow;

            this.OnEvent(new SessionEvent(SessionEventType.Begin));
        }
        private void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    try {
                        Rollback();
                    } catch (Exception ex) {
                        this.OnError(new Exception("Error while rolling back on Dispose", ex));
                    } finally {
                        if (Context != null)
                        {
                            Context.Dispose();
                        }
                    }
                }

                Context  = null;
                access   = null;
                disposed = true;
            }
        }