#region Using directives

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

#endregion

namespace ChangePassword1
{
    class Program
    {
        static void Main(string[] args)
        {
          using (SqlConnection conn = new SqlConnection("uid=fred;pwd=foo1234;server=.;database=pubs"))
          {
                int tries = 0;
                while (tries < 2 && conn.State == ConnectionState.Closed)
                {
                    try
                    {
                        conn.Open();
                    }
                    catch (SqlException ex)
                    {
                        // 18487 = password expired
                        // 18488 = must change password on first login
                        if ((ex.Number == 18487) || (ex.Number == 18488))
                        {
                            // prompt user for password
                            // user answers "newpass"
                            // change password takes 2 parms;
                            //  1. enough of a connection string to connect to server
                            //  2. new password (only)
                          SqlConnection.ChangePassword("uid=fred;pwd=foo1234;server=.", "newpass0000");
                          // change password in connection string
                          conn.ConnectionString = "uid=fred;pwd=newpass0000;server=.;database=pubs";
                        }
                        else
                        {
                            Console.WriteLine(ex.Message);
                            if (ex.InnerException != null)
                                Console.WriteLine(ex.InnerException.Message);
                        }
                    }
                }
            }
        }
    }
}
