/*
 * ADO.NET lets you create a database connection to SqlServer using
 * either a SQL login or do a Windows login with the credentials your 
 * program is running under. What if you want to impersonate another
 * Windows user?
 * 
 * Given that you have the users' password and appropirate privledges and some effort,
 * at runtime you can slip another users credentials into and ADO.NET connection.
 * 
 * ...Or you can let SMO (Sql Server Managemement objects) to that work for you.
 * 
 * The ServerConnection object from the Microsoft.SqlServer.Management.Common
 * namespace lets you choose how to make your connection. A SeverConnection 
 * will login to SQL Server with Windows credential if you set the ConnectAsUser
 * property to true.
 * 
 * An ADO.NET SqlCommand cannot use a ServerConnection directly, but 
 * ServerConnection does have a property named SqlConnectionObject that
 * returns a SqlConnection.
 * 
 * Below is some sample code that shows using a ServerConnection to execute
 * an ADO.NET SqlCommand with the Windows identity of MiniDan.
 * 
 * Of course this code is doing no error checking and glosses over some of 
 * the differences between a ServerConnection and a SqlConnection that is
 * constructed directly.
 * 
 * To use this example you will have to add a reference to 
 * Microsoft.SqlServer.ConnectionInfo.
*/

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
namespace AutoConnect
{
    class Program
    {
        static void Main(string[] args)
        {
            ServerConnection serverConnection = new ServerConnection();
            SqlCommand cmd =
                new SqlCommand("SELECT SUSER_NAME()", 
                serverConnection.SqlConnectionObject);
            serverConnection.ServerInstance = "CANOPUS5";
            serverConnection.ConnectAsUser = true;
            serverConnection.LoginSecure = true;
            serverConnection.ConnectAsUserName = @"MiniDan";
            serverConnection.ConnectAsUserPassword = "P@ssw0rd";
            serverConnection.Connect();
            Console.WriteLine(cmd.ExecuteScalar());
        }

    }
}
 