Questo articolo è stato tradotto automaticamente. Per visualizzare l'articolo in inglese, selezionare la casella di controllo Inglese. È possibile anche visualizzare il testo inglese in una finestra popup posizionando il puntatore del mouse sopra il testo.
Traduzione
Inglese

Metodo SqlConnection.ChangePassword (String, String)

 

Data di pubblicazione: ottobre 2016

Sostituisce la password SQL Server dell'utente indicato nella stringa di connessione con la nuova password fornita.

Spazio dei nomi:   System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)

public static void ChangePassword(
	string connectionString,
	string newPassword
)

Parametri

connectionString
Type: System.String

Stringa di connessione contenente informazioni sufficienti per connettersi al server desiderato. La stringa di connessione deve contenere l'ID utente e la password corrente.

newPassword
Type: System.String

Nuova password da impostare. Questa password deve essere conforme ai relativi criteri di sicurezza impostati sul server, inclusa la lunghezza minima, l'obbligo di usare determinati caratteri e così via.

Exception Condition
ArgumentException

La stringa di connessione include l'opzione per usare la sicurezza integrata.

Oppure

newPassword supera i 128 caratteri.

ArgumentNullException

Il parametro connectionString o newPassword è Null.

When you are using ssNoVersion on Windows Server, developers can take advantage of functionality that lets the client application supply both the current and a new password in order to change the existing password. Applications can implement functionality such as prompting the user for a new password during initial login if the old one has expired, and this operation can be completed without administrator intervention.

The M:System.Data.SqlClient.SqlConnection.ChangePassword(System.String,System.String) method changes the ssNoVersion password for the user indicated in the supplied connectionString parameter to the value supplied in the newPassword parameter. If the connection string includes the option for integrated security (that is, "Integrated Security=True" or the equivalent), an exception is thrown.

To determine that the password has expired, calling the M:System.Data.SqlClient.SqlConnection.Open method raises a T:System.Data.SqlClient.SqlException. In order to indicate that the password that is contained within the connection string must be reset, the P:System.Data.SqlClient.SqlException.Number property for the exception contains the status value 18487 or 18488. The first value (18487) indicates that the password has expired and the second (18488) indicates that the password must be reset before logging in.

This method opens its own connection to the server, requests the password change, and closes the connection as soon as it has completed. This connection is not retrieved from, nor returned to, the ssNoVersion connection pool.

The following is a simple example of changing a password:

class Program {
   static void Main(string[] args) {
      System.Data.SqlClient.SqlConnection.ChangePassword(
        "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", 
       "new_password");
   }
}

Module Module1
    Sub Main()
System.Data.SqlClient.SqlConnection.ChangePassword(
        "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", 
       "new_password")
    End Sub
End Module

The following console application demonstrates the issues involved in changing a user's password because the current password has expired.

using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        try
        {
            DemonstrateChangePassword();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        Console.WriteLine("Press ENTER to continue...");
        Console.ReadLine();
    }

    private static void DemonstrateChangePassword()
    {
        // Retrieve the connection string. In a production application,
        // this string should not be contained within the source code.
        string connectionString = GetConnectionString();

        using (SqlConnection cnn = new SqlConnection())
        {
            for (int i = 0; i <= 1; i++)
            {
                // Run this loop at most two times. If the first attempt fails, 
                // the code checks the Number property of the SqlException object.
                // If that contains the special values 18487 or 18488, the code 
                // attempts to set the user's password to a new value. 
                // Assuming this succeeds, the second pass through 
                // successfully opens the connection.
                // If not, the exception handler catches the exception.
                try
                {
                    cnn.ConnectionString = connectionString;
                    cnn.Open();
                    // Once this succeeds, just get out of the loop.
                    // No need to try again if the connection is already open.
                    break;
                }
                catch (SqlException ex)
                {
                    if (i == 0 && ((ex.Number == 18487) || (ex.Number == 18488)))
                    {
                        // You must reset the password. 
                        connectionString =
                            ModifyConnectionString(connectionString, 
                            GetNewPassword());

                    }
                    else
                        // Bubble all other SqlException occurrences
                        // back up to the caller.
                        throw;
                }
            }
            SqlCommand cmd = new SqlCommand(
                "SELECT ProductID, Name FROM Product", cnn);
            // Use the connection and command here...
        }
    }

    private static string ModifyConnectionString(
        string connectionString, string NewPassword)
    {

        // Use the SqlConnectionStringBuilder class to modify the
        // password portion of the connection string. 
        SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder(connectionString);
        builder.Password = NewPassword;
        return builder.ConnectionString;
    }

    private static string GetNewPassword()
    {
        // In a real application, you might display a modal
        // dialog box to retrieve the new password. The concepts
        // are the same as for this simple console application, however.
        Console.Write("Your password must be reset. Enter a new password: ");
        return Console.ReadLine();
    }

    private static string GetConnectionString()
    {
        // For this demonstration, the connection string must
        // contain both user and password information. In your own
        // application, you might want to retrieve this setting
        // from a config file, or from some other source.

        // In a production application, you would want to 
        // display a modal form that could gather user and password
        // information.
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(
            "Data Source=(local);Initial Catalog=AdventureWorks");

        Console.Write("Enter your user id: ");
        builder.UserID = Console.ReadLine();
        Console.Write("Enter your password: ");
        builder.Password = Console.ReadLine();

        return builder.ConnectionString;
    }
}

.NET Framework
Disponibile da 2.0
Torna all'inizio
Mostra: