diff --git a/snippets/csharp/VS_Snippets_WebNet/FormsAuthenticationHashPassword/CS/formsauthenticationhashpasswordcs.aspx b/snippets/csharp/VS_Snippets_WebNet/FormsAuthenticationHashPassword/CS/formsauthenticationhashpasswordcs.aspx deleted file mode 100644 index 4300c638b19..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/FormsAuthenticationHashPassword/CS/formsauthenticationhashpasswordcs.aspx +++ /dev/null @@ -1,103 +0,0 @@ - -<%@ Page Language="C#" %> - - - - ASP.NET Example - - - - -
-

This form displays the results of the FormsAuthentication.HashPasswordForStoringInConfigFile - method.
The user name and hashed password can be stored in a <credentials> node - in the Web.config file.

- - - - - - - - - - - - - - - - - - - - - - - - - -
New User Name:
Password:
Repeat Password: -
Hash function: - - -
-    - -
- -
-
- - - \ No newline at end of file diff --git a/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs b/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs deleted file mode 100644 index 1fdfdb20528..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs +++ /dev/null @@ -1,128 +0,0 @@ -// -using System; -using System.Web.Management; - -namespace UsingSQLServices -{ - class UsingSqlServices - { - static void Main(string[] args) - { - try - { -// Values to use. -string server = "ASPFeatureServer"; -string database = "ASPFeatureDB"; -string connectionString = - "server=ASPFeatureServer, pooling=False, user=, password="; -string user = "AspAdmin"; -string password = "Secure Password"; // Use a sicure password. - -// -// Install membership and personalization. -SqlServices.Install(database, - SqlFeatures.Membership & - SqlFeatures.Personalization, - connectionString); -// - -// -// Remove membership and personalization. -SqlServices.Uninstall(database, - SqlFeatures.Membership & - SqlFeatures.Personalization, - connectionString); -// - -// -// Install all features. -SqlServices.Install(server, database, - SqlFeatures.All); -// - -// -// Remove all features. -SqlServices.Uninstall(server, database, - SqlFeatures.All); -// - -// -// Install a custom session state database. -SqlServices.InstallSessionState(database, - SessionStateType.Custom, - connectionString); -// - -// -// Remove a custom session state database. -SqlServices.UninstallSessionState(database, - SessionStateType.Custom, - connectionString); -// - -// -// Install temporary session state. -SqlServices.InstallSessionState(server, null, - SessionStateType.Temporary); -// - -// -// Remove temporary session state. -SqlServices.UninstallSessionState(server, null, - SessionStateType.Temporary); -// - -// -// Install persisted session state. -SqlServices.InstallSessionState(server, user, password, - null, SessionStateType.Persisted); -// - -// -// Remove persisted session state. -SqlServices.UninstallSessionState(server, user, password, - null, SessionStateType.Persisted); -// - } - catch (SqlExecutionException sqlExecutionException) - { -// -Console.WriteLine( - "An SQL execution exception occurred."); -Console.WriteLine(); -// -Console.WriteLine(" Message: {0}", - sqlExecutionException.Message); -// -// -Console.WriteLine(" Server: {0}", - sqlExecutionException.Server); -// -// -Console.WriteLine(" Database: {0}", - sqlExecutionException.Database); -// -// -Console.WriteLine(" Commands: {0}", - sqlExecutionException.Commands); -// -// -Console.WriteLine(" SqlFile: {0}", - sqlExecutionException.SqlFile); -// -// -Console.WriteLine(" Inner Exception: {0}", - sqlExecutionException.Exception); -// -// - } - catch (Exception ex) - { -Console.WriteLine("An unknown exception occurred."); -Console.WriteLine(); -Console.WriteLine(" Message: {0}", ex.Message); - } - } - } -} -// diff --git a/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovider.cs b/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovider.cs deleted file mode 100644 index 7ecd2ac4bba..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovider.cs +++ /dev/null @@ -1,1500 +0,0 @@ -using System.Web.Security; -using System.Configuration.Provider; -using System.Collections.Specialized; -using System; -using System.Data; -using System.Data.Odbc; -using System.Configuration; -using System.Diagnostics; -using System.Web; -using System.Globalization; -using System.Web.Configuration; -using System.Security.Cryptography; -using System.Text; - -/* - -This provider works with the following schema for the table of user data. - -CREATE TABLE Users -( - PKID Guid NOT NULL PRIMARY KEY, - Username Text (255) NOT NULL, - ApplicationName Text (255) NOT NULL, - Email Text (128) NOT NULL, - Comment Text (255), - Password Text (128) NOT NULL, - PasswordQuestion Text (255), - PasswordAnswer Text (255), - IsApproved YesNo, - LastActivityDate DateTime, - LastLoginDate DateTime, - LastPasswordChangedDate DateTime, - CreationDate DateTime, - IsOnLine YesNo, - IsLockedOut YesNo, - LastLockedOutDate DateTime, - FailedPasswordAttemptCount Integer, - FailedPasswordAttemptWindowStart DateTime, - FailedPasswordAnswerAttemptCount Integer, - FailedPasswordAnswerAttemptWindowStart DateTime -) - -*/ - -namespace Samples.AspNet.Membership -{ - - public sealed class OdbcMembershipProvider : MembershipProvider - { - - // - // Global generated password length, generic exception message, event log info. - // - - private int newPasswordLength = 8; - - // - // Used when determining encryption key values. - // - - private MachineKeySection machineKey; - - // - // Database connection string. - // - - private ConnectionStringSettings pConnectionStringSettings; - - public string ConnectionString - { - get { return pConnectionStringSettings.ConnectionString; } - } - - // - // System.Configuration.Provider.ProviderBase.Initialize Method - // - - public override void Initialize(string name, NameValueCollection config) - { - // - // Initialize values from web.config. - // - - if (config == null) - throw new ArgumentNullException("config"); - - if (name == null || name.Length == 0) - name = "OdbcMembershipProvider"; - - if (String.IsNullOrEmpty(config["description"])) - { - config.Remove("description"); - config.Add("description", "Sample ODBC Membership provider"); - } - - // Initialize the abstract base class. - base.Initialize(name, config); - - pApplicationName = GetConfigValue(config["applicationName"], - System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); - pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); - pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); - pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); - pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); - pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); - pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); - pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); - pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); - pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); - - string temp_format = config["passwordFormat"]; - temp_format ??= "Hashed"; - - switch (temp_format) - { - case "Hashed": - pPasswordFormat = MembershipPasswordFormat.Hashed; - break; - case "Encrypted": - pPasswordFormat = MembershipPasswordFormat.Encrypted; - break; - case "Clear": - pPasswordFormat = MembershipPasswordFormat.Clear; - break; - default: - throw new ProviderException("Password format not supported."); - } - - // - // Initialize OdbcConnection. - // - - pConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; - - if (pConnectionStringSettings == null || pConnectionStringSettings.ConnectionString.Trim() == "") - { - throw new ProviderException("Connection string cannot be blank."); - } - - // Get encryption and decryption key information from the configuration. - Configuration cfg = - WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); - machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); - } - - // - // A helper function to retrieve config values from the configuration file. - // - - private string GetConfigValue(string configValue, string defaultValue) - { - if (configValue == null || configValue.Trim() == "") - return defaultValue; - - return configValue; - } - - // - // System.Web.Security.MembershipProvider properties. - // - - private bool pRequiresUniqueEmail; - - public override bool RequiresUniqueEmail - { - get { return pRequiresUniqueEmail; } - } - - private int pMaxInvalidPasswordAttempts; - - public override int MaxInvalidPasswordAttempts - { - get { return pMaxInvalidPasswordAttempts; } - } - - private int pPasswordAttemptWindow; - - public override int PasswordAttemptWindow - { - get { return pPasswordAttemptWindow; } - } - - private MembershipPasswordFormat pPasswordFormat; - - public override MembershipPasswordFormat PasswordFormat - { - get { return pPasswordFormat; } - } - - private int pMinRequiredNonAlphanumericCharacters; - - public override int MinRequiredNonAlphanumericCharacters - { - get { return pMinRequiredNonAlphanumericCharacters; } - } - - private int pMinRequiredPasswordLength; - - public override int MinRequiredPasswordLength - { - get { return pMinRequiredPasswordLength; } - } - - private string pPasswordStrengthRegularExpression; - - public override string PasswordStrengthRegularExpression - { - get { return pPasswordStrengthRegularExpression; } - } - - // - private string pApplicationName; - - public override string ApplicationName - { - get { return pApplicationName; } - set { pApplicationName = value; } - } - // - - // - private bool pEnablePasswordReset; - - public override bool EnablePasswordReset - { - get { return pEnablePasswordReset; } - } - // - - // - private bool pEnablePasswordRetrieval; - - public override bool EnablePasswordRetrieval - { - get { return pEnablePasswordRetrieval; } - } - // - - // - private bool pRequiresQuestionAndAnswer; - - public override bool RequiresQuestionAndAnswer - { - get { return pRequiresQuestionAndAnswer; } - } - // - - // - // System.Web.Security.MembershipProvider methods. - // - - // - // MembershipProvider.ChangePassword - // - - // - public override bool ChangePassword(string username, string oldPwd, string newPwd) - { - if (!ValidateUser(username, oldPwd)) - { - return false; - } - - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, newPwd, true); - - OnValidatingPassword(args); - - if (args.Cancel) - if (args.FailureInformation != null) - throw args.FailureInformation; - else - throw new MembershipPasswordException("Change password canceled due to new password validation failure."); - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET Password = ?, LastPasswordChangedDate = ? " + - " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = EncodePassword(newPwd); - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@OldPassword", OdbcType.VarChar, 128).Value = oldPwd; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; - } - // - - // - // MembershipProvider.ChangePasswordQuestionAndAnswer - // - - // - public override bool ChangePasswordQuestionAndAnswer(string username, - string password, - string newPwdQuestion, - string newPwdAnswer) - { - if (!ValidateUser(username, password)) - { - return false; - } - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET PasswordQuestion = ?, PasswordAnswer = ?" + - " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Question", OdbcType.VarChar, 255).Value = newPwdQuestion; - cmd.Parameters.Add("@Answer", OdbcType.VarChar, 255).Value = EncodePassword(newPwdAnswer); - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = password; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; - } - // - - // - // MembershipProvider.CreateUser - // - - // - public override MembershipUser CreateUser(string username, - string password, - string email, - string passwordQuestion, - string passwordAnswer, - bool isApproved, - object providerUserKey, - out MembershipCreateStatus status) - { - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, password, true); - - OnValidatingPassword(args); - - if (args.Cancel) - { - status = MembershipCreateStatus.InvalidPassword; - return null; - } - - if (RequiresUniqueEmail && GetUserNameByEmail(email) != "") - { - status = MembershipCreateStatus.DuplicateEmail; - return null; - } - - MembershipUser u = GetUser(username, false); - - if (u == null) - { - DateTime createDate = DateTime.Now; - - if (providerUserKey == null) - { - providerUserKey = Guid.NewGuid(); - } - else - { - if (!(providerUserKey is Guid)) - { - status = MembershipCreateStatus.InvalidProviderUserKey; - return null; - } - } - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("INSERT INTO Users " + - " (PKID, Username, Password, Email, PasswordQuestion, " + - " PasswordAnswer, IsApproved," + - " Comment, CreationDate, LastPasswordChangedDate, LastActivityDate," + - " ApplicationName, IsLockedOut, LastLockedOutDate," + - " FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, " + - " FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart)" + - " Values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", conn); - - cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(password); - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email; - cmd.Parameters.Add("@PasswordQuestion", OdbcType.VarChar, 255).Value = passwordQuestion; - cmd.Parameters.Add("@PasswordAnswer", OdbcType.VarChar, 255).Value = EncodePassword(passwordAnswer); - cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = isApproved; - cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = ""; - cmd.Parameters.Add("@CreationDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = false; - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@FailedPasswordAttemptCount", OdbcType.Int).Value = 0; - cmd.Parameters.Add("@FailedPasswordAttemptWindowStart", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@FailedPasswordAnswerAttemptCount", OdbcType.Int).Value = 0; - cmd.Parameters.Add("@FailedPasswordAnswerAttemptWindowStart", OdbcType.DateTime).Value = createDate; - - try - { - conn.Open(); - - int recAdded = cmd.ExecuteNonQuery(); - - if (recAdded > 0) - { - status = MembershipCreateStatus.Success; - } - else - { - status = MembershipCreateStatus.UserRejected; - } - } - catch (OdbcException) - { - // Handle exception. - - status = MembershipCreateStatus.ProviderError; - } - finally - { - conn.Close(); - } - - return GetUser(username, false); - } - else - { - status = MembershipCreateStatus.DuplicateUserName; - } - - return null; - } - // - - // - // MembershipProvider.DeleteUser - // - - // - public override bool DeleteUser(string username, bool deleteAllRelatedData) - { - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("DELETE FROM Users " + - " WHERE Username = ? AND Applicationname = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - - if (deleteAllRelatedData) - { - // Process commands to delete all data for the user in the database. - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; - } - // - - // - // MembershipProvider.GetAllUsers - // - - public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE ApplicationName = ?", conn); - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return users; - } - - // - // MembershipProvider.GetNumberOfUsersOnline - // - - // - public override int GetNumberOfUsersOnline() - { - - TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0); - DateTime compareTime = DateTime.Now.Subtract(onlineSpan); - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - " WHERE LastActivityDate > ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@CompareDate", OdbcType.DateTime).Value = compareTime; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int numOnline = 0; - - try - { - conn.Open(); - - numOnline = (int)cmd.ExecuteScalar(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - return numOnline; - } - // - - // - // MembershipProvider.GetPassword - // - - // - public override string GetPassword(string username, string answer) - { - if (!EnablePasswordRetrieval) - { - throw new ProviderException("Password Retrieval Not Enabled."); - } - - if (PasswordFormat == MembershipPasswordFormat.Hashed) - { - throw new ProviderException("Cannot retrieve Hashed passwords."); - } - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Password, PasswordAnswer, IsLockedOut FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - string password = ""; - string passwordAnswer = ""; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - - if (reader.GetBoolean(2)) - throw new MembershipPasswordException("The supplied user is locked out."); - - password = reader.GetString(0); - passwordAnswer = reader.GetString(1); - } - else - { - throw new MembershipPasswordException("The supplied user name is not found."); - } - } - catch (OdbcException) - { - // Handle exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer)) - { - UpdateFailureCount(username, "passwordAnswer"); - - throw new MembershipPasswordException("Incorrect password answer."); - } - - if (PasswordFormat == MembershipPasswordFormat.Encrypted) - { - password = UnEncodePassword(password); - } - - return password; - } - // - - // - // MembershipProvider.GetUser - // - - // - public override MembershipUser GetUser(string username, bool userIsOnline) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," + - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" + - " FROM Users WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - MembershipUser u = null; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(); - - if (reader.HasRows) - { - reader.Read(); - u = GetUserFromReader(reader); - - if (userIsOnline) - { - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " + - "SET LastActivityDate = ? " + - "WHERE Username = ? AND Applicationname = ?", conn); - - updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - updateCmd.ExecuteNonQuery(); - } - } - } - catch (OdbcException) - { - // Handle exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return u; - } - - // - // GetUserFromReader - // A helper function that takes the current row from the OdbcDataReader - // and populates a MembershipUser object with the values. Called by the - // MembershipUser.GetUser implementation. - // - - public MembershipUser GetUserFromReader(OdbcDataReader reader) - { - object providerUserKey = reader.GetValue(0); - string username = reader.GetString(1); - string email = reader.GetString(2); - - string passwordQuestion = ""; - if (reader.GetValue(3) != DBNull.Value) - passwordQuestion = reader.GetString(3); - - string comment = ""; - if (reader.GetValue(4) != DBNull.Value) - comment = reader.GetString(4); - - bool isApproved = reader.GetBoolean(5); - bool isLockedOut = reader.GetBoolean(6); - DateTime creationDate = reader.GetDateTime(7); - - DateTime lastLoginDate = new DateTime(); - if (reader.GetValue(8) != DBNull.Value) - lastLoginDate = reader.GetDateTime(8); - - DateTime lastActivityDate = reader.GetDateTime(9); - DateTime lastPasswordChangedDate = reader.GetDateTime(10); - - DateTime lastLockedOutDate = new DateTime(); - if (reader.GetValue(11) != DBNull.Value) - lastLockedOutDate = reader.GetDateTime(11); - - MembershipUser u = new MembershipUser(this.Name, - username, - providerUserKey, - email, - passwordQuestion, - comment, - isApproved, - isLockedOut, - creationDate, - lastLoginDate, - lastActivityDate, - lastPasswordChangedDate, - lastLockedOutDate); - - return u; - } - // - - // - // MembershipProvider.GetUserNameByEmail - // - - // - public override string GetUserNameByEmail(string email) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Username" + - " FROM Users WHERE Email = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - string username = ""; - - try - { - conn.Open(); - - username = (string)cmd.ExecuteScalar(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - return username; - } - // - - // - // MembershipProvider.ResetPassword - // - - // - public override string ResetPassword(string username, string answer) - { - if (!EnablePasswordReset) - { - throw new NotSupportedException("Password reset is not enabled."); - } - - if (answer == null && RequiresQuestionAndAnswer) - { - UpdateFailureCount(username, "passwordAnswer"); - - throw new ProviderException("Password answer required for password reset."); - } - - string newPassword = - System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters); - - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, newPassword, true); - - OnValidatingPassword(args); - - if (args.Cancel) - if (args.FailureInformation != null) - throw args.FailureInformation; - else - throw new MembershipPasswordException("Reset password canceled due to password validation failure."); - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT PasswordAnswer, IsLockedOut FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - int rowsAffected = 0; - string passwordAnswer = ""; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - - if (reader.GetBoolean(1)) - throw new MembershipPasswordException("The supplied user is locked out."); - - passwordAnswer = reader.GetString(0); - } - else - { - throw new MembershipPasswordException("The supplied user name is not found."); - } - - if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer)) - { - UpdateFailureCount(username, "passwordAnswer"); - - throw new MembershipPasswordException("Incorrect password answer."); - } - - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " + - " SET Password = ?, LastPasswordChangedDate = ?" + - " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn); - - updateCmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(newPassword); - updateCmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - rowsAffected = updateCmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - if (rowsAffected > 0) - { - return newPassword; - } - else - { - throw new MembershipPasswordException("User not found, or user is locked out. Password not Reset."); - } - } - // - - // - // MembershipProvider.UpdateUser - // - - // - public override void UpdateUser(MembershipUser user) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET Email = ?, Comment = ?," + - " IsApproved = ?" + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = user.Email; - cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = user.Comment; - cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = user.IsApproved; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = user.UserName; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - try - { - conn.Open(); - - cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - } - // - - // - // MembershipProvider.ValidateUser - // - - // - public override bool ValidateUser(string username, string password) - { - bool isValid = false; - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Password, IsApproved FROM Users " + - " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - OdbcDataReader reader = null; - bool isApproved = false; - string pwd = ""; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - pwd = reader.GetString(0); - isApproved = reader.GetBoolean(1); - } - else - { - return false; - } - - if (isApproved && (password == pwd)) - { - isValid = true; - - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users SET LastLoginDate = ?" + - " WHERE Username = ? AND ApplicationName = ?", conn); - - updateCmd.Parameters.Add("@LastLoginDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - updateCmd.ExecuteNonQuery(); - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return isValid; - } - // - - public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE Username LIKE ? AND ApplicationName = ?", conn); - cmd.Parameters.Add("@UsernameSearch", OdbcType.VarChar, 255).Value = usernameToMatch; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE Username LIKE ? AND ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return users; - } - - public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE Email LIKE ? AND ApplicationName = ?", conn); - cmd.Parameters.Add("@EmailSearch", OdbcType.VarChar, 255).Value = emailToMatch; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE Email LIKE ? AND ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return users; - } - - // - // MembershipProvider.UnlockUser - // - - public override bool UnlockUser(string username) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET IsLockedOut = False, LastLockedOutDate = ? " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - return true; - - return false; - } - - // - // MembershipProvider.GetUser(object, bool) - // - - public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," + - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" + - " FROM Users WHERE PKID = ?", conn); - - cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - - MembershipUser u = null; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(); - - if (reader.HasRows) - { - reader.Read(); - u = GetUserFromReader(reader); - - if (userIsOnline) - { - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " + - "SET LastActivityDate = ? " + - "WHERE PKID = ?", conn); - - updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - - updateCmd.ExecuteNonQuery(); - } - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return u; - } - - // - // UpdateFailureCount - // A helper method that performs the checks and updates associated with - // password failure tracking. - // - - private void UpdateFailureCount(string username, string failureType) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT FailedPasswordAttemptCount, " + - " FailedPasswordAttemptWindowStart, " + - " FailedPasswordAnswerAttemptCount, " + - " FailedPasswordAnswerAttemptWindowStart " + - " FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - OdbcDataReader reader = null; - DateTime windowStart = new DateTime(); - int failureCount = 0; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - - if (failureType == "password") - { - failureCount = reader.GetInt32(0); - windowStart = reader.GetDateTime(1); - } - - if (failureType == "passwordAnswer") - { - failureCount = reader.GetInt32(2); - windowStart = reader.GetDateTime(3); - } - } - - reader.Close(); - - DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow); - - if (failureCount == 0 || DateTime.Now > windowEnd) - { - // First password failure or outside of PasswordAttemptWindow. - // Start a new password failure count from 1 and a new window starting now. - - if (failureType == "password") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAttemptCount = ?, " + - " FailedPasswordAttemptWindowStart = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - if (failureType == "passwordAnswer") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAnswerAttemptCount = ?, " + - " FailedPasswordAnswerAttemptWindowStart = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@Count", OdbcType.Int).Value = 1; - cmd.Parameters.Add("@WindowStart", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new ProviderException("Unable to update failure count and window start."); - } - else - { - if (failureCount++ >= MaxInvalidPasswordAttempts) - { - // Password attempts have exceeded the failure threshold. Lock out - // the user. - - cmd.CommandText = "UPDATE Users " + - " SET IsLockedOut = ?, LastLockedOutDate = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = true; - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new ProviderException("Unable to lock out user."); - } - else - { - // Password attempts have not exceeded the failure threshold. Update - // the failure counts. Leave the window the same. - - if (failureType == "password") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAttemptCount = ?" + - " WHERE Username = ? AND ApplicationName = ?"; - - if (failureType == "passwordAnswer") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAnswerAttemptCount = ?" + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@Count", OdbcType.Int).Value = failureCount; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new ProviderException("Unable to update failure count."); - } - } - } - catch (OdbcException) - { - // Handle Exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - } - - // - // CheckPassword - // Compares password values based on the MembershipPasswordFormat. - // - - private bool CheckPassword(string password, string dbpassword) - { - string pass1 = password; - string pass2 = dbpassword; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Encrypted: - pass2 = UnEncodePassword(dbpassword); - break; - case MembershipPasswordFormat.Hashed: - pass1 = EncodePassword(password); - break; - default: - break; - } - - if (pass1 == pass2) - { - return true; - } - - return false; - } - - // - // EncodePassword - // Encrypts, Hashes, or leaves the password clear based on the PasswordFormat. - // - - private string EncodePassword(string password) - { - string encodedPassword = password; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Clear: - break; - case MembershipPasswordFormat.Encrypted: - encodedPassword = - Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); - break; - case MembershipPasswordFormat.Hashed: - HMACSHA256 hash = new HMACSHA256(); - hash.Key = HexToByte(machineKey.ValidationKey); - encodedPassword = - Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); - break; - default: - throw new ProviderException("Unsupported password format."); - } - - return encodedPassword; - } - - // - // UnEncodePassword - // Decrypts or leaves the password clear based on the PasswordFormat. - // - - private string UnEncodePassword(string encodedPassword) - { - string password = encodedPassword; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Clear: - break; - case MembershipPasswordFormat.Encrypted: - password = - Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))); - break; - case MembershipPasswordFormat.Hashed: - throw new ProviderException("Cannot unencode a hashed password."); - default: - throw new ProviderException("Unsupported password format."); - } - - return password; - } - - // - // HexToByte - // Converts a hexadecimal string to a byte array. Used to convert encryption - // key values from the configuration. - // - - private byte[] HexToByte(string hexString) - { - byte[] returnBytes = new byte[hexString.Length / 2]; - for (int i = 0; i < returnBytes.Length; i++) - returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); - return returnBytes; - } - } -} diff --git a/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovidergetallusers.cs b/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovidergetallusers.cs deleted file mode 100644 index 30efffd38c2..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovidergetallusers.cs +++ /dev/null @@ -1,1457 +0,0 @@ -using System.Web.Security; -using System.Configuration.Provider; -using System.Collections.Specialized; -using System; -using System.Data; -using System.Data.Odbc; -using System.Configuration; -using System.Diagnostics; -using System.Web; -using System.Globalization; -using System.Web.Configuration; -using System.Security.Cryptography; -using System.Text; - -/* - -This provider works with the following schema for the table of user data. - -CREATE TABLE Users -( - PKID Guid NOT NULL PRIMARY KEY, - Username Text (255) NOT NULL, - ApplicationName Text (255) NOT NULL, - Email Text (128) NOT NULL, - Comment Text (255), - Password Text (128) NOT NULL, - PasswordQuestion Text (255), - PasswordAnswer Text (128), - IsApproved YesNo, - LastActivityDate DateTime, - LastLoginDate DateTime, - LastPasswordChangedDate DateTime, - CreationDate DateTime, - IsOnLine YesNo, - IsLockedOut YesNo, - LastLockedOutDate DateTime, - FailedPasswordAttemptCount Integer, - FailedPasswordAttemptWindowStart DateTime, - FailedPasswordAnswerAttemptCount Integer, - FailedPasswordAnswerAttemptWindowStart DateTime -) - -*/ - -namespace Samples.AspNet.Membership -{ - -public sealed class OdbcMembershipProvider: MembershipProvider -{ - -// -// Global OdbcConnection, generated password length, generic exception message, event log info. -// - -private OdbcConnection conn; -private int newPasswordLength = 8; - -// -// Used when determining encryption key values. -// - -private MachineKeySection machineKey; - -// -// Database connection string. -// - -private ConnectionStringSettings pConnectionStringSettings; - -public string ConnectionString -{ - get { return pConnectionStringSettings.ConnectionString; } -} - -// -// System.Configuration.Provider.ProviderBase.Initialize Method -// - -public override void Initialize(string name, NameValueCollection config) -{ - - // - // Initialize values from web.config. - // - - if (config == null) - throw new ArgumentNullException("config"); - - if (name == null || name.Length == 0) - name = "OdbcMembershipProvider"; - - if (String.IsNullOrEmpty(config["description"])) - { - config.Remove("description"); - config.Add("description", "Sample ODBC Membership provider"); - } - - // Initialize the abstract base class. - base.Initialize(name, config); - - pApplicationName = GetConfigValue(config["applicationName"], - System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); - pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); - pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); - pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); - pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); - pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); - pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); - pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); - pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); - pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); - - string temp_format = config["passwordFormat"]; - temp_format ??= "Hashed"; - - switch (temp_format) - { - case "Hashed": - pPasswordFormat = MembershipPasswordFormat.Hashed; - break; - case "Encrypted": - pPasswordFormat = MembershipPasswordFormat.Encrypted; - break; - case "Clear": - pPasswordFormat = MembershipPasswordFormat.Clear; - break; - default: - throw new ProviderException("Password format not supported."); - } - - // - // Initialize OdbcConnection. - // - - pConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; - - if (pConnectionStringSettings == null || pConnectionStringSettings.ConnectionString.Trim() == "") - { - throw new ProviderException("Connection string cannot be blank."); - } - - conn = new OdbcConnection(ConnectionString); - - // Get encryption and decryption key information from the configuration. - Configuration cfg = - WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); - machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); -} - - // - // A helper function to retrieve config values from the configuration file. - // - - private string GetConfigValue(string configValue, string defaultValue) - { - if (configValue == null || configValue.Trim() == "") - return defaultValue; - - return configValue; - } - -// -// System.Web.Security.MembershipProvider properties. -// - - private bool pRequiresUniqueEmail; - - public override bool RequiresUniqueEmail - { - get { return pRequiresUniqueEmail; } - } - - private int pMaxInvalidPasswordAttempts; - - public override int MaxInvalidPasswordAttempts - { - get { return pMaxInvalidPasswordAttempts; } - } - - private int pPasswordAttemptWindow; - - public override int PasswordAttemptWindow - { - get { return pPasswordAttemptWindow; } - } - - private MembershipPasswordFormat pPasswordFormat; - - public override MembershipPasswordFormat PasswordFormat - { - get { return pPasswordFormat; } - } - - private int pMinRequiredNonAlphanumericCharacters; - - public override int MinRequiredNonAlphanumericCharacters - { - get { return pMinRequiredNonAlphanumericCharacters; } - } - - private int pMinRequiredPasswordLength; - - public override int MinRequiredPasswordLength - { - get { return pMinRequiredPasswordLength; } - } - - private string pPasswordStrengthRegularExpression; - - public override string PasswordStrengthRegularExpression - { - get { return pPasswordStrengthRegularExpression; } - } - -// -17> -private string pApplicationName; - -public override string ApplicationName -{ - get { return pApplicationName; } - set { pApplicationName = value; } -} -// - /17> - -// -1> -private bool pEnablePasswordReset; - -public override bool EnablePasswordReset -{ - get { return pEnablePasswordReset; } -} -// - /1> - -// -2> -private bool pEnablePasswordRetrieval; - -public override bool EnablePasswordRetrieval -{ - get { return pEnablePasswordRetrieval; } -} -// - /2> - -// -3> -private bool pRequiresQuestionAndAnswer; - -public override bool RequiresQuestionAndAnswer -{ - get { return pRequiresQuestionAndAnswer; } -} -// - /3> - -// -// System.Web.Security.MembershipProvider methods. -// - -// -// MembershipProvider.ChangePassword -// - -// -4> -public override bool ChangePassword(string username, string oldPwd, string newPwd) -{ - if (!ValidateUser(username, oldPwd)) - { - throw new MembershipPasswordException("Password validation failed."); - } - - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, newPwd, true); - - OnValidatingPassword(args); - - if (args.Cancel) - if (args.FailureInformation != null) - throw args.FailureInformation; - else - throw new Exception("Change password canceled due to new password validation failure."); - - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("UPDATE Users "+ - " SET Password = ?, LastPasswordChangedDate = ? " + - " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = newPwd; - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@OldPassword", OdbcType.VarChar, 128).Value = oldPwd; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; -} -// - /4> - -// -// MembershipProvider.ChangePasswordQuestionAndAnswer -// - -// -5> -public override bool ChangePasswordQuestionAndAnswer(string username, - string password, - string newPwdQuestion, - string newPwdAnswer) -{ - if (!ValidateUser(username, password)) - { - return false; - } - - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET PasswordQuestion = ?, PasswordAnswer = ?" + - " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Question", OdbcType.VarChar, 255).Value = newPwdQuestion; - cmd.Parameters.Add("@Answer", OdbcType.VarChar, 128).Value = newPwdAnswer; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = password; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; -} -// - /5> - -// -// MembershipProvider.CreateUser -// - -// -6> -public override MembershipUser CreateUser(string username, - string password, - string email, - string passwordQuestion, - string passwordAnswer, - bool isApproved, - object providerUserKey, - out MembershipCreateStatus status) -{ - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, password, true); - - OnValidatingPassword(args); - - if (args.Cancel) - if (args.FailureInformation != null) - throw args.FailureInformation; - else - throw new Exception("Create user canceled due to password validation failure."); - - if (RequiresUniqueEmail && GetUserNameByEmail(email) != "") - { - status = MembershipCreateStatus.DuplicateEmail; - return null; - } - - MembershipUser u = GetUser(username, false); - - if (u == null) - { - DateTime createDate = DateTime.Now; - - if (providerUserKey == null) - { - providerUserKey = Guid.NewGuid(); - } - else - { - if ( !(providerUserKey is Guid) ) - { - status = MembershipCreateStatus.InvalidProviderUserKey; - return null; - } - } - - OdbcCommand cmd = new OdbcCommand("INSERT INTO Users " + - " (PKID, Username, Password, Email, PasswordQuestion, " + - " PasswordAnswer, IsApproved," + - " Comment, CreationDate, LastPasswordChangedDate, LastActivityDate," + - " ApplicationName, IsLockedOut, LastLockedOutDate," + - " FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, " + - " FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart)" + - " Values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", conn); - - cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(password); - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email; - cmd.Parameters.Add("@PasswordQuestion", OdbcType.VarChar, 255).Value = passwordQuestion; - cmd.Parameters.Add("@PasswordAnswer", OdbcType.VarChar, 128).Value = passwordAnswer; - cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = isApproved; - cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = ""; - cmd.Parameters.Add("@CreationDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = false; - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@FailedPasswordAttemptCount", OdbcType.Int).Value = 0; - cmd.Parameters.Add("@FailedPasswordAttemptWindowStart", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@FailedPasswordAnswerAttemptCount", OdbcType.Int).Value = 0; - cmd.Parameters.Add("@FailedPasswordAnswerAttemptWindowStart", OdbcType.DateTime).Value = createDate; - - try - { - conn.Open(); - - int recAdded = cmd.ExecuteNonQuery(); - - if (recAdded > 0) - { - status = MembershipCreateStatus.Success; - } - else - { - status = MembershipCreateStatus.UserRejected; - } - } - catch (OdbcException) - { - // Handle exception. - - status = MembershipCreateStatus.ProviderError; - } - finally - { - conn.Close(); - } - - return GetUser(username, false); - } - else - { - status = MembershipCreateStatus.DuplicateUserName; - } - - return null; -} -// - /6> - -// -// MembershipProvider.DeleteUser -// - -// -7> -public override bool DeleteUser(string username, bool deleteAllRelatedData) -{ - - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("DELETE FROM Users " + - " WHERE Username = ? AND Applicationname = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - - if (deleteAllRelatedData) - { - // Process commands to delete all data for the user in the database. - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; -} -// - /7> - -// -// MembershipProvider.GetAllUsers -// - -// -public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) -{ - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE ApplicationName = ?", conn); - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return users; -} - -// -// GetUserFromReader -// A helper function that takes the current row from the OdbcDataReader -// and populates a MembershipUser object with the values. Called by the -// MembershipUser.GetUser implementation. -// - -public MembershipUser GetUserFromReader(OdbcDataReader reader) -{ - object providerUserKey = reader.GetValue(0); - string username = reader.GetString(1); - string email = reader.GetString(2); - - string passwordQuestion = ""; - if (reader.GetValue(3) != DBNull.Value) - passwordQuestion = reader.GetString(3); - - string comment = ""; - if (reader.GetValue(4) != DBNull.Value) - comment = reader.GetString(4); - - bool isApproved = reader.GetBoolean(5); - bool isLockedOut = reader.GetBoolean(6); - DateTime creationDate = reader.GetDateTime(7); - - DateTime lastLoginDate = new DateTime(); - if (reader.GetValue(8) != DBNull.Value) - lastLoginDate = reader.GetDateTime(8); - - DateTime lastActivityDate = reader.GetDateTime(9); - DateTime lastPasswordChangedDate = reader.GetDateTime(10); - - DateTime lastLockedOutDate = new DateTime(); - if (reader.GetValue(11) != DBNull.Value) - lastLockedOutDate = reader.GetDateTime(11); - - MembershipUser u = new MembershipUser(this.Name, - username, - providerUserKey, - email, - passwordQuestion, - comment, - isApproved, - isLockedOut, - creationDate, - lastLoginDate, - lastActivityDate, - lastPasswordChangedDate, - lastLockedOutDate); - - return u; -} -// - -// -// MembershipProvider.GetNumberOfUsersOnline -// - -// -8> -public override int GetNumberOfUsersOnline() -{ - - TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0); - DateTime compareTime = DateTime.Now.Subtract(onlineSpan); - - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - " WHERE LastActivityDate > ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@CompareDate", OdbcType.DateTime).Value = compareTime; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int numOnline = 0; - - try - { - conn.Open(); - - numOnline = (int)cmd.ExecuteScalar(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - return numOnline; -} -// - /8> - -// -// MembershipProvider.GetPassword -// - -// -9> -public override string GetPassword(string username, string answer) -{ - if (!EnablePasswordRetrieval) - { - throw new ProviderException("Password retrieval is not enabled."); - } - - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("SELECT Password, PasswordAnswer FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - string password = ""; - string passwordAnswer = ""; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - password = reader.GetString(0); - passwordAnswer = reader.GetString(1); - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - if (RequiresQuestionAndAnswer && - String.Compare(passwordAnswer, answer, true, CultureInfo.InvariantCulture) != 0) - { - throw new MembershipPasswordException("Incorrect password answer."); - } - - return password; -} -// - /9> - -// -// MembershipProvider.GetUser -// - -// -10> -public override MembershipUser GetUser(string username, bool userIsOnline) -{ - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," + - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" + - " FROM Users WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - MembershipUser u = null; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(); - - if (reader.HasRows) - { - reader.Read(); - u = GetUserFromReader(reader); - - if (userIsOnline) - { - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " + - "SET LastActivityDate = ? " + - "WHERE Username = ? AND Applicationname = ?", conn); - - updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - updateCmd.ExecuteNonQuery(); - } - } - } - catch (OdbcException) - { - // Handle exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return u; -} - -// - /10> - -// -// MembershipProvider.GetUserNameByEmail -// - -// -11> -public override string GetUserNameByEmail(string email) -{ - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("SELECT Username" + - " FROM Users WHERE Email = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - string username = ""; - - try - { - conn.Open(); - - username = (string)cmd.ExecuteScalar(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - return username; -} -// - /11> - -// -// MembershipProvider.ResetPassword -// - -// -12> -public override string ResetPassword(string username, string answer) -{ - if (!EnablePasswordReset) - { - throw new NotSupportedException("Password reset is not enabled."); - } - - if (answer == null && RequiresQuestionAndAnswer) - { - throw new ProviderException("A password answer is required to reset the password."); - } - - string newPassword = - System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters); - - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, newPassword, true); - - OnValidatingPassword(args); - - if (args.Cancel) - if (args.FailureInformation != null) - throw args.FailureInformation; - else - throw new Exception("Reset password canceled due to password validation failure."); - - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET Password = ?, LastPasswordChangedDate = ?" + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = newPassword; - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - if (RequiresQuestionAndAnswer) - { - cmd.CommandText += " AND PasswordAnswer = ?"; - cmd.Parameters.Add("@PasswordAnswer", OdbcType.VarChar, 128).Value = answer; - } - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return newPassword; - } - else - { - throw new MembershipPasswordException("Invalid password answer for userid. Password not reset."); - } -} -// - /12> - -// -// MembershipProvider.UpdateUser -// - -// -13> -public override void UpdateUser(MembershipUser user) -{ - // conn is an OdbcConnection defined globally for the class. - - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET Email = ?, Comment = ?," + - " IsApproved = ?" + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = user.Email; - cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = user.Comment; - cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = user.IsApproved; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = user.UserName; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - try - { - conn.Open(); - - cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } -} -// - /13> - -// -// MembershipProvider.ValidateUser -// - -// -14> -public override bool ValidateUser(string username, string password) -{ - bool isValid = false; - - OdbcCommand cmd = new OdbcCommand("SELECT Password, IsApproved FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - OdbcDataReader reader = null; - bool isApproved = false; - string pwd = ""; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - pwd = reader.GetString(0); - isApproved = reader.GetBoolean(1); - } - - if (isApproved && (password == pwd)) - { - isValid = true; - - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users SET LastLoginDate = ?" + - " WHERE Username = ? AND ApplicationName = ?", conn); - - updateCmd.Parameters.Add("@LastLoginDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - updateCmd.ExecuteNonQuery(); - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return isValid; -} -// - /14> - -public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) -{ - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE Username LIKE ? AND ApplicationName = ?", conn); - cmd.Parameters.Add("@UsernameSearch", OdbcType.VarChar, 255).Value = usernameToMatch; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE Username LIKE ? AND ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return users; -} - -public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) -{ - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE Email LIKE ? AND ApplicationName = ?", conn); - cmd.Parameters.Add("@EmailSearch", OdbcType.VarChar, 255).Value = emailToMatch; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE Email LIKE ? AND ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return users; -} - -// -// MembershipProvider.UnlockUser -// - -public override bool UnlockUser(string username) -{ - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET IsLockedOut = False, LastLockedOutDate = ? " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - return true; - - return false; -} - -// -// MembershipProvider.GetUser(object, bool) -// - -public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) -{ - OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," + - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" + - " FROM Users WHERE PKID = ?", conn); - - cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - - MembershipUser u = null; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(); - - if (reader.HasRows) - { - reader.Read(); - u = GetUserFromReader(reader); - - if (userIsOnline) - { - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " + - "SET LastActivityDate = ? " + - "WHERE PKID = ?", conn); - - updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - - updateCmd.ExecuteNonQuery(); - } - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return u; -} - - // - // UpdateFailureCount - // A helper method that performs the checks and updates associated with - // password failure tracking. - // - - private void UpdateFailureCount(string username, string failureType) - { - OdbcCommand cmd = new OdbcCommand("SELECT FailedPasswordAttemptCount, " + - " FailedPasswordAttemptWindowStart, " + - " FailedPasswordAnswerAttemptCount, " + - " FailedPasswordAnswerAttemptWindowStart " + - " FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - OdbcDataReader reader = null; - DateTime windowStart = new DateTime(); - int failureCount = 0; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - - if (failureType == "password") - { - failureCount = reader.GetInt32(0); - windowStart = reader.GetDateTime(1); - } - - if (failureType == "passwordAnswer") - { - failureCount = reader.GetInt32(2); - windowStart = reader.GetDateTime(3); - } - } - - reader.Close(); - - DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow); - - if (failureCount == 0 || DateTime.Now > windowEnd) - { - // First password failure or outside of PasswordAttemptWindow. - // Start a new password failure count from 1 and a new window starting now. - - if (failureType == "password") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAttemptCount = ?, " + - " FailedPasswordAttemptWindowStart = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - if (failureType == "passwordAnswer") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAnswerAttemptCount = ?, " + - " FailedPasswordAnswerAttemptWindowStart = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@Count", OdbcType.Int).Value = 1; - cmd.Parameters.Add("@WindowStart", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new Exception("Unable to update failure count and window start."); - } - else - { - if (failureCount++ >= MaxInvalidPasswordAttempts) - { - // Password attempts have exceeded the failure threshold. Lock out - // the user. - - cmd.CommandText = "UPDATE Users " + - " SET IsLockedOut = ?, LastLockedOutDate = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = true; - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new Exception("Unable to lock out user."); - } - else - { - // Password attempts have not exceeded the failure threshold. Update - // the failure counts. Leave the window the same. - - if (failureType == "password") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAttemptCount = ?" + - " WHERE Username = ? AND ApplicationName = ?"; - - if (failureType == "passwordAnswer") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAnswerAttemptCount = ?" + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@Count", OdbcType.Int).Value = failureCount; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new Exception("Unable to update failure count."); - } - } - } - catch (OdbcException) - { - // Handle Exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - } - - // - // CheckPassword - // Compares password values based on the MembershipPasswordFormat. - // - - private bool CheckPassword(string password, string dbpassword) - { - string pass1 = password; - string pass2 = dbpassword; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Encrypted: - pass2 = UnEncodePassword(dbpassword); - break; - case MembershipPasswordFormat.Hashed: - pass1 = EncodePassword(password); - break; - default: - break; - } - - if (pass1 == pass2) - { - return true; - } - - return false; - } - - // - // EncodePassword - // Encrypts, Hashes, or leaves the password clear based on the PasswordFormat. - // - - private string EncodePassword(string password) - { - string encodedPassword = password; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Clear: - break; - case MembershipPasswordFormat.Encrypted: - encodedPassword = - Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); - break; - case MembershipPasswordFormat.Hashed: - HMACSHA256 hash = new HMACSHA256(); - hash.Key = HexToByte(machineKey.ValidationKey); - encodedPassword = - Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); - break; - default: - throw new ProviderException("Unsupported password format."); - } - - return encodedPassword; - } - - // - // UnEncodePassword - // Decrypts or leaves the password clear based on the PasswordFormat. - // - - private string UnEncodePassword(string encodedPassword) - { - string password = encodedPassword; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Clear: - break; - case MembershipPasswordFormat.Encrypted: - password = - Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))); - break; - case MembershipPasswordFormat.Hashed: - throw new ProviderException("Cannot unencode a hashed password."); - default: - throw new ProviderException("Unsupported password format."); - } - - return password; - } - - // - // HexToByte - // Converts a hexadecimal string to a byte array. Used to convert encryption - // key values from the configuration. - // - - private byte[] HexToByte(string hexString) - { - byte[] returnBytes = new byte[hexString.Length / 2]; - for (int i = 0; i < returnBytes.Length; i++) - returnBytes[i] = Convert.ToByte(hexString.Substring(i*2, 2), 16); - return returnBytes; - } -} -} diff --git a/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.MembershipUser.Constructor/CS/newuser.cs b/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.MembershipUser.Constructor/CS/newuser.cs deleted file mode 100644 index 6e321c9ab9f..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.MembershipUser.Constructor/CS/newuser.cs +++ /dev/null @@ -1,1499 +0,0 @@ -using System.Web.Security; -using System.Configuration.Provider; -using System.Collections.Specialized; -using System; -using System.Data; -using System.Data.Odbc; -using System.Configuration; -using System.Diagnostics; -using System.Web; -using System.Globalization; -using System.Web.Configuration; -using System.Security.Cryptography; -using System.Text; - -/* - -This provider works with the following schema for the table of user data. - -CREATE TABLE Users -( - PKID Guid NOT NULL PRIMARY KEY, - Username Text (255) NOT NULL, - ApplicationName Text (255) NOT NULL, - Email Text (128) NOT NULL, - Comment Text (255), - Password Text (128) NOT NULL, - PasswordQuestion Text (255), - PasswordAnswer Text (255), - IsApproved YesNo, - LastActivityDate DateTime, - LastLoginDate DateTime, - LastPasswordChangedDate DateTime, - CreationDate DateTime, - IsOnLine YesNo, - IsLockedOut YesNo, - LastLockedOutDate DateTime, - FailedPasswordAttemptCount Integer, - FailedPasswordAttemptWindowStart DateTime, - FailedPasswordAnswerAttemptCount Integer, - FailedPasswordAnswerAttemptWindowStart DateTime -) - -*/ - -namespace Samples.AspNet.Membership -{ - - public sealed class OdbcMembershipProvider : MembershipProvider - { - - // - // Global generated password length, generic exception message, event log info. - // - - private int newPasswordLength = 8; - - // - // Used when determining encryption key values. - // - - private MachineKeySection machineKey; - - // - // Database connection string. - // - - private ConnectionStringSettings pConnectionStringSettings; - - public string ConnectionString - { - get { return pConnectionStringSettings.ConnectionString; } - } - - // - // System.Configuration.Provider.ProviderBase.Initialize Method - // - - public override void Initialize(string name, NameValueCollection config) - { - // - // Initialize values from web.config. - // - - if (config == null) - throw new ArgumentNullException("config"); - - if (name == null || name.Length == 0) - name = "OdbcMembershipProvider"; - - if (String.IsNullOrEmpty(config["description"])) - { - config.Remove("description"); - config.Add("description", "Sample ODBC Membership provider"); - } - - // Initialize the abstract base class. - base.Initialize(name, config); - - pApplicationName = GetConfigValue(config["applicationName"], - System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); - pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); - pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); - pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); - pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); - pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); - pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); - pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); - pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); - pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); - - string temp_format = config["passwordFormat"]; - temp_format ??= "Hashed"; - - switch (temp_format) - { - case "Hashed": - pPasswordFormat = MembershipPasswordFormat.Hashed; - break; - case "Encrypted": - pPasswordFormat = MembershipPasswordFormat.Encrypted; - break; - case "Clear": - pPasswordFormat = MembershipPasswordFormat.Clear; - break; - default: - throw new ProviderException("Password format not supported."); - } - - // - // Initialize OdbcConnection. - // - - pConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; - - if (pConnectionStringSettings == null || pConnectionStringSettings.ConnectionString.Trim() == "") - { - throw new ProviderException("Connection string cannot be blank."); - } - - // Get encryption and decryption key information from the configuration. - Configuration cfg = - WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); - machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); - } - - // - // A helper function to retrieve config values from the configuration file. - // - - private string GetConfigValue(string configValue, string defaultValue) - { - if (configValue == null || configValue.Trim() == "") - return defaultValue; - - return configValue; - } - - // - // System.Web.Security.MembershipProvider properties. - // - - private bool pRequiresUniqueEmail; - - public override bool RequiresUniqueEmail - { - get { return pRequiresUniqueEmail; } - } - - private int pMaxInvalidPasswordAttempts; - - public override int MaxInvalidPasswordAttempts - { - get { return pMaxInvalidPasswordAttempts; } - } - - private int pPasswordAttemptWindow; - - public override int PasswordAttemptWindow - { - get { return pPasswordAttemptWindow; } - } - - private MembershipPasswordFormat pPasswordFormat; - - public override MembershipPasswordFormat PasswordFormat - { - get { return pPasswordFormat; } - } - - private int pMinRequiredNonAlphanumericCharacters; - - public override int MinRequiredNonAlphanumericCharacters - { - get { return pMinRequiredNonAlphanumericCharacters; } - } - - private int pMinRequiredPasswordLength; - - public override int MinRequiredPasswordLength - { - get { return pMinRequiredPasswordLength; } - } - - private string pPasswordStrengthRegularExpression; - - public override string PasswordStrengthRegularExpression - { - get { return pPasswordStrengthRegularExpression; } - } - - // - private string pApplicationName; - - public override string ApplicationName - { - get { return pApplicationName; } - set { pApplicationName = value; } - } - // - - // - private bool pEnablePasswordReset; - - public override bool EnablePasswordReset - { - get { return pEnablePasswordReset; } - } - // - - // - private bool pEnablePasswordRetrieval; - - public override bool EnablePasswordRetrieval - { - get { return pEnablePasswordRetrieval; } - } - // - - // - private bool pRequiresQuestionAndAnswer; - - public override bool RequiresQuestionAndAnswer - { - get { return pRequiresQuestionAndAnswer; } - } - // - - // - // System.Web.Security.MembershipProvider methods. - // - - // - // MembershipProvider.ChangePassword - // - - // - public override bool ChangePassword(string username, string oldPwd, string newPwd) - { - if (!ValidateUser(username, oldPwd)) - { - return false; - } - - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, newPwd, true); - - OnValidatingPassword(args); - - if (args.Cancel) - if (args.FailureInformation != null) - throw args.FailureInformation; - else - throw new MembershipPasswordException("Change password canceled due to new password validation failure."); - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET Password = ?, LastPasswordChangedDate = ? " + - " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = EncodePassword(newPwd); - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@OldPassword", OdbcType.VarChar, 128).Value = oldPwd; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; - } - // - - // - // MembershipProvider.ChangePasswordQuestionAndAnswer - // - - // - public override bool ChangePasswordQuestionAndAnswer(string username, - string password, - string newPwdQuestion, - string newPwdAnswer) - { - if (!ValidateUser(username, password)) - { - return false; - } - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET PasswordQuestion = ?, PasswordAnswer = ?" + - " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Question", OdbcType.VarChar, 255).Value = newPwdQuestion; - cmd.Parameters.Add("@Answer", OdbcType.VarChar, 255).Value = EncodePassword(newPwdAnswer); - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = password; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; - } - // - - // - // MembershipProvider.CreateUser - // - - // - public override MembershipUser CreateUser(string username, - string password, - string email, - string passwordQuestion, - string passwordAnswer, - bool isApproved, - object providerUserKey, - out MembershipCreateStatus status) - { - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, password, true); - - OnValidatingPassword(args); - - if (args.Cancel) - { - status = MembershipCreateStatus.InvalidPassword; - return null; - } - - if (RequiresUniqueEmail && GetUserNameByEmail(email) != "") - { - status = MembershipCreateStatus.DuplicateEmail; - return null; - } - - MembershipUser u = GetUser(username, false); - - if (u == null) - { - DateTime createDate = DateTime.Now; - - if (providerUserKey == null) - { - providerUserKey = Guid.NewGuid(); - } - else - { - if (!(providerUserKey is Guid)) - { - status = MembershipCreateStatus.InvalidProviderUserKey; - return null; - } - } - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("INSERT INTO Users " + - " (PKID, Username, Password, Email, PasswordQuestion, " + - " PasswordAnswer, IsApproved," + - " Comment, CreationDate, LastPasswordChangedDate, LastActivityDate," + - " ApplicationName, IsLockedOut, LastLockedOutDate," + - " FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, " + - " FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart)" + - " Values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", conn); - - cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(password); - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email; - cmd.Parameters.Add("@PasswordQuestion", OdbcType.VarChar, 255).Value = passwordQuestion; - cmd.Parameters.Add("@PasswordAnswer", OdbcType.VarChar, 255).Value = EncodePassword(passwordAnswer); - cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = isApproved; - cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = ""; - cmd.Parameters.Add("@CreationDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = false; - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@FailedPasswordAttemptCount", OdbcType.Int).Value = 0; - cmd.Parameters.Add("@FailedPasswordAttemptWindowStart", OdbcType.DateTime).Value = createDate; - cmd.Parameters.Add("@FailedPasswordAnswerAttemptCount", OdbcType.Int).Value = 0; - cmd.Parameters.Add("@FailedPasswordAnswerAttemptWindowStart", OdbcType.DateTime).Value = createDate; - - try - { - conn.Open(); - - int recAdded = cmd.ExecuteNonQuery(); - - if (recAdded > 0) - { - status = MembershipCreateStatus.Success; - } - else - { - status = MembershipCreateStatus.UserRejected; - } - } - catch (OdbcException) - { - // Handle exception. - - status = MembershipCreateStatus.ProviderError; - } - finally - { - conn.Close(); - } - - return GetUser(username, false); - } - else - { - status = MembershipCreateStatus.DuplicateUserName; - } - - return null; - } - // - - // - // MembershipProvider.DeleteUser - // - - // - public override bool DeleteUser(string username, bool deleteAllRelatedData) - { - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("DELETE FROM Users " + - " WHERE Username = ? AND Applicationname = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - - if (deleteAllRelatedData) - { - // Process commands to delete all data for the user in the database. - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - { - return true; - } - - return false; - } - // - - // - // MembershipProvider.GetAllUsers - // - - public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE ApplicationName = ?", conn); - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return users; - } - - // - // MembershipProvider.GetNumberOfUsersOnline - // - - // - public override int GetNumberOfUsersOnline() - { - - TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0); - DateTime compareTime = DateTime.Now.Subtract(onlineSpan); - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - " WHERE LastActivityDate > ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@CompareDate", OdbcType.DateTime).Value = compareTime; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - int numOnline = 0; - - try - { - conn.Open(); - - numOnline = (int)cmd.ExecuteScalar(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - return numOnline; - } - // - - // - // MembershipProvider.GetPassword - // - - // - public override string GetPassword(string username, string answer) - { - if (!EnablePasswordRetrieval) - { - throw new ProviderException("Password Retrieval Not Enabled."); - } - - if (PasswordFormat == MembershipPasswordFormat.Hashed) - { - throw new ProviderException("Cannot retrieve Hashed passwords."); - } - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Password, PasswordAnswer, IsLockedOut FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - string password = ""; - string passwordAnswer = ""; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - - if (reader.GetBoolean(2)) - throw new MembershipPasswordException("The supplied user is locked out."); - - password = reader.GetString(0); - passwordAnswer = reader.GetString(1); - } - else - { - throw new MembershipPasswordException("The supplied user name is not found."); - } - } - catch (OdbcException) - { - // Handle exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer)) - { - UpdateFailureCount(username, "passwordAnswer"); - - throw new MembershipPasswordException("Incorrect password answer."); - } - - if (PasswordFormat == MembershipPasswordFormat.Encrypted) - { - password = UnEncodePassword(password); - } - - return password; - } - // - - // - // MembershipProvider.GetUser - // - - // - public override MembershipUser GetUser(string username, bool userIsOnline) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," + - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" + - " FROM Users WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - MembershipUser u = null; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(); - - if (reader.HasRows) - { - reader.Read(); - u = GetUserFromReader(reader); - - if (userIsOnline) - { - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " + - "SET LastActivityDate = ? " + - "WHERE Username = ? AND Applicationname = ?", conn); - - updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - updateCmd.ExecuteNonQuery(); - } - } - } - catch (OdbcException) - { - // Handle exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return u; - } - - // - // GetUserFromReader - // A helper function that takes the current row from the OdbcDataReader - // and populates a MembershipUser object with the values. Called by the - // MembershipUser.GetUser implementation. - // - - public MembershipUser GetUserFromReader(OdbcDataReader reader) - { - object providerUserKey = reader.GetValue(0); - string username = reader.GetString(1); - string email = reader.GetString(2); - - string passwordQuestion = ""; - if (reader.GetValue(3) != DBNull.Value) - passwordQuestion = reader.GetString(3); - - string comment = ""; - if (reader.GetValue(4) != DBNull.Value) - comment = reader.GetString(4); - - bool isApproved = reader.GetBoolean(5); - bool isLockedOut = reader.GetBoolean(6); - DateTime creationDate = reader.GetDateTime(7); - - DateTime lastLoginDate = new DateTime(); - if (reader.GetValue(8) != DBNull.Value) - lastLoginDate = reader.GetDateTime(8); - - DateTime lastActivityDate = reader.GetDateTime(9); - DateTime lastPasswordChangedDate = reader.GetDateTime(10); - - DateTime lastLockedOutDate = new DateTime(); - if (reader.GetValue(11) != DBNull.Value) - lastLockedOutDate = reader.GetDateTime(11); - - MembershipUser u = new MembershipUser(this.Name, - username, - providerUserKey, - email, - passwordQuestion, - comment, - isApproved, - isLockedOut, - creationDate, - lastLoginDate, - lastActivityDate, - lastPasswordChangedDate, - lastLockedOutDate); - - return u; - } - // - - // - // MembershipProvider.GetUserNameByEmail - // - - // - public override string GetUserNameByEmail(string email) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Username" + - " FROM Users WHERE Email = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - string username = ""; - - try - { - conn.Open(); - - username = (string)cmd.ExecuteScalar(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - return username; - } - // - - // - // MembershipProvider.ResetPassword - // - - // - public override string ResetPassword(string username, string answer) - { - if (!EnablePasswordReset) - { - throw new NotSupportedException("Password reset is not enabled."); - } - - if (answer == null && RequiresQuestionAndAnswer) - { - UpdateFailureCount(username, "passwordAnswer"); - - throw new ProviderException("Password answer required for password reset."); - } - - string newPassword = System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters); - - ValidatePasswordEventArgs args = - new ValidatePasswordEventArgs(username, newPassword, true); - - OnValidatingPassword(args); - - if (args.Cancel) - if (args.FailureInformation != null) - throw args.FailureInformation; - else - throw new MembershipPasswordException("Reset password canceled due to password validation failure."); - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT PasswordAnswer, IsLockedOut FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - int rowsAffected = 0; - string passwordAnswer = ""; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - - if (reader.GetBoolean(1)) - throw new MembershipPasswordException("The supplied user is locked out."); - - passwordAnswer = reader.GetString(0); - } - else - { - throw new MembershipPasswordException("The supplied user name is not found."); - } - - if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer)) - { - UpdateFailureCount(username, "passwordAnswer"); - - throw new MembershipPasswordException("Incorrect password answer."); - } - - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " + - " SET Password = ?, LastPasswordChangedDate = ?" + - " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn); - - updateCmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(newPassword); - updateCmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - rowsAffected = updateCmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - if (rowsAffected > 0) - { - return newPassword; - } - else - { - throw new MembershipPasswordException("User not found, or user is locked out. Password not Reset."); - } - } - // - - // - // MembershipProvider.UpdateUser - // - - // - public override void UpdateUser(MembershipUser user) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET Email = ?, Comment = ?," + - " IsApproved = ?" + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = user.Email; - cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = user.Comment; - cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = user.IsApproved; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = user.UserName; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - try - { - conn.Open(); - - cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - } - // - - // - // MembershipProvider.ValidateUser - // - - // - public override bool ValidateUser(string username, string password) - { - bool isValid = false; - - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Password, IsApproved FROM Users " + - " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - OdbcDataReader reader = null; - bool isApproved = false; - string pwd = ""; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - pwd = reader.GetString(0); - isApproved = reader.GetBoolean(1); - } - else - { - return false; - } - - if (isApproved && (password == pwd)) - { - isValid = true; - - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users SET LastLoginDate = ?" + - " WHERE Username = ? AND ApplicationName = ?", conn); - - updateCmd.Parameters.Add("@LastLoginDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - updateCmd.ExecuteNonQuery(); - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - - return isValid; - } - // - - public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE Username LIKE ? AND ApplicationName = ?", conn); - cmd.Parameters.Add("@UsernameSearch", OdbcType.VarChar, 255).Value = usernameToMatch; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE Username LIKE ? AND ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return users; - } - - public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " + - "WHERE Email LIKE ? AND ApplicationName = ?", conn); - cmd.Parameters.Add("@EmailSearch", OdbcType.VarChar, 255).Value = emailToMatch; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName; - - MembershipUserCollection users = new MembershipUserCollection(); - - OdbcDataReader reader = null; - totalRecords = 0; - - try - { - conn.Open(); - totalRecords = (int)cmd.ExecuteScalar(); - - if (totalRecords <= 0) { return users; } - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," + - " Comment, IsApproved, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate " + - " FROM Users " + - " WHERE Email LIKE ? AND ApplicationName = ? " + - " ORDER BY Username Asc"; - - reader = cmd.ExecuteReader(); - - int counter = 0; - int startIndex = pageSize * pageIndex; - int endIndex = startIndex + pageSize - 1; - - while (reader.Read()) - { - if (counter >= startIndex) - { - MembershipUser u = GetUserFromReader(reader); - users.Add(u); - } - - if (counter >= endIndex) { cmd.Cancel(); } - - counter++; - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return users; - } - - // - // MembershipProvider.UnlockUser - // - - public override bool UnlockUser(string username) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("UPDATE Users " + - " SET IsLockedOut = False, LastLockedOutDate = ? " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - int rowsAffected = 0; - - try - { - conn.Open(); - - rowsAffected = cmd.ExecuteNonQuery(); - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - conn.Close(); - } - - if (rowsAffected > 0) - return true; - - return false; - } - - // - // MembershipProvider.GetUser(object, bool) - // - - public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," + - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," + - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" + - " FROM Users WHERE PKID = ?", conn); - - cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - - MembershipUser u = null; - OdbcDataReader reader = null; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(); - - if (reader.HasRows) - { - reader.Read(); - u = GetUserFromReader(reader); - - if (userIsOnline) - { - OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " + - "SET LastActivityDate = ? " + - "WHERE PKID = ?", conn); - - updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now; - updateCmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey; - - updateCmd.ExecuteNonQuery(); - } - } - } - catch (OdbcException) - { - // Handle exception. - } - finally - { - if (reader != null) { reader.Close(); } - - conn.Close(); - } - - return u; - } - - // - // UpdateFailureCount - // A helper method that performs the checks and updates associated with - // password failure tracking. - // - - private void UpdateFailureCount(string username, string failureType) - { - OdbcConnection conn = new OdbcConnection(ConnectionString); - OdbcCommand cmd = new OdbcCommand("SELECT FailedPasswordAttemptCount, " + - " FailedPasswordAttemptWindowStart, " + - " FailedPasswordAnswerAttemptCount, " + - " FailedPasswordAnswerAttemptWindowStart " + - " FROM Users " + - " WHERE Username = ? AND ApplicationName = ?", conn); - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - OdbcDataReader reader = null; - DateTime windowStart = new DateTime(); - int failureCount = 0; - - try - { - conn.Open(); - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow); - - if (reader.HasRows) - { - reader.Read(); - - if (failureType == "password") - { - failureCount = reader.GetInt32(0); - windowStart = reader.GetDateTime(1); - } - - if (failureType == "passwordAnswer") - { - failureCount = reader.GetInt32(2); - windowStart = reader.GetDateTime(3); - } - } - - reader.Close(); - - DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow); - - if (failureCount == 0 || DateTime.Now > windowEnd) - { - // First password failure or outside of PasswordAttemptWindow. - // Start a new password failure count from 1 and a new window starting now. - - if (failureType == "password") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAttemptCount = ?, " + - " FailedPasswordAttemptWindowStart = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - if (failureType == "passwordAnswer") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAnswerAttemptCount = ?, " + - " FailedPasswordAnswerAttemptWindowStart = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@Count", OdbcType.Int).Value = 1; - cmd.Parameters.Add("@WindowStart", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new ProviderException("Unable to update failure count and window start."); - } - else - { - if (failureCount++ >= MaxInvalidPasswordAttempts) - { - // Password attempts have exceeded the failure threshold. Lock out - // the user. - - cmd.CommandText = "UPDATE Users " + - " SET IsLockedOut = ?, LastLockedOutDate = ? " + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = true; - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new ProviderException("Unable to lock out user."); - } - else - { - // Password attempts have not exceeded the failure threshold. Update - // the failure counts. Leave the window the same. - - if (failureType == "password") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAttemptCount = ?" + - " WHERE Username = ? AND ApplicationName = ?"; - - if (failureType == "passwordAnswer") - cmd.CommandText = "UPDATE Users " + - " SET FailedPasswordAnswerAttemptCount = ?" + - " WHERE Username = ? AND ApplicationName = ?"; - - cmd.Parameters.Clear(); - - cmd.Parameters.Add("@Count", OdbcType.Int).Value = failureCount; - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username; - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName; - - if (cmd.ExecuteNonQuery() < 0) - throw new ProviderException("Unable to update failure count."); - } - } - } - catch (OdbcException) - { - // Handle Exception - } - finally - { - if (reader != null) { reader.Close(); } - conn.Close(); - } - } - - // - // CheckPassword - // Compares password values based on the MembershipPasswordFormat. - // - - private bool CheckPassword(string password, string dbpassword) - { - string pass1 = password; - string pass2 = dbpassword; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Encrypted: - pass2 = UnEncodePassword(dbpassword); - break; - case MembershipPasswordFormat.Hashed: - pass1 = EncodePassword(password); - break; - default: - break; - } - - if (pass1 == pass2) - { - return true; - } - - return false; - } - - // - // EncodePassword - // Encrypts, Hashes, or leaves the password clear based on the PasswordFormat. - // - - private string EncodePassword(string password) - { - string encodedPassword = password; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Clear: - break; - case MembershipPasswordFormat.Encrypted: - encodedPassword = - Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); - break; - case MembershipPasswordFormat.Hashed: - HMACSHA256 hash = new HMACSHA256(); - hash.Key = HexToByte(machineKey.ValidationKey); - encodedPassword = - Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); - break; - default: - throw new ProviderException("Unsupported password format."); - } - - return encodedPassword; - } - - // - // UnEncodePassword - // Decrypts or leaves the password clear based on the PasswordFormat. - // - - private string UnEncodePassword(string encodedPassword) - { - string password = encodedPassword; - - switch (PasswordFormat) - { - case MembershipPasswordFormat.Clear: - break; - case MembershipPasswordFormat.Encrypted: - password = - Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))); - break; - case MembershipPasswordFormat.Hashed: - throw new ProviderException("Cannot unencode a hashed password."); - default: - throw new ProviderException("Unsupported password format."); - } - - return password; - } - - // - // HexToByte - // Converts a hexadecimal string to a byte array. Used to convert encryption - // key values from the configuration. - // - - private byte[] HexToByte(string hexString) - { - byte[] returnBytes = new byte[hexString.Length / 2]; - for (int i = 0; i < returnBytes.Length; i++) - returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); - return returnBytes; - } - } -} diff --git a/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/CS/changepassword_cs.aspx b/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/CS/changepassword_cs.aspx deleted file mode 100644 index 483e43a69dc..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/CS/changepassword_cs.aspx +++ /dev/null @@ -1,72 +0,0 @@ - -<%@ Page Language="C#" AutoEventWireup="True" %> - - - - - - - ChangePassword including a ChangingPassword event handler - - -
-
- -

ChangePassword

- - - - -
-
- - You are not logged in - -

- - -
- -
- - - Home - - -
-
- - - \ No newline at end of file diff --git a/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword/CS/changepassword_cs.aspx b/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword/CS/changepassword_cs.aspx deleted file mode 100644 index 3d31e734916..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword/CS/changepassword_cs.aspx +++ /dev/null @@ -1,46 +0,0 @@ - -<%@ Page Language="C#" CodeFile="ChangePassword.cs" Inherits="ChangePassword_cs_aspx" %> - - - - - ChangePassword using code-behind including a SendMailError Event - - -
-
- -

ChangePassword

- - - - -
-
- - You are not logged in - -

- - -
- -
- - - Home - - -
-
- - - \ No newline at end of file diff --git a/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/CS/paramcoll2cs.aspx b/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/CS/paramcoll2cs.aspx deleted file mode 100644 index c3120a1ee67..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/CS/paramcoll2cs.aspx +++ /dev/null @@ -1,81 +0,0 @@ - -<%@Page Language="C#" %> -<%@Import Namespace="System.Data" %> -<%@Import Namespace="System.Data.Common" %> - - - - - - - - - ASP.NET Example - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx b/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx deleted file mode 100644 index 8691b60c4f5..00000000000 --- a/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx +++ /dev/null @@ -1,81 +0,0 @@ - -<%@ Page Language="C#" AutoEventWireup="True" %> - - - - - - - ChangePassword including a SendMailError Event - - -
-
- -

ChangePassword

- - - - -
-
- - You are not logged in - -

- - - - - - - - -
- -
- - - Home - - -
-
- - - \ No newline at end of file diff --git a/snippets/visualbasic/VS_Snippets_WebNet/FormsAuthenticationHashPassword/VB/formsauthenticationhashpasswordvb.aspx b/snippets/visualbasic/VS_Snippets_WebNet/FormsAuthenticationHashPassword/VB/formsauthenticationhashpasswordvb.aspx deleted file mode 100644 index af1723e071b..00000000000 --- a/snippets/visualbasic/VS_Snippets_WebNet/FormsAuthenticationHashPassword/VB/formsauthenticationhashpasswordvb.aspx +++ /dev/null @@ -1,95 +0,0 @@ - -<%@ Page Language="VB" %> - - - - ASP.NET Example - - - - -
-

This form displays the results of the FormsAuthentication.HashPasswordForStoringInConfigFile - method.
The user name and hashed password can be stored in a <credentials> node - in the Web.config file.

- - - - - - - - - - - - - - - - - - - - - - - - - -
New User Name:
Password:
Repeat Password: -
Hash function: - - -
-    - -
- -
-
- - - \ No newline at end of file diff --git a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb b/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb deleted file mode 100644 index be85824900a..00000000000 --- a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb +++ /dev/null @@ -1,117 +0,0 @@ -' -Imports System.Web.Management - -Module UsingSqlServices - Sub Main() - Try -' Values to use. -Dim server As String = "ASPFeatureServer" -Dim database As String = "ASPFeatureDB" -Dim connectionString As String = _ - "server=ASPFeatureServer, pooling=False, user=, password=" -Dim user As String = "AspAdmin" -Dim password As String = "Secure Password" - -' -' Install membership and personalization. -SqlServices.Install(database, _ - SqlFeatures.Membership And _ - SqlFeatures.Personalization, _ - connectionString) -' - -' -' Remove membership and personalization. -SqlServices.Uninstall(database, _ - SqlFeatures.Membership And _ - SqlFeatures.Personalization, _ - connectionString) -' - -' -' Install all features. -SqlServices.Install(server, database, _ - SqlFeatures.All) -' - -' -' Remove all features. -SqlServices.Uninstall(server, database, _ - SqlFeatures.All) -' - -' -' Install a custom session state database. -SqlServices.InstallSessionState(database, _ - SessionStateType.Custom, _ - connectionString) -' - -' -' Remove a custom session state database. -SqlServices.UninstallSessionState(database, _ - SessionStateType.Custom, _ - connectionString) -' - -' -' Install temporary session state. -SqlServices.InstallSessionState(server, Nothing, _ - SessionStateType.Temporary) -' - -' -' Remove temporary session state. -SqlServices.UninstallSessionState(server, Nothing, _ - SessionStateType.Temporary) -' - -' -' Install persisted session state. -SqlServices.InstallSessionState(server, user, password, _ - Nothing, SessionStateType.Persisted) -' - -' -' Remove persisted session state. -SqlServices.UninstallSessionState(server, user, password, _ - Nothing, SessionStateType.Persisted) -' - Catch sqlExecutionException As SqlExecutionException -' -Console.WriteLine( _ - "An SQL execution exception occurred.") -Console.WriteLine() -' -Console.WriteLine(" Message: {0}", _ - sqlExecutionException.Message) -' -' -Console.WriteLine(" Server: {0}", _ - sqlExecutionException.Server) -' -' -Console.WriteLine(" Database: {0}", _ - sqlExecutionException.Database) -' -' -Console.WriteLine(" Commands: {0}", _ - sqlExecutionException.Commands) -' -' -Console.WriteLine(" SqlFile: {0}", _ - sqlExecutionException.SqlFile) -' -' -Console.WriteLine(" Inner Exception: {0}", _ - sqlExecutionException.Exception) -' -' - Catch ex As Exception -Console.WriteLine("An unknown exception occurred.") -Console.WriteLine() -Console.WriteLine(" Message: {0}", ex.Message) - End Try - End Sub -End Module -' diff --git a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/Project.vbproj b/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/Project.vbproj new file mode 100644 index 00000000000..007962c868f --- /dev/null +++ b/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/Project.vbproj @@ -0,0 +1,14 @@ + + + + Library + net481 + + + + + + + + + diff --git a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovider.vb b/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovider.vb index b7be60d0ed7..b7af1e35dca 100644 --- a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovider.vb +++ b/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovider.vb @@ -1,18 +1,13 @@ -Imports System.Web.Security +Imports System.Collections.Specialized +Imports System.Configuration Imports System.Configuration.Provider -Imports System.Collections.Specialized -Imports System.Data Imports System.Data.Odbc -Imports System.Configuration -Imports System.Diagnostics -Imports System.Web -Imports System.Globalization -Imports System.Web.Configuration Imports System.Security.Cryptography Imports System.Text +Imports System.Web.Configuration +Imports System.Web.Security -' ' This provider works with the following schema for the table of user data. ' ' CREATE TABLE Users @@ -38,308 +33,300 @@ Imports System.Text ' FailedPasswordAnswerAttemptCount Integer, ' FailedPasswordAnswerAttemptWindowStart DateTime ' ) -' - Namespace Samples.AspNet.Membership - Public NotInheritable Class OdbcMembershipProvider - Inherits MembershipProvider - + Public NotInheritable Class OdbcMembershipProvider + Inherits MembershipProvider + + + Private newPasswordLength As Integer = 8 + + ' + ' Used when determining encryption key values. + ' + + Private machineKey As MachineKeySection + + + ' + ' Database connection string. + ' + + Private pConnectionStringSettings As ConnectionStringSettings + + Public ReadOnly Property ConnectionString As String + Get + Return pConnectionStringSettings.ConnectionString + End Get + End Property + + + ' + ' System.Configuration.Provider.ProviderBase.Initialize Method + ' + + Public Overrides Sub Initialize(name As String, config As NameValueCollection) + + ' + ' Initialize values from web.config. + ' + + If config Is Nothing Then _ + Throw New ArgumentNullException("config") + + If name Is Nothing OrElse name.Length = 0 Then _ + name = "OdbcMembershipProvider" + + If String.IsNullOrEmpty(config("description")) Then + config.Remove("description") + config.Add("description", "Sample ODBC Membership provider") + End If + + ' Initialize the abstract base class. + MyBase.Initialize(name, config) + + + pApplicationName = GetConfigValue(config("applicationName"), + System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath) + pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config("maxInvalidPasswordAttempts"), "5")) + pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config("passwordAttemptWindow"), "10")) + pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config("minRequiredAlphaNumericCharacters"), "1")) + pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config("minRequiredPasswordLength"), "7")) + pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config("passwordStrengthRegularExpression"), "")) + pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config("enablePasswordReset"), "True")) + pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config("enablePasswordRetrieval"), "True")) + pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config("requiresQuestionAndAnswer"), "False")) + pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config("requiresUniqueEmail"), "True")) + + Dim temp_format As String = config("passwordFormat") + If temp_format Is Nothing Then + temp_format = "Hashed" + End If + + Select Case temp_format + Case "Hashed" + pPasswordFormat = MembershipPasswordFormat.Hashed + Case "Encrypted" + pPasswordFormat = MembershipPasswordFormat.Encrypted + Case "Clear" + pPasswordFormat = MembershipPasswordFormat.Clear + Case Else + Throw New ProviderException("Password format not supported.") + End Select + ' + ' Initialize OdbcConnection. + ' + + pConnectionStringSettings = ConfigurationManager.ConnectionStrings(config("connectionStringName")) + + If pConnectionStringSettings Is Nothing OrElse pConnectionStringSettings.ConnectionString.Trim() = "" Then + Throw New ProviderException("Connection string cannot be blank.") + End If + + + ' Get encryption and decryption key information from the configuration. + Dim cfg As System.Configuration.Configuration = + WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath) + machineKey = CType(cfg.GetSection("system.web/machineKey"), MachineKeySection) + End Sub - Private newPasswordLength As Integer = 8 + ' + ' A helper function to retrieve config values from the configuration file. + ' - ' - ' Used when determining encryption key values. - ' + Private Function GetConfigValue(configValue As String, defaultValue As String) As String + If configValue Is Nothing OrElse configValue.Trim() = "" Then _ + Return defaultValue - Private machineKey As MachineKeySection + Return configValue + End Function - + ' + ' System.Web.Security.MembershipProvider properties. + ' + Private pRequiresUniqueEmail As Boolean - ' - ' Database connection string. - ' + Public Overrides ReadOnly Property RequiresUniqueEmail As Boolean + Get + Return pRequiresUniqueEmail + End Get + End Property - Private pConnectionStringSettings As ConnectionStringSettings + Private pMaxInvalidPasswordAttempts As Integer - Public ReadOnly Property ConnectionString As String - Get - Return pConnectionStringSettings.ConnectionString - End Get - End Property + Public Overrides ReadOnly Property MaxInvalidPasswordAttempts As Integer + Get + Return pMaxInvalidPasswordAttempts + End Get + End Property + Private pPasswordAttemptWindow As Integer + Public Overrides ReadOnly Property PasswordAttemptWindow As Integer + Get + Return pPasswordAttemptWindow + End Get + End Property + Private pPasswordFormat As MembershipPasswordFormat + Public Overrides ReadOnly Property PasswordFormat As MembershipPasswordFormat + Get + Return pPasswordFormat + End Get + End Property - ' - ' System.Configuration.Provider.ProviderBase.Initialize Method - ' + Private pMinRequiredNonAlphanumericCharacters As Integer -Public Overrides Sub Initialize(name As String, config As NameValueCollection) - - ' - ' Initialize values from web.config. - ' + Public Overrides ReadOnly Property MinRequiredNonAlphanumericCharacters() As Integer + Get + Return pMinRequiredNonAlphanumericCharacters + End Get + End Property - If config Is Nothing Then _ - Throw New ArgumentNullException("config") + Private pMinRequiredPasswordLength As Integer - If name Is Nothing OrElse name.Length = 0 Then _ - name = "OdbcMembershipProvider" + Public Overrides ReadOnly Property MinRequiredPasswordLength() As Integer + Get + Return pMinRequiredPasswordLength + End Get + End Property - If String.IsNullOrEmpty(config("description")) Then - config.Remove("description") - config.Add("description", "Sample ODBC Membership provider") - End If + Private pPasswordStrengthRegularExpression As String - ' Initialize the abstract base class. - MyBase.Initialize(name, config) + Public Overrides ReadOnly Property PasswordStrengthRegularExpression() As String + Get + Return pPasswordStrengthRegularExpression + End Get + End Property + ' + Private pApplicationName As String - pApplicationName = GetConfigValue(config("applicationName"), _ - System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath) - pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config("maxInvalidPasswordAttempts"), "5")) - pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config("passwordAttemptWindow"), "10")) - pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config("minRequiredAlphaNumericCharacters"), "1")) - pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config("minRequiredPasswordLength"), "7")) - pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config("passwordStrengthRegularExpression"), "")) - pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config("enablePasswordReset"), "True")) - pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config("enablePasswordRetrieval"), "True")) - pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config("requiresQuestionAndAnswer"), "False")) - pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config("requiresUniqueEmail"), "True")) + Public Overrides Property ApplicationName As String + Get + Return pApplicationName + End Get + Set + pApplicationName = Value + End Set + End Property + ' - Dim temp_format As String = config("passwordFormat") - If temp_format Is Nothing Then - temp_format = "Hashed" - End If + ' + Private pEnablePasswordReset As Boolean - Select Case temp_format - Case "Hashed" - pPasswordFormat = MembershipPasswordFormat.Hashed - Case "Encrypted" - pPasswordFormat = MembershipPasswordFormat.Encrypted - Case "Clear" - pPasswordFormat = MembershipPasswordFormat.Clear - Case Else - Throw New ProviderException("Password format not supported.") - End Select - ' - ' Initialize OdbcConnection. - ' + Public Overrides ReadOnly Property EnablePasswordReset As Boolean + Get + Return pEnablePasswordReset + End Get + End Property + ' - pConnectionStringSettings = ConfigurationManager.ConnectionStrings(config("connectionStringName")) + ' + Private pEnablePasswordRetrieval As Boolean - If pConnectionStringSettings Is Nothing OrElse pConnectionStringSettings.ConnectionString.Trim() = "" Then - Throw New ProviderException("Connection string cannot be blank.") - End If + Public Overrides ReadOnly Property EnablePasswordRetrieval As Boolean + Get + Return pEnablePasswordRetrieval + End Get + End Property + ' - ' Get encryption and decryption key information from the configuration. - Dim cfg As System.Configuration.Configuration = _ - WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath) - machineKey = CType(cfg.GetSection("system.web/machineKey"), MachineKeySection) -End Sub + ' + Private pRequiresQuestionAndAnswer As Boolean - ' - ' A helper function to retrieve config values from the configuration file. - ' + Public Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean + Get + Return pRequiresQuestionAndAnswer + End Get + End Property + ' - Private Function GetConfigValue(configValue As String, defaultValue As String) As String - If configValue Is Nothing OrElse configValue.Trim() = "" Then _ - Return defaultValue - Return configValue - End Function + ' + ' System.Web.Security.MembershipProvider methods. + ' + ' + ' MembershipProvider.ChangePassword + ' + + ' + Public Overrides Function ChangePassword(username As String, + oldPwd As String, + newPwd As String) As Boolean + + If Not ValidateUser(username, oldPwd) Then + Return False + End If - ' - ' System.Web.Security.MembershipProvider properties. - ' - - Private pRequiresUniqueEmail As Boolean - - Public Overrides ReadOnly Property RequiresUniqueEmail As Boolean - Get - Return pRequiresUniqueEmail - End Get - End Property - - Private pMaxInvalidPasswordAttempts As Integer - - Public Overrides ReadOnly Property MaxInvalidPasswordAttempts As Integer - Get - Return pMaxInvalidPasswordAttempts - End Get - End Property - - Private pPasswordAttemptWindow As Integer - - Public Overrides ReadOnly Property PasswordAttemptWindow As Integer - Get - Return pPasswordAttemptWindow - End Get - End Property - - Private pPasswordFormat As MembershipPasswordFormat - - Public Overrides ReadOnly Property PasswordFormat As MembershipPasswordFormat - Get - Return pPasswordFormat - End Get - End Property - - Private pMinRequiredNonAlphanumericCharacters As Integer - - Public Overrides ReadOnly Property MinRequiredNonAlphanumericCharacters() As Integer - Get - Return pMinRequiredNonAlphanumericCharacters - End Get - End Property - - Private pMinRequiredPasswordLength As Integer - - Public Overrides ReadOnly Property MinRequiredPasswordLength() As Integer - Get - Return pMinRequiredPasswordLength - End Get - End Property - - Private pPasswordStrengthRegularExpression As String - - Public Overrides ReadOnly Property PasswordStrengthRegularExpression() As String - Get - Return pPasswordStrengthRegularExpression - End Get - End Property - -' -Private pApplicationName As String - -Public Overrides Property ApplicationName As String - Get - Return pApplicationName - End Get - Set - pApplicationName = value - End Set -End Property -' - -' -Private pEnablePasswordReset As Boolean - -Public Overrides ReadOnly Property EnablePasswordReset As Boolean - Get - Return pEnablePasswordReSet - End Get -End Property -' - -' -Private pEnablePasswordRetrieval As Boolean - -Public Overrides ReadOnly Property EnablePasswordRetrieval As Boolean - Get - Return pEnablePasswordRetrieval - End Get -End Property -' - - -' -Private pRequiresQuestionAndAnswer As Boolean - -Public Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean - Get - Return pRequiresQuestionAndAnswer - End Get -End Property -' - - - ' - ' System.Web.Security.MembershipProvider methods. - ' - - ' - ' MembershipProvider.ChangePassword - ' - -' -Public Overrides Function ChangePassword(username As String, _ - oldPwd As String, _ - newPwd As String) As Boolean - - If Not ValidateUser(username, oldPwd) Then - Return False - End If - - Dim args As ValidatePasswordEventArgs = _ - New ValidatePasswordEventArgs(username, newPwd, True) - - OnValidatingPassword(args) - - If args.Cancel Then - If Not args.FailureInformation Is Nothing Then - Throw args.FailureInformation - Else - Throw New MembershipPasswordException("Change password canceled due to New password validation failure.") - End If - End If - - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET Password = ?, LastPasswordChangedDate = ? " & _ + Dim args As ValidatePasswordEventArgs = + New ValidatePasswordEventArgs(username, newPwd, True) + + OnValidatingPassword(args) + + If args.Cancel Then + If Not args.FailureInformation Is Nothing Then + Throw args.FailureInformation + Else + Throw New MembershipPasswordException("Change password canceled due to New password validation failure.") + End If + End If + + + Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) + Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & + " SET Password = ?, LastPasswordChangedDate = ? " & " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn) - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = EncodePassword(newPwd) - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@OldPassword", OdbcType.VarChar, 128).Value = oldPwd - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName + cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = EncodePassword(newPwd) + cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now + cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username + cmd.Parameters.Add("@OldPassword", OdbcType.VarChar, 128).Value = oldPwd + cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - Dim rowsAffected As Integer = 0 + Dim rowsAffected As Integer = 0 - Try - conn.Open() + Try + conn.Open() - rowsAffected = cmd.ExecuteNonQuery() - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try + rowsAffected = cmd.ExecuteNonQuery() + Catch e As OdbcException + ' Handle exception. + Finally + conn.Close() + End Try - If rowsAffected > 0 Then Return True + If rowsAffected > 0 Then Return True - Return False -End Function -' + Return False + End Function + ' - ' - ' MembershipProvider.ChangePasswordQuestionAndAnswer - ' + ' + ' MembershipProvider.ChangePasswordQuestionAndAnswer + ' + + ' + Public Overrides Function ChangePasswordQuestionAndAnswer(username As String, + password As String, + newPwdQuestion As String, + newPwdAnswer As String) _ + As Boolean -' -Public Overrides Function ChangePasswordQuestionAndAnswer(username As String, _ - password As String, _ - newPwdQuestion As String, _ - newPwdAnswer As String) _ - As Boolean - - If Not ValidateUser(username, password) Then Return False + If Not ValidateUser(username, password) Then Return False - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET PasswordQuestion = ?, PasswordAnswer = ?" & _ + Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) + Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & + " SET PasswordQuestion = ?, PasswordAnswer = ?" & " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@Question", OdbcType.VarChar, 255).Value = newPwdQuestion @@ -375,21 +362,21 @@ Public Overrides Function ChangePasswordQuestionAndAnswer(username As String, _ ' ' - Public Overrides Function CreateUser(ByVal username As String, _ - ByVal password As String, _ - ByVal email As String, _ - ByVal passwordQuestion As String, _ - ByVal passwordAnswer As String, _ - ByVal isApproved As Boolean, _ - ByVal providerUserKey As Object, _ + Public Overrides Function CreateUser(ByVal username As String, + ByVal password As String, + ByVal email As String, + ByVal passwordQuestion As String, + ByVal passwordAnswer As String, + ByVal isApproved As Boolean, + ByVal providerUserKey As Object, ByRef status As MembershipCreateStatus) As MembershipUser - Dim Args As ValidatePasswordEventArgs = _ + Dim Args As ValidatePasswordEventArgs = New ValidatePasswordEventArgs(username, password, True) - OnValidatingPassword(args) + OnValidatingPassword(Args) - If args.Cancel Then + If Args.Cancel Then status = MembershipCreateStatus.InvalidPassword Return Nothing End If @@ -415,13 +402,13 @@ Public Overrides Function ChangePasswordQuestionAndAnswer(username As String, _ End If Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("INSERT INTO Users " & _ - " (PKID, Username, Password, Email, PasswordQuestion, " & _ - " PasswordAnswer, IsApproved," & _ - " Comment, CreationDate, LastPasswordChangedDate, LastActivityDate," & _ - " ApplicationName, IsLockedOut, LastLockedOutDate," & _ - " FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, " & _ - " FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart)" & _ + Dim cmd As OdbcCommand = New OdbcCommand("INSERT INTO Users " & + " (PKID, Username, Password, Email, PasswordQuestion, " & + " PasswordAnswer, IsApproved," & + " Comment, CreationDate, LastPasswordChangedDate, LastActivityDate," & + " ApplicationName, IsLockedOut, LastLockedOutDate," & + " FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, " & + " FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart)" & " Values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", conn) cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey @@ -469,19 +456,19 @@ Public Overrides Function ChangePasswordQuestionAndAnswer(username As String, _ Return Nothing End Function -' + ' - ' - ' MembershipProvider.DeleteUser - ' + ' + ' MembershipProvider.DeleteUser + ' -' -Public Overrides Function DeleteUser(username As String, deleteAllRelatedData As Boolean) As Boolean + ' + Public Overrides Function DeleteUser(username As String, deleteAllRelatedData As Boolean) As Boolean - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("DELETE FROM Users " & _ + Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) + Dim cmd As OdbcCommand = New OdbcCommand("DELETE FROM Users " & " WHERE Username = ? AND Applicationname = ?", conn) cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username @@ -518,13 +505,13 @@ Public Overrides Function DeleteUser(username As String, deleteAllRelatedData As ' - Public Overrides Function GetAllUsers(ByVal pageIndex As Integer, _ - ByVal pageSize As Integer, _ + Public Overrides Function GetAllUsers(ByVal pageIndex As Integer, + ByVal pageSize As Integer, ByRef totalRecords As Integer) _ As MembershipUserCollection Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & _ + Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & "WHERE ApplicationName = ?", conn) cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName @@ -539,11 +526,11 @@ Public Overrides Function DeleteUser(username As String, deleteAllRelatedData As If totalRecords <= 0 Then Return users - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate " & _ - " FROM Users " & _ - " WHERE ApplicationName = ? " & _ + cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & + " Comment, IsApproved, CreationDate, LastLoginDate," & + " LastActivityDate, LastPasswordChangedDate " & + " FROM Users " & + " WHERE ApplicationName = ? " & " ORDER BY Username Asc" reader = cmd.ExecuteReader() @@ -588,7 +575,7 @@ Public Overrides Function DeleteUser(username As String, deleteAllRelatedData As Dim compareTime As DateTime = DateTime.Now.Subtract(onlineSpan) Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & _ + Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & " WHERE LastActivityDate > ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@CompareDate", OdbcType.DateTime).Value = compareTime @@ -608,28 +595,28 @@ Public Overrides Function DeleteUser(username As String, deleteAllRelatedData As Return numOnline End Function -' + ' - ' - ' MembershipProvider.GetPassword - ' + ' + ' MembershipProvider.GetPassword + ' -' -Public Overrides Function GetPassword(username As String, answer As String) As String - - If Not EnablePasswordRetrieval Then - Throw New ProviderException("Password Retrieval Not Enabled.") - End If + ' + Public Overrides Function GetPassword(username As String, answer As String) As String - If PasswordFormat = MembershipPasswordFormat.Hashed Then - Throw New ProviderException("Cannot retrieve Hashed passwords.") - End If + If Not EnablePasswordRetrieval Then + Throw New ProviderException("Password Retrieval Not Enabled.") + End If - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Password, PasswordAnswer, IsLockedOut FROM Users " & _ + If PasswordFormat = MembershipPasswordFormat.Hashed Then + Throw New ProviderException("Cannot retrieve Hashed passwords.") + End If + + Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) + Dim cmd As OdbcCommand = New OdbcCommand("SELECT Password, PasswordAnswer, IsLockedOut FROM Users " & " WHERE Username = ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username @@ -688,9 +675,9 @@ Public Overrides Function GetPassword(username As String, answer As String) As S Public Overrides Function GetUser(ByVal username As String, ByVal userIsOnline As Boolean) As MembershipUser Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" & _ + Dim cmd As OdbcCommand = New OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," & + " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," & + " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" & " FROM Users WHERE Username = ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username @@ -709,8 +696,8 @@ Public Overrides Function GetPassword(username As String, answer As String) As S u = GetUserFromReader(reader) If userIsOnline Then - Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - "SET LastActivityDate = ? " & _ + Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users " & + "SET LastActivityDate = ? " & "WHERE Username = ? AND Applicationname = ?", conn) updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now @@ -768,18 +755,18 @@ Public Overrides Function GetPassword(username As String, answer As String) As S If Not reader.GetValue(11) Is DBNull.Value Then _ lastLockedOutDate = reader.GetDateTime(11) - Dim u As MembershipUser = New MembershipUser(Me.Name, _ - username, _ - providerUserKey, _ - email, _ - passwordQuestion, _ - comment, _ - isApproved, _ - isLockedOut, _ - creationDate, _ - lastLoginDate, _ - lastActivityDate, _ - lastPasswordChangedDate, _ + Dim u As MembershipUser = New MembershipUser(Me.Name, + username, + providerUserKey, + email, + passwordQuestion, + comment, + isApproved, + isLockedOut, + creationDate, + lastLoginDate, + lastActivityDate, + lastPasswordChangedDate, lastLockedOutDate) Return u @@ -796,7 +783,7 @@ Public Overrides Function GetPassword(username As String, answer As String) As S Public Overrides Function GetUserNameByEmail(ByVal email As String) As String Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Username" & _ + Dim cmd As OdbcCommand = New OdbcCommand("SELECT Username" & " FROM Users WHERE Email = ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email @@ -816,50 +803,50 @@ Public Overrides Function GetPassword(username As String, answer As String) As S Return username End Function -' + ' + + + ' + ' MembershipProvider.ResetPassword + ' - ' - ' MembershipProvider.ResetPassword - ' + ' + Public Overrides Function ResetPassword(username As String, answer As String) As String + If Not EnablePasswordReset Then + Throw New NotSupportedException("Password Reset is not enabled.") + End If -' -Public Overrides Function ResetPassword(username As String, answer As String) As String - - If Not EnablePasswordReset Then - Throw New NotSupportedException("Password Reset is not enabled.") - End If + If answer Is Nothing AndAlso RequiresQuestionAndAnswer Then + UpdateFailureCount(username, "passwordAnswer") - If answer Is Nothing AndAlso RequiresQuestionAndAnswer Then - UpdateFailureCount(username, "passwordAnswer") + Throw New ProviderException("Password answer required for password Reset.") + End If - Throw New ProviderException("Password answer required for password Reset.") - End If + Dim newPassword As String = + System.Web.Security.Membership.GeneratePassword(newPasswordLength, pMinRequiredNonAlphanumericCharacters) - Dim newPassword As String = _ - System.Web.Security.Membership.GeneratePassword(newPasswordLength, pMinRequiredNonAlphanumericCharacters) + Dim Args As ValidatePasswordEventArgs = + New ValidatePasswordEventArgs(username, newPassword, True) - Dim Args As ValidatePasswordEventArgs = _ - New ValidatePasswordEventArgs(username, newPassword, True) + OnValidatingPassword(Args) - OnValidatingPassword(args) - - If args.Cancel Then - If Not args.FailureInformation Is Nothing Then - Throw args.FailureInformation - Else - Throw New MembershipPasswordException("Reset password canceled due to password validation failure.") - End If - End If + If Args.Cancel Then + If Not Args.FailureInformation Is Nothing Then + Throw Args.FailureInformation + Else + Throw New MembershipPasswordException("Reset password canceled due to password validation failure.") + End If + End If - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT PasswordAnswer, IsLockedOut FROM Users " & _ + Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) + Dim cmd As OdbcCommand = New OdbcCommand("SELECT PasswordAnswer, IsLockedOut FROM Users " & " WHERE Username = ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username @@ -891,8 +878,8 @@ Public Overrides Function ResetPassword(username As String, answer As String) As Throw New MembershipPasswordException("Incorrect password answer.") End If - Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET Password = ?, LastPasswordChangedDate = ?" & _ + Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users " & + " SET Password = ?, LastPasswordChangedDate = ?" & " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn) updateCmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(newPassword) @@ -908,27 +895,27 @@ Public Overrides Function ResetPassword(username As String, answer As String) As conn.Close() End Try - If rowsAffected > 0 Then - Return newPassword - Else - Throw New MembershipPasswordException("User not found, or user is locked out. Password not Reset.") - End If -End Function -' + If rowsAffected > 0 Then + Return newPassword + Else + Throw New MembershipPasswordException("User not found, or user is locked out. Password not Reset.") + End If + End Function + ' - ' - ' MembershipProvider.UpdateUser - ' + ' + ' MembershipProvider.UpdateUser + ' -' -Public Overrides Sub UpdateUser(user As MembershipUser) + ' + Public Overrides Sub UpdateUser(user As MembershipUser) - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET Email = ?, Comment = ?," & _ - " IsApproved = ?" & _ + Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) + Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & + " SET Email = ?, Comment = ?," & + " IsApproved = ?" & " WHERE Username = ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = user.Email @@ -962,7 +949,7 @@ Public Overrides Sub UpdateUser(user As MembershipUser) Dim isValid As Boolean = False Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Password, IsApproved FROM Users " & _ + Dim cmd As OdbcCommand = New OdbcCommand("SELECT Password, IsApproved FROM Users " & " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn) cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username @@ -988,7 +975,7 @@ Public Overrides Sub UpdateUser(user As MembershipUser) If isApproved AndAlso (password = pwd) Then isValid = True - Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users SET LastLoginDate = ?" & _ + Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users SET LastLoginDate = ?" & " WHERE Username = ? AND ApplicationName = ?", conn) updateCmd.Parameters.Add("@LastLoginDate", OdbcType.DateTime).Value = DateTime.Now @@ -1009,14 +996,14 @@ Public Overrides Sub UpdateUser(user As MembershipUser) ' - Public Overrides Function FindUsersByName(ByVal usernameToMatch As String, _ - ByVal pageIndex As Integer, _ - ByVal pageSize As Integer, _ + Public Overrides Function FindUsersByName(ByVal usernameToMatch As String, + ByVal pageIndex As Integer, + ByVal pageSize As Integer, ByRef totalRecords As Integer) _ As MembershipUserCollection Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & _ + Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & "WHERE Username LIKE ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@UsernameSearch", OdbcType.VarChar, 255).Value = usernameToMatch cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName @@ -1032,11 +1019,11 @@ Public Overrides Sub UpdateUser(user As MembershipUser) If totalRecords <= 0 Then Return users - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate " & _ - " FROM Users " & _ - " WHERE Username LIKE ? AND ApplicationName = ? " & _ + cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & + " Comment, IsApproved, CreationDate, LastLoginDate," & + " LastActivityDate, LastPasswordChangedDate " & + " FROM Users " & + " WHERE Username LIKE ? AND ApplicationName = ? " & " ORDER BY Username Asc" reader = cmd.ExecuteReader() @@ -1066,14 +1053,14 @@ Public Overrides Sub UpdateUser(user As MembershipUser) End Function - Public Overrides Function FindUsersByEmail(ByVal emailToMatch As String, _ - ByVal pageIndex As Integer, _ - ByVal pageSize As Integer, _ + Public Overrides Function FindUsersByEmail(ByVal emailToMatch As String, + ByVal pageIndex As Integer, + ByVal pageSize As Integer, ByRef totalRecords As Integer) _ As MembershipUserCollection Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & _ + Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & "WHERE Email LIKE ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@EmailSearch", OdbcType.VarChar, 255).Value = emailToMatch cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName @@ -1089,11 +1076,11 @@ Public Overrides Sub UpdateUser(user As MembershipUser) If totalRecords <= 0 Then Return users - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate " & _ - " FROM Users " & _ - " WHERE Email LIKE ? AND ApplicationName = ? " & _ + cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & + " Comment, IsApproved, CreationDate, LastLoginDate," & + " LastActivityDate, LastPasswordChangedDate " & + " FROM Users " & + " WHERE Email LIKE ? AND ApplicationName = ? " & " ORDER BY Username Asc" reader = cmd.ExecuteReader() @@ -1128,8 +1115,8 @@ Public Overrides Sub UpdateUser(user As MembershipUser) Public Overrides Function UnlockUser(ByVal username As String) As Boolean Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET IsLockedOut = False, LastLockedOutDate = ? " & _ + Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & + " SET IsLockedOut = False, LastLockedOutDate = ? " & " WHERE Username = ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now @@ -1155,17 +1142,17 @@ Public Overrides Sub UpdateUser(user As MembershipUser) End Function -' -' MembershipProvider.GetUser(Object, Boolean) -' + ' + ' MembershipProvider.GetUser(Object, Boolean) + ' + + Public Overrides Function GetUser(providerUserKey As Object, + userIsOnline As Boolean) As MembershipUser -Public Overrides Function GetUser(providerUserKey As Object, _ - userIsOnline As Boolean) As MembershipUser - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" & _ + Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) + Dim cmd As OdbcCommand = New OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," & + " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," & + " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" & " FROM Users WHERE PKID = ?", conn) cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey @@ -1183,8 +1170,8 @@ Public Overrides Function GetUser(providerUserKey As Object, _ u = GetUserFromReader(reader) If userIsOnline Then - Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - "SET LastActivityDate = ? " & _ + Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users " & + "SET LastActivityDate = ? " & "WHERE PKID = ?", conn) updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now @@ -1200,24 +1187,24 @@ Public Overrides Function GetUser(providerUserKey As Object, _ conn.Close() End Try - Return u -End Function + Return u + End Function + + ' + ' UpdateFailureCount + ' A helper method that performs the checks and updates associated with + ' password failure tracking. + ' - ' - ' UpdateFailureCount - ' A helper method that performs the checks and updates associated with - ' password failure tracking. - ' + Private Sub UpdateFailureCount(username As String, failureType As String) - Private Sub UpdateFailureCount(username As String, failureType As String) - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT FailedPasswordAttemptCount, " & _ - " FailedPasswordAttemptWindowStart, " & _ - " FailedPasswordAnswerAttemptCount, " & _ - " FailedPasswordAnswerAttemptWindowStart " & _ - " FROM Users " & _ + Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) + Dim cmd As OdbcCommand = New OdbcCommand("SELECT FailedPasswordAttemptCount, " & + " FailedPasswordAttemptWindowStart, " & + " FailedPasswordAnswerAttemptCount, " & + " FailedPasswordAnswerAttemptWindowStart " & + " FROM Users " & " WHERE Username = ? AND ApplicationName = ?", conn) cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username @@ -1255,15 +1242,15 @@ End Function ' Start a New password failure count from 1 and a New window starting now. If failureType = "password" Then _ - cmd.CommandText = "UPDATE Users " & _ - " SET FailedPasswordAttemptCount = ?, " & _ - " FailedPasswordAttemptWindowStart = ? " & _ + cmd.CommandText = "UPDATE Users " & + " SET FailedPasswordAttemptCount = ?, " & + " FailedPasswordAttemptWindowStart = ? " & " WHERE Username = ? AND ApplicationName = ?" If failureType = "passwordAnswer" Then _ - cmd.CommandText = "UPDATE Users " & _ - " SET FailedPasswordAnswerAttemptCount = ?, " & _ - " FailedPasswordAnswerAttemptWindowStart = ? " & _ + cmd.CommandText = "UPDATE Users " & + " SET FailedPasswordAnswerAttemptCount = ?, " & + " FailedPasswordAnswerAttemptWindowStart = ? " & " WHERE Username = ? AND ApplicationName = ?" cmd.Parameters.Clear() @@ -1282,8 +1269,8 @@ End Function ' Password attempts have exceeded the failure threshold. Lock out ' the user. - cmd.CommandText = "UPDATE Users " & _ - " SET IsLockedOut = ?, LastLockedOutDate = ? " & _ + cmd.CommandText = "UPDATE Users " & + " SET IsLockedOut = ?, LastLockedOutDate = ? " & " WHERE Username = ? AND ApplicationName = ?" cmd.Parameters.Clear() @@ -1300,13 +1287,13 @@ End Function ' the failure counts. Leave the window the same. If failureType = "password" Then _ - cmd.CommandText = "UPDATE Users " & _ - " SET FailedPasswordAttemptCount = ?" & _ + cmd.CommandText = "UPDATE Users " & + " SET FailedPasswordAttemptCount = ?" & " WHERE Username = ? AND ApplicationName = ?" If failureType = "passwordAnswer" Then _ - cmd.CommandText = "UPDATE Users " & _ - " SET FailedPasswordAnswerAttemptCount = ?" & _ + cmd.CommandText = "UPDATE Users " & + " SET FailedPasswordAnswerAttemptCount = ?" & " WHERE Username = ? AND ApplicationName = ?" cmd.Parameters.Clear() @@ -1325,99 +1312,99 @@ End Function If Not reader Is Nothing Then reader.Close() conn.Close() End Try - End Sub - - - ' - ' CheckPassword - ' Compares password values based on the MembershipPasswordFormat. - ' - - Private Function CheckPassword(password As String, dbpassword As String) As Boolean - Dim pass1 As String = password - Dim pass2 As String = dbpassword + End Sub - Select Case PasswordFormat - Case MembershipPasswordFormat.Encrypted - pass2 = UnEncodePassword(dbpassword) - Case MembershipPasswordFormat.Hashed - pass1 = EncodePassword(password) - Case Else - End Select - If pass1 = pass2 Then - Return True - End If + ' + ' CheckPassword + ' Compares password values based on the MembershipPasswordFormat. + ' - Return False - End Function + Private Function CheckPassword(password As String, dbpassword As String) As Boolean + Dim pass1 As String = password + Dim pass2 As String = dbpassword + Select Case PasswordFormat + Case MembershipPasswordFormat.Encrypted + pass2 = UnEncodePassword(dbpassword) + Case MembershipPasswordFormat.Hashed + pass1 = EncodePassword(password) + Case Else + End Select - ' - ' EncodePassword - ' Encrypts, Hashes, or leaves the password clear based on the PasswordFormat. - ' + If pass1 = pass2 Then + Return True + End If - Private Function EncodePassword(password As String) As String - Dim encodedPassword As String = password + Return False + End Function - Select Case PasswordFormat - Case MembershipPasswordFormat.Clear - Case MembershipPasswordFormat.Encrypted - encodedPassword = _ - Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))) - Case MembershipPasswordFormat.Hashed - Dim hash As HMACSHA256 = New HMACSHA256() - hash.Key = HexToByte(machineKey.ValidationKey) - encodedPassword = _ - Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))) - Case Else - Throw New ProviderException("Unsupported password format.") - End Select + ' + ' EncodePassword + ' Encrypts, Hashes, or leaves the password clear based on the PasswordFormat. + ' - Return encodedPassword - End Function + Private Function EncodePassword(password As String) As String + Dim encodedPassword As String = password + + Select Case PasswordFormat + Case MembershipPasswordFormat.Clear + + Case MembershipPasswordFormat.Encrypted + encodedPassword = + Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))) + Case MembershipPasswordFormat.Hashed + Dim hash As HMACSHA256 = New HMACSHA256() + hash.Key = HexToByte(machineKey.ValidationKey) + encodedPassword = + Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))) + Case Else + Throw New ProviderException("Unsupported password format.") + End Select + + Return encodedPassword + End Function - ' - ' UnEncodePassword - ' Decrypts or leaves the password clear based on the PasswordFormat. - ' + ' + ' UnEncodePassword + ' Decrypts or leaves the password clear based on the PasswordFormat. + ' - Private Function UnEncodePassword(encodedPassword As String) As String - Dim password As String = encodedPassword + Private Function UnEncodePassword(encodedPassword As String) As String + Dim password As String = encodedPassword - Select Case PasswordFormat - Case MembershipPasswordFormat.Clear + Select Case PasswordFormat + Case MembershipPasswordFormat.Clear - Case MembershipPasswordFormat.Encrypted - password = _ - Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))) - Case MembershipPasswordFormat.Hashed - Throw New ProviderException("Cannot unencode a hashed password.") - Case Else - throw new ProviderException("Unsupported password format.") - End Select + Case MembershipPasswordFormat.Encrypted + password = + Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))) + Case MembershipPasswordFormat.Hashed + Throw New ProviderException("Cannot unencode a hashed password.") + Case Else + Throw New ProviderException("Unsupported password format.") + End Select - Return password - End Function + Return password + End Function - ' - ' HexToByte - ' Converts a hexadecimal string to a byte array. Used to convert encryption - ' key values from the configuration. - ' + ' + ' HexToByte + ' Converts a hexadecimal string to a byte array. Used to convert encryption + ' key values from the configuration. + ' - Private Function HexToByte(hexString As String) As Byte() - Dim ReturnBytes((hexString.Length \ 2) - 1) As Byte - For i As Integer = 0 To ReturnBytes.Length - 1 - ReturnBytes(i) = Convert.ToByte(hexString.Substring(i*2, 2), 16) - Next - Return ReturnBytes - End Function + Private Function HexToByte(hexString As String) As Byte() + Dim ReturnBytes((hexString.Length \ 2) - 1) As Byte + For i As Integer = 0 To ReturnBytes.Length - 1 + ReturnBytes(i) = Convert.ToByte(hexString.Substring(i * 2, 2), 16) + Next + Return ReturnBytes + End Function - End Class + End Class End Namespace diff --git a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovidergetallusers.vb b/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovidergetallusers.vb deleted file mode 100644 index 1309013d98c..00000000000 --- a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovidergetallusers.vb +++ /dev/null @@ -1,1386 +0,0 @@ -Imports System.Web.Security -Imports System.Configuration.Provider -Imports System.Collections.Specialized -Imports System.Data -Imports System.Data.Odbc -Imports System.Configuration -Imports System.Diagnostics -Imports System.Web -Imports System.Globalization -Imports System.Web.Configuration -Imports System.Security.Cryptography -Imports System.Text - - -' -' This provider works with the following schema for the table of user data. -' -' CREATE TABLE Users -' ( -' PKID Guid NOT NULL PRIMARY KEY, -' Username Text (255) NOT NULL, -' ApplicationName Text (255) NOT NULL, -' Email Text (128) NOT NULL, -' Comment Text (255), -' Password Text (128) NOT NULL, -' PasswordQuestion Text (255), -' PasswordAnswer Text (128), -' IsApproved YesNo, -' LastActivityDate DateTime, -' LastLoginDate DateTime, -' LastPasswordChangedDate DateTime, -' CreationDate DateTime, -' IsOnLine YesNo, -' IsLockedOut YesNo, -' LastLockedOutDate DateTime, -' FailedPasswordAttemptCount Integer, -' FailedPasswordAttemptWindowStart DateTime, -' FailedPasswordAnswerAttemptCount Integer, -' FailedPasswordAnswerAttemptWindowStart DateTime -' ) -' - - -Namespace Samples.AspNet.Membership - - Public NotInheritable Class OdbcMembershipProvider - Inherits MembershipProvider - - - Private newPasswordLength As Integer = 8 - - ' - ' Used when determining encryption key values. - ' - - Private machineKey As MachineKeySection - - - - - - ' - ' Database connection string. - ' - - Private pConnectionStringSettings As ConnectionStringSettings - - Public ReadOnly Property ConnectionString As String - Get - Return pConnectionStringSettings.ConnectionString - End Get - End Property - - - - - - ' - ' System.Configuration.Provider.ProviderBase.Initialize Method - ' - -Public Overrides Sub Initialize(name As String, config As NameValueCollection) - - ' - ' Initialize values from web.config. - ' - - If config Is Nothing Then _ - Throw New ArgumentNullException("config") - - If name Is Nothing OrElse name.Length = 0 Then _ - name = "OdbcMembershipProvider" - - If String.IsNullOrEmpty(config("description")) Then - config.Remove("description") - config.Add("description", "Sample ODBC Membership provider") - End If - - ' Initialize the abstract base class. - MyBase.Initialize(name, config) - - - pApplicationName = GetConfigValue(config("applicationName"), _ - System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath) - pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config("maxInvalidPasswordAttempts"), "5")) - pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config("passwordAttemptWindow"), "10")) - pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config("minRequiredAlphaNumericCharacters"), "1")) - pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config("minRequiredPasswordLength"), "7")) - pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config("passwordStrengthRegularExpression"), "")) - pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config("enablePasswordReset"), "True")) - pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config("enablePasswordRetrieval"), "True")) - pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config("requiresQuestionAndAnswer"), "False")) - pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config("requiresUniqueEmail"), "True")) - - Dim temp_format As String = config("passwordFormat") - If temp_format Is Nothing Then - temp_format = "Hashed" - End If - - Select Case temp_format - Case "Hashed" - pPasswordFormat = MembershipPasswordFormat.Hashed - Case "Encrypted" - pPasswordFormat = MembershipPasswordFormat.Encrypted - Case "Clear" - pPasswordFormat = MembershipPasswordFormat.Clear - Case Else - Throw New ProviderException("Password format not supported.") - End Select - ' - ' Initialize OdbcConnection. - ' - - pConnectionStringSettings = ConfigurationManager.ConnectionStrings(config("connectionStringName")) - - If pConnectionStringSettings Is Nothing OrElse pConnectionStringSettings.ConnectionString.Trim() = "" Then - Throw New ProviderException("Connection string cannot be blank.") - End If - - - ' Get encryption and decryption key information from the configuration. - Dim cfg As System.Configuration.Configuration = _ - WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath) - machineKey = CType(cfg.GetSection("system.web/machineKey"), MachineKeySection) -End Sub - - ' - ' A helper function to retrieve config values from the configuration file. - ' - - Private Function GetConfigValue(configValue As String, defaultValue As String) As String - If configValue Is Nothing OrElse configValue.Trim() = "" Then _ - Return defaultValue - - Return configValue - End Function - - - ' - ' System.Web.Security.MembershipProvider properties. - ' - - Private pRequiresUniqueEmail As Boolean - - Public Overrides ReadOnly Property RequiresUniqueEmail As Boolean - Get - Return pRequiresUniqueEmail - End Get - End Property - - Private pMaxInvalidPasswordAttempts As Integer - - Public Overrides ReadOnly Property MaxInvalidPasswordAttempts As Integer - Get - Return pMaxInvalidPasswordAttempts - End Get - End Property - - Private pPasswordAttemptWindow As Integer - - Public Overrides ReadOnly Property PasswordAttemptWindow As Integer - Get - Return pPasswordAttemptWindow - End Get - End Property - - Private pPasswordFormat As MembershipPasswordFormat - - Public Overrides ReadOnly Property PasswordFormat As MembershipPasswordFormat - Get - Return pPasswordFormat - End Get - End Property - - Private pMinRequiredNonAlphanumericCharacters As Integer - - Public Overrides ReadOnly Property MinRequiredNonAlphanumericCharacters() As Integer - Get - Return pMinRequiredNonAlphanumericCharacters - End Get - End Property - - Private pMinRequiredPasswordLength As Integer - - Public Overrides ReadOnly Property MinRequiredPasswordLength() As Integer - Get - Return pMinRequiredPasswordLength - End Get - End Property - - Private pPasswordStrengthRegularExpression As String - - Public Overrides ReadOnly Property PasswordStrengthRegularExpression() As String - Get - Return pPasswordStrengthRegularExpression - End Get - End Property - -' -17> -Private pApplicationName As String - -Public Overrides Property ApplicationName As String - Get - Return pApplicationName - End Get - Set - pApplicationName = value - End Set -End Property -' - /17> - -' -1> -Private pEnablePasswordReset As Boolean - -Public Overrides ReadOnly Property EnablePasswordReset As Boolean - Get - Return pEnablePasswordReSet - End Get -End Property -' - /1> - -' -2> -Private pEnablePasswordRetrieval As Boolean - -Public Overrides ReadOnly Property EnablePasswordRetrieval As Boolean - Get - Return pEnablePasswordRetrieval - End Get -End Property -' - /2> - - -' -3> -Private pRequiresQuestionAndAnswer As Boolean - -Public Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean - Get - Return pRequiresQuestionAndAnswer - End Get -End Property -' - /3> - - - ' - ' System.Web.Security.MembershipProvider methods. - ' - - ' - ' MembershipProvider.ChangePassword - ' - -' -4> -Public Overrides Function ChangePassword(username As String, _ - oldPwd As String, _ - newPwd As String) As Boolean - - If Not ValidateUser(username, oldPwd) Then - Throw New MembershipPasswordException("Password validation failed.") - End If - - Dim args As ValidatePasswordEventArgs = _ - New ValidatePasswordEventArgs(username, newPwd, True) - - OnValidatingPassword(args) - - If args.Cancel Then - If Not args.FailureInformation Is Nothing Then - Throw args.FailureInformation - Else - Throw New Exception("Change password canceled due to New password validation failure.") - End If - End If - - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET Password = ?, LastPasswordChangedDate = ? " & _ - " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = newPwd - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@OldPassword", OdbcType.VarChar, 128).Value = oldPwd - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - - Dim rowsAffected As Integer = 0 - - Try - conn.Open() - - rowsAffected = cmd.ExecuteNonQuery() - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try - - If rowsAffected > 0 Then Return True - - Return False - End Function - ' - /4> - - - - ' - ' MembershipProvider.ChangePasswordQuestionAndAnswer - ' - - ' -5> - Public Overrides Function ChangePasswordQuestionAndAnswer(ByVal username As String, _ - ByVal password As String, _ - ByVal newPwdQuestion As String, _ - ByVal newPwdAnswer As String) _ - As Boolean - - If Not ValidateUser(username, password) Then Return False - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET PasswordQuestion = ?, PasswordAnswer = ?" & _ - " WHERE Username = ? AND Password = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Question", OdbcType.VarChar, 255).Value = newPwdQuestion - cmd.Parameters.Add("@Answer", OdbcType.VarChar, 128).Value = newPwdAnswer - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = password - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - - Dim rowsAffected As Integer = 0 - - Try - conn.Open() - - rowsAffected = cmd.ExecuteNonQuery() - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try - - If rowsAffected > 0 Then Return True - - Return False - End Function -' - /5> - - - - - ' - ' MembershipProvider.CreateUser - ' - -' -6> -Public Overrides Function CreateUser(username As String, _ - password As String, _ - email As String, _ - passwordQuestion As String, _ - passwordAnswer As String, _ - isApproved As Boolean, _ - providerUserKey As Object, _ - ByRef status As MembershipCreateStatus) As MembershipUser - - Dim Args As ValidatePasswordEventArgs = _ - New ValidatePasswordEventArgs(username, password, True) - - OnValidatingPassword(args) - - If args.Cancel Then - If Not args.FailureInformation Is Nothing Then - Throw args.FailureInformation - Else - Throw New Exception("Create user canceled due to password validation failure.") - End If - End If - - - If RequiresUniqueEmail AndAlso GetUserNameByEmail(email) <> "" Then - status = MembershipCreateStatus.DuplicateEmail - Return Nothing - End If - - Dim u As MembershipUser = GetUser(username, False) - - If u Is Nothing Then - Dim createDate As DateTime = DateTime.Now - - If providerUserKey Is Nothing Then - providerUserKey = Guid.NewGuid() - Else - If Not TypeOf providerUserKey Is Guid Then - status = MembershipCreateStatus.InvalidProviderUserKey - Return Nothing - End If - End If - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("INSERT INTO Users " & _ - " (PKID, Username, Password, Email, PasswordQuestion, " & _ - " PasswordAnswer, IsApproved," & _ - " Comment, CreationDate, LastPasswordChangedDate, LastActivityDate," & _ - " ApplicationName, IsLockedOut, LastLockedOutDate," & _ - " FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, " & _ - " FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart)" & _ - " Values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", conn) - - cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(password) - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email - cmd.Parameters.Add("@PasswordQuestion", OdbcType.VarChar, 255).Value = passwordQuestion - cmd.Parameters.Add("@PasswordAnswer", OdbcType.VarChar, 128).Value = passwordAnswer - cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = isApproved - cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = "" - cmd.Parameters.Add("@CreationDate", OdbcType.DateTime).Value = createDate - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = createDate - cmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = createDate - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = False - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = createDate - cmd.Parameters.Add("@FailedPasswordAttemptCount", OdbcType.Int).Value = 0 - cmd.Parameters.Add("@FailedPasswordAttemptWindowStart", OdbcType.DateTime).Value = createDate - cmd.Parameters.Add("@FailedPasswordAnswerAttemptCount", OdbcType.Int).Value = 0 - cmd.Parameters.Add("@FailedPasswordAnswerAttemptWindowStart", OdbcType.DateTime).Value = createDate - - Try - conn.Open() - - Dim recAdded As Integer = cmd.ExecuteNonQuery() - - If recAdded > 0 Then - status = MembershipCreateStatus.Success - Else - status = MembershipCreateStatus.UserRejected - End If - Catch e As OdbcException - ' Handle exception. - - status = MembershipCreateStatus.ProviderError - Finally - conn.Close() - End Try - - - Return GetUser(username, False) - Else - status = MembershipCreateStatus.DuplicateUserName - End If - - Return Nothing - End Function - ' - /6> - - - - ' - ' MembershipProvider.DeleteUser - ' - - ' -7> - Public Overrides Function DeleteUser(ByVal username As String, ByVal deleteAllRelatedData As Boolean) As Boolean - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("DELETE FROM Users " & _ - " WHERE Username = ? AND Applicationname = ?", conn) - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - - Dim rowsAffected As Integer = 0 - - Try - conn.Open() - - rowsAffected = cmd.ExecuteNonQuery() - - If deleteAllRelatedData Then - ' Process commands to delete all data for the user in the database. - End If - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try - - If rowsAffected > 0 Then Return True - - Return False - End Function -' - /7> - - - - - ' - ' MembershipProvider.GetAllUsers - ' - -' -Public Overrides Function GetAllUsers(pageIndex As Integer, _ - pageSize As Integer, _ - ByRef totalRecords As Integer) _ - As MembershipUserCollection - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & _ - "WHERE ApplicationName = ?", conn) - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - Dim users As MembershipUserCollection = New MembershipUserCollection() - - Dim reader As OdbcDataReader = Nothing - totalRecords = 0 - - Try - conn.Open() - totalRecords = CType(cmd.ExecuteScalar(), Integer) - - If totalRecords <= 0 Then Return users - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate " & _ - " FROM Users " & _ - " WHERE ApplicationName = ? " & _ - " ORDER BY Username Asc" - - reader = cmd.ExecuteReader() - - Dim counter As Integer = 0 - Dim startIndex As Integer = pageSize * pageIndex - Dim endIndex As Integer = startIndex + pageSize - 1 - - Do While reader.Read() - If counter >= startIndex Then - Dim u As MembershipUser = GetUserFromReader(reader) - users.Add(u) - End If - - If counter >= endIndex Then cmd.Cancel() - - counter += 1 - Loop - Catch e As OdbcException - ' Handle exception. - Finally - If Not reader Is Nothing Then reader.Close() - conn.Close() - End Try - - Return users -End Function - - -' -' GetUserFromReader -' A helper function that takes the current row from the OdbcDataReader -' and populates a MembershipUser object with the values. Called by the -' MembershipUser.GetUser implementation. -' - -Public Function GetUserFromReader(reader As OdbcDataReader) As MembershipUser - - Dim providerUserKey As Object = reader.GetValue(0) - Dim username As String = reader.GetString(1) - Dim email As String = reader.GetString(2) - - Dim passwordQuestion As String = "" - If Not reader.GetValue(3) Is DBNull.Value Then _ - passwordQuestion = reader.GetString(3) - - Dim comment As String = "" - If Not reader.GetValue(4) Is DBNull.Value Then _ - comment = reader.GetString(4) - - Dim isApproved As Boolean = reader.GetBoolean(5) - Dim isLockedOut As Boolean = reader.GetBoolean(6) - Dim creationDate As DateTime = reader.GetDateTime(7) - - Dim lastLoginDate As DateTime = New DateTime() - If Not reader.GetValue(8) Is DBNull.Value Then _ - lastLoginDate = reader.GetDateTime(8) - - Dim lastActivityDate As DateTime = reader.GetDateTime(9) - Dim lastPasswordChangedDate As DateTime = reader.GetDateTime(10) - - Dim lastLockedOutDate As DateTime = New DateTime() - If Not reader.GetValue(11) Is DBNull.Value Then _ - lastLockedOutDate = reader.GetDateTime(11) - - Dim u As MembershipUser = New MembershipUser(Me.Name, _ - username, _ - providerUserKey, _ - email, _ - passwordQuestion, _ - comment, _ - isApproved, _ - isLockedOut, _ - creationDate, _ - lastLoginDate, _ - lastActivityDate, _ - lastPasswordChangedDate, _ - lastLockedOutDate) - - Return u -End Function -' - - - - - - ' - ' MembershipProvider.GetNumberOfUsersOnline - ' - -' -8> -Public Overrides Function GetNumberOfUsersOnline() As Integer - - Dim onlineSpan As TimeSpan = New TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0) - Dim compareTime As DateTime = DateTime.Now.Subtract(onlineSpan) - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & _ - " WHERE LastActivityDate > ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@CompareDate", OdbcType.DateTime).Value = compareTime - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - Dim numOnline As Integer = 0 - - Try - conn.Open() - - numOnline = CType(cmd.ExecuteScalar(), Integer) - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try - - Return numOnline - End Function - ' - /8> - - - - - ' - ' MembershipProvider.GetPassword - ' - - ' -9> - Public Overrides Function GetPassword(ByVal username As String, ByVal answer As String) As String - - If Not EnablePasswordRetrieval Then - Throw New ProviderException("Password retrieval is not enabled.") - End If - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Password, PasswordAnswer FROM Users " & _ - " WHERE Username = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - - Dim password As String = "" - Dim passwordAnswer As String = "" - Dim reader As OdbcDataReader = Nothing - - Try - conn.Open() - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow) - - If reader.HasRows Then - reader.Read() - password = reader.GetString(0) - passwordAnswer = reader.GetString(1) - End If - Catch e As OdbcException - ' Handle exception. - Finally - If Not reader Is Nothing Then reader.Close() - conn.Close() - End Try - - If RequiresQuestionAndAnswer AndAlso _ - String.Compare(passwordAnswer, answer, True, CultureInfo.InvariantCulture) <> 0 Then - Throw New MembershipPasswordException("Incorrect password answer.") - End If - - Return password - End Function -' - /9> - - - - ' - ' MembershipProvider.GetUser - ' - -' -10> -Public Overrides Function GetUser(username As String, userIsOnline As Boolean) As MembershipUser - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" & _ - " FROM Users WHERE Username = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - - Dim u As MembershipUser = Nothing - Dim reader As OdbcDataReader = Nothing - - Try - conn.Open() - - reader = cmd.ExecuteReader() - - If reader.HasRows Then - reader.Read() - u = GetUserFromReader(reader) - - If userIsOnline Then - Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - "SET LastActivityDate = ? " & _ - "WHERE Username = ? AND Applicationname = ?", conn) - - updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - - updateCmd.ExecuteNonQuery() - End If - End If - Catch e As OdbcException - ' Handle Exception - Finally - If Not reader Is Nothing Then reader.Close() - - conn.Close() - End Try - - Return u -End Function - - - -' - /10> - - - - ' - ' MembershipProvider.GetUserNameByEmail - ' - -' -11> -Public Overrides Function GetUserNameByEmail(email As String) As String - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Username" & _ - " FROM Users WHERE Email = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - Dim username As String = "" - - Try - conn.Open() - - username = CType(cmd.ExecuteScalar(), String) - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try - - Return username - End Function - ' - /11> - - - - - - ' - ' MembershipProvider.ResetPassword - ' - - - ' -12> - Public Overrides Function ResetPassword(ByVal username As String, ByVal answer As String) As String - - If Not EnablePasswordReset Then - Throw New NotSupportedException("Password reSet is not enabled.") - End If - - If answer Is Nothing AndAlso RequiresQuestionAndAnswer Then - Throw New ProviderException("A password answer is required to reSet the password.") - End If - - Dim newPassword As String = _ - System.Web.Security.Membership.GeneratePassword(newPasswordLength, pMinRequiredNonAlphanumericCharacters) - - - Dim Args As ValidatePasswordEventArgs = _ - New ValidatePasswordEventArgs(username, newPassword, True) - - OnValidatingPassword(args) - - If args.Cancel Then - If Not args.FailureInformation Is Nothing Then - Throw args.FailureInformation - Else - Throw New Exception("Reset password canceled due to password validation failure.") - End If - End If - - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET Password = ?, LastPasswordChangedDate = ?" & _ - " WHERE Username = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Password", OdbcType.VarChar, 128).Value = newPassword - cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - If RequiresQuestionAndAnswer Then - cmd.CommandText &= " AND PasswordAnswer = ?" - cmd.Parameters.Add("@PasswordAnswer", OdbcType.VarChar, 128).Value = answer - End If - - Dim rowsAffected As Integer = 0 - - Try - conn.Open() - - rowsAffected = cmd.ExecuteNonQuery() - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try - - If rowsAffected > 0 Then - Return newPassword - Else - Throw New MembershipPasswordException("Invalid password answer for userid. Password not reset.") - End If - End Function -' - /12> - - - - ' - ' MembershipProvider.UpdateUser - ' - -' -13> -Public Overrides Sub UpdateUser(user As MembershipUser) - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET Email = ?, Comment = ?," & _ - " IsApproved = ?" & _ - " WHERE Username = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = user.Email - cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = user.Comment - cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = user.IsApproved - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = user.UserName - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - - Try - conn.Open() - - cmd.ExecuteNonQuery() - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try - End Sub - ' - /13> - - - - ' - ' MembershipProvider.ValidateUser - ' - - ' -14> - Public Overrides Function ValidateUser(ByVal username As String, ByVal password As String) As Boolean - - Dim isValid As Boolean = False - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Password, IsApproved FROM Users " & _ - " WHERE Username = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - - Dim reader As OdbcDataReader = Nothing - Dim isApproved As Boolean = False - Dim pwd As String = "" - - Try - conn.Open() - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow) - - If reader.HasRows Then - reader.Read() - pwd = reader.GetString(0) - isApproved = reader.GetBoolean(1) - End If - - If isApproved AndAlso (password = pwd) Then - isValid = True - - Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users SET LastLoginDate = ?" & _ - " WHERE Username = ? AND ApplicationName = ?", conn) - - updateCmd.Parameters.Add("@LastLoginDate", OdbcType.DateTime).Value = DateTime.Now - updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - updateCmd.ExecuteNonQuery() - End If - Catch e As OdbcException - ' Handle exception. - Finally - If Not reader Is Nothing Then reader.Close() - conn.Close() - End Try - - Return isValid - End Function - ' - /14> - - - Public Overrides Function FindUsersByName(ByVal usernameToMatch As String, _ - ByVal pageIndex As Integer, _ - ByVal pageSize As Integer, _ - ByRef totalRecords As Integer) _ - As MembershipUserCollection - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & _ - "WHERE Username LIKE ? AND ApplicationName = ?", conn) - cmd.Parameters.Add("@UsernameSearch", OdbcType.VarChar, 255).Value = usernameToMatch - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - Dim users As MembershipUserCollection = New MembershipUserCollection() - - Dim reader As OdbcDataReader = Nothing - totalRecords = 0 - - Try - conn.Open() - totalRecords = CType(cmd.ExecuteScalar(), Integer) - - If totalRecords <= 0 Then Return users - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate " & _ - " FROM Users " & _ - " WHERE Username LIKE ? AND ApplicationName = ? " & _ - " ORDER BY Username Asc" - - reader = cmd.ExecuteReader() - - Dim counter As Integer = 0 - Dim startIndex As Integer = pageSize * pageIndex - Dim endIndex As Integer = startIndex + pageSize - 1 - - Do While reader.Read() - If counter >= startIndex Then - Dim u As MembershipUser = GetUserFromReader(reader) - users.Add(u) - End If - - If counter >= endIndex Then cmd.Cancel() - - counter += 1 - Loop - Catch e As OdbcException - ' Handle exception. - Finally - If Not reader Is Nothing Then reader.Close() - conn.Close() - End Try - - Return users - End Function - - - Public Overrides Function FindUsersByEmail(ByVal emailToMatch As String, _ - ByVal pageIndex As Integer, _ - ByVal pageSize As Integer, _ - ByRef totalRecords As Integer) _ - As MembershipUserCollection - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT Count(*) FROM Users " & _ - "WHERE Email LIKE ? AND ApplicationName = ?", conn) - cmd.Parameters.Add("@EmailSearch", OdbcType.VarChar, 255).Value = emailToMatch - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName - - Dim users As MembershipUserCollection = New MembershipUserCollection() - - Dim reader As OdbcDataReader = Nothing - totalRecords = 0 - - Try - conn.Open() - totalRecords = CType(cmd.ExecuteScalar(), Integer) - - If totalRecords <= 0 Then Return users - - cmd.CommandText = "SELECT Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate " & _ - " FROM Users " & _ - " WHERE Email LIKE ? AND ApplicationName = ? " & _ - " ORDER BY Username Asc" - - reader = cmd.ExecuteReader() - - Dim counter As Integer = 0 - Dim startIndex As Integer = pageSize * pageIndex - Dim endIndex As Integer = startIndex + pageSize - 1 - - Do While reader.Read() - If counter >= startIndex Then - Dim u As MembershipUser = GetUserFromReader(reader) - users.Add(u) - End If - - If counter >= endIndex Then cmd.Cancel() - - counter += 1 - Loop - Catch e As OdbcException - ' Handle exception. - Finally - If Not reader Is Nothing Then reader.Close() - conn.Close() - End Try - - Return users - End Function - - ' - ' MembershipProvider.UnlockUser - ' - - Public Overrides Function UnlockUser(ByVal username As String) As Boolean - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - " SET IsLockedOut = False, LastLockedOutDate = ? " & _ - " WHERE Username = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - - Dim rowsAffected As Integer = 0 - - Try - conn.Open() - - rowsAffected = cmd.ExecuteNonQuery() - Catch e As OdbcException - ' Handle exception. - Finally - conn.Close() - End Try - - If rowsAffected > 0 Then _ - Return True - - Return False - End Function - - -' -' MembershipProvider.GetUser(Object, Boolean) -' - -Public Overrides Function GetUser(providerUserKey As Object, _ - userIsOnline As Boolean) As MembershipUser - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," & _ - " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," & _ - " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" & _ - " FROM Users WHERE PKID = ?", conn) - - cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey - - Dim u As MembershipUser = Nothing - Dim reader As OdbcDataReader = Nothing - - Try - conn.Open() - - reader = cmd.ExecuteReader() - - If reader.HasRows Then - reader.Read() - u = GetUserFromReader(reader) - - If userIsOnline Then - Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _ - "SET LastActivityDate = ? " & _ - "WHERE PKID = ?", conn) - - updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now - updateCmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey - - updateCmd.ExecuteNonQuery() - End If - End If - Catch e As OdbcException - ' Handle exception. - Finally - If Not reader Is Nothing Then reader.Close() - conn.Close() - End Try - - Return u -End Function - - - ' - ' UpdateFailureCount - ' A helper method that performs the checks and updates associated with - ' password failure tracking. - ' - - Private Sub UpdateFailureCount(username As String, failureType As String) - - Dim conn As OdbcConnection = New OdbcConnection(ConnectionString) - Dim cmd As OdbcCommand = New OdbcCommand("SELECT FailedPasswordAttemptCount, " & _ - " FailedPasswordAttemptWindowStart, " & _ - " FailedPasswordAnswerAttemptCount, " & _ - " FailedPasswordAnswerAttemptWindowStart " & _ - " FROM Users " & _ - " WHERE Username = ? AND ApplicationName = ?", conn) - - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - - Dim reader As OdbcDataReader = Nothing - Dim windowStart As DateTime = New DateTime() - Dim failureCount As Integer = 0 - - Try - conn.Open() - - reader = cmd.ExecuteReader(CommandBehavior.SingleRow) - - If reader.HasRows Then - reader.Read() - - If failureType = "password" Then - failureCount = reader.GetInt32(0) - windowStart = reader.GetDateTime(1) - End If - - If failureType = "passwordAnswer" Then - failureCount = reader.GetInt32(2) - windowStart = reader.GetDateTime(3) - End If - End If - - reader.Close() - - Dim windowEnd As DateTime = windowStart.AddMinutes(PasswordAttemptWindow) - - If failureCount = 0 OrElse DateTime.Now > windowEnd Then - ' First password failure or outside of PasswordAttemptWindow. - ' Start a New password failure count from 1 and a New window starting now. - - If failureType = "password" Then _ - cmd.CommandText = "UPDATE Users " & _ - " SET FailedPasswordAttemptCount = ?, " & _ - " FailedPasswordAttemptWindowStart = ? " & _ - " WHERE Username = ? AND ApplicationName = ?" - - If failureType = "passwordAnswer" Then _ - cmd.CommandText = "UPDATE Users " & _ - " SET FailedPasswordAnswerAttemptCount = ?, " & _ - " FailedPasswordAnswerAttemptWindowStart = ? " & _ - " WHERE Username = ? AND ApplicationName = ?" - - cmd.Parameters.Clear() - - cmd.Parameters.Add("@Count", OdbcType.Int).Value = 1 - cmd.Parameters.Add("@WindowStart", OdbcType.DateTime).Value = DateTime.Now - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - - If cmd.ExecuteNonQuery() < 0 Then _ - Throw New Exception("Unable to update failure count and window start.") - Else - failureCount += 1 - - If failureCount >= MaxInvalidPasswordAttempts Then - ' Password attempts have exceeded the failure threshold. Lock out - ' the user. - - cmd.CommandText = "UPDATE Users " & _ - " SET IsLockedOut = ?, LastLockedOutDate = ? " & _ - " WHERE Username = ? AND ApplicationName = ?" - - cmd.Parameters.Clear() - - cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = True - cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - - If cmd.ExecuteNonQuery() < 0 Then _ - Throw New Exception("Unable to lock out user.") - Else - ' Password attempts have not exceeded the failure threshold. Update - ' the failure counts. Leave the window the same. - - If failureType = "password" Then _ - cmd.CommandText = "UPDATE Users " & _ - " SET FailedPasswordAttemptCount = ?" & _ - " WHERE Username = ? AND ApplicationName = ?" - - If failureType = "passwordAnswer" Then _ - cmd.CommandText = "UPDATE Users " & _ - " SET FailedPasswordAnswerAttemptCount = ?" & _ - " WHERE Username = ? AND ApplicationName = ?" - - cmd.Parameters.Clear() - - cmd.Parameters.Add("@Count", OdbcType.Int).Value = failureCount - cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username - cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName - - If cmd.ExecuteNonQuery() < 0 Then _ - Throw New Exception("Unable to update failure count.") - End If - End If - Catch e As OdbcException - ' Handle Exception - Finally - If Not reader Is Nothing Then reader.Close() - conn.Close() - End Try - End Sub - - - ' - ' CheckPassword - ' Compares password values based on the MembershipPasswordFormat. - ' - - Private Function CheckPassword(password As String, dbpassword As String) As Boolean - Dim pass1 As String = password - Dim pass2 As String = dbpassword - - Select Case PasswordFormat - Case MembershipPasswordFormat.Encrypted - pass2 = UnEncodePassword(dbpassword) - Case MembershipPasswordFormat.Hashed - pass1 = EncodePassword(password) - Case Else - End Select - - If pass1 = pass2 Then - Return True - End If - - Return False - End Function - - - ' - ' EncodePassword - ' Encrypts, Hashes, or leaves the password clear based on the PasswordFormat. - ' - - Private Function EncodePassword(password As String) As String - Dim encodedPassword As String = password - - Select Case PasswordFormat - Case MembershipPasswordFormat.Clear - - Case MembershipPasswordFormat.Encrypted - encodedPassword = _ - Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))) - Case MembershipPasswordFormat.Hashed - Dim hash As HMACSHA256 = New HMACSHA256() - hash.Key = HexToByte(machineKey.ValidationKey) - encodedPassword = _ - Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))) - Case Else - Throw New ProviderException("Unsupported password format.") - End Select - - Return encodedPassword - End Function - - - ' - ' UnEncodePassword - ' Decrypts or leaves the password clear based on the PasswordFormat. - ' - - Private Function UnEncodePassword(encodedPassword As String) As String - Dim password As String = encodedPassword - - Select Case PasswordFormat - Case MembershipPasswordFormat.Clear - - Case MembershipPasswordFormat.Encrypted - password = _ - Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))) - Case MembershipPasswordFormat.Hashed - Throw New ProviderException("Cannot unencode a hashed password.") - Case Else - throw new ProviderException("Unsupported password format.") - End Select - - Return password - End Function - - ' - ' HexToByte - ' Converts a hexadecimal string to a byte array. Used to convert encryption - ' key values from the configuration. - ' - - Private Function HexToByte(hexString As String) As Byte() - Dim ReturnBytes(hexString.Length \ 2) As Byte - For i As Integer = 0 To ReturnBytes.Length - 1 - ReturnBytes(i) = Convert.ToByte(hexString.Substring(i*2, 2), 16) - Next - Return ReturnBytes - End Function - - - - End Class -End Namespace diff --git a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/VB/changepassword_vb.aspx b/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/VB/changepassword_vb.aspx deleted file mode 100644 index cfada375710..00000000000 --- a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/VB/changepassword_vb.aspx +++ /dev/null @@ -1,67 +0,0 @@ - -<%@ Page Language="VB" AutoEventWireup="True" %> - - - - - - - - ChangePassword including a ChangingPassword event handler - - -
-
- -

ChangePassword

- - - - -
-
- - You are not logged in - -

- - -
- -
- - - Home - - -
-
- - - \ No newline at end of file diff --git a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/VB/paramcoll2vb.aspx b/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/VB/paramcoll2vb.aspx deleted file mode 100644 index 15873720fe9..00000000000 --- a/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/VB/paramcoll2vb.aspx +++ /dev/null @@ -1,87 +0,0 @@ - -<%@Page Language="VB" %> -<%@Import Namespace="System.Data" %> -<%@Import Namespace="System.Data.Common" %> - - - - - - - ASP.NET Example - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/xml/System.Web.Configuration/ProcessModelSection.xml b/xml/System.Web.Configuration/ProcessModelSection.xml index b35a3287774..dc85e926f5d 100644 --- a/xml/System.Web.Configuration/ProcessModelSection.xml +++ b/xml/System.Web.Configuration/ProcessModelSection.xml @@ -33,14 +33,14 @@ The following configuration file example shows how to specify values declaratively for the `processModel` section. -``` +```xml Describes the session-state type used when installing a session-state database provider. - - enumeration with the method of the type. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet8"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet8"::: - - ]]> - + To be added. diff --git a/xml/System.Web.Management/SqlExecutionException.xml b/xml/System.Web.Management/SqlExecutionException.xml index 3b9e6486edb..fcbd31787c2 100644 --- a/xml/System.Web.Management/SqlExecutionException.xml +++ b/xml/System.Web.Management/SqlExecutionException.xml @@ -23,19 +23,10 @@ Defines a class for SQL execution exceptions in the namespace. - exception type. This code example is part of a larger example provided for the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet14"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet14"::: - + @@ -198,17 +189,7 @@ Gets the SQL commands being run when the exception occurred. The SQL commands being run when the exception occurred. - - property of the exception type. This code example is part of a larger example provided for the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet18"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet18"::: - - ]]> - + To be added. @@ -236,17 +217,7 @@ Gets the name of the database being accessed when the exception occurred. The name of the database being accessed when the exception occurred. - - property of the exception type. This code example is part of a larger example provided for the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet17"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet17"::: - - ]]> - + To be added. @@ -274,17 +245,7 @@ Gets the exception encountered when processing the SQL commands. The encountered when processing the SQL commands. - - property of the exception type. This code example is part of a larger example provided for the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet20"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet20"::: - - ]]> - + To be added. @@ -340,17 +301,7 @@ Gets the SQL Server instance being accessed when the exception occurred. The name of the SQL Server instance being accessed when the exception occurred. - - property of the exception type. This code example is part of a larger example provided for the type. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet16"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet16"::: - - ]]> - + To be added. @@ -378,17 +329,7 @@ Gets the path and name of the file containing the SQL commands being run when the exception occurred. The path and name of the file that contains the SQL commands being run when the exception occurred. - - property of the exception type. This code example is part of a larger example provided for the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet19"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet19"::: - - ]]> - + To be added. diff --git a/xml/System.Web.Management/SqlFeatures.xml b/xml/System.Web.Management/SqlFeatures.xml index c5847980b6c..ebb9d4bb812 100644 --- a/xml/System.Web.Management/SqlFeatures.xml +++ b/xml/System.Web.Management/SqlFeatures.xml @@ -20,21 +20,13 @@ - Specifies the ASP.Net features to install or remove using the methods provided by the class. + Specifies the ASP.NET features to install or remove using the methods provided by the class. - , which means you can select two or more features by combining them with the `&` (and) operator (the `And` operator in Visual Basic). - - - -## Examples - The following code example shows how to use the enumeration with the method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet2"::: - + , which means you can select two or more features by combining them with the `&` (and) operator (the `And` operator in Visual Basic). + ]]> diff --git a/xml/System.Web.Management/SqlServices.xml b/xml/System.Web.Management/SqlServices.xml index 15e9751f482..e8b7111c901 100644 --- a/xml/System.Web.Management/SqlServices.xml +++ b/xml/System.Web.Management/SqlServices.xml @@ -17,22 +17,13 @@ Supports installing and removing the SQL Server database elements of ASP.NET features. - class directly from your code. - + class directly from your code. + > [!NOTE] -> Using the aspnet_regsql.exe tool or the class to configure the database only sets up the database that the providers will use with the proper tables, triggers, and stored procedures. Configuring the database in this way does not modify configuration files to specify that these features use the SQL Providers for these services. - - - -## Examples - The following code example shows how to use the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet1"::: - +> Using the aspnet_regsql.exe tool or the class to configure the database only sets up the database that the providers will use with the proper tables, triggers, and stored procedures. Configuring the database in this way does not modify configuration files to specify that these features use the SQL Providers for these services. + ]]> Installing the SQL Server Provider Database @@ -150,22 +141,14 @@ A bitwise combination of the values, specifying the features to install. Installs components for selected ASP.NET features on a SQL Server database. - will use the default database, `aspnetdb`. If `server` is `null` or not supplied, will use the default SQL Server instance. - + will use the default database, `aspnetdb`. If `server` is `null` or not supplied, will use the default SQL Server instance. + > [!NOTE] -> The connection to the database server is made with a trusted connection. - - - -## Examples - The following code example shows how to use the method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet4"::: - +> The connection to the database server is made with a trusted connection. + ]]> Unable to connect to the specified database server. @@ -208,19 +191,11 @@ The connection string to use. The connection string is only used to establish a connection to the database server. Specifying a database in the connection string has no effect. Installs components for selected ASP.NET services on a SQL Server database. - will use the default database, `aspnetdb`. - - - -## Examples - The following code example shows how to use the method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet2"::: - + will use the default database, `aspnetdb`. + ]]> Unable to connect to the specified database server. @@ -267,14 +242,14 @@ A bitwise combination of the values, specifying the features to install. Installs components for selected ASP.NET features on a SQL Server database. - will use the default database, `aspnetdb`. If `server` is `null` or not supplied, will use the default SQL Server instance. - + will use the default database, `aspnetdb`. If `server` is `null` or not supplied, will use the default SQL Server instance. + > [!NOTE] -> The connection to the database server is made with a trusted connection. - +> The connection to the database server is made with a trusted connection. + ]]> Unable to connect to the specified database server. @@ -328,22 +303,14 @@ One of the values, specifying the type of session state to install. Installs components for ASP.NET session state on a SQL Server database. - will use the default SQL Server instance. - + will use the default SQL Server instance. + > [!NOTE] -> The connection to the database server is made with a trusted connection. - - - -## Examples - The following code example shows how to use the method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet10"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet10"::: - +> The connection to the database server is made with a trusted connection. + ]]> The type is and the value is not supplied, or the type is either or and the value is not null. @@ -385,17 +352,7 @@ One of the values, specifying the type of session state to install. The connection string to use. The connection string is only used to establish a connection to the database server. Specifying a database in the connection string has no effect. Installs components for ASP.NET session state on a SQL Server database. - - method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet8"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet8"::: - - ]]> - + To be added. The type is and the value is not supplied, or the type is either or and the value is not null. Unable to connect to the specified database server. An exception occurred while processing the SQL statements required for the operation. @@ -440,22 +397,14 @@ One of the values, specifying the type of session state to install. Installs components for ASP.NET session state on a SQL Server database. - will use the default SQL Server instance. - + uses the default SQL Server instance. + > [!NOTE] -> The connection to the database server is made with a trusted connection. - - - -## Examples - The following code example shows how to use the method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet12"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet12"::: - +> The connection to the database server is made with a trusted connection. + ]]> The type is and the value is not supplied, or the type is either or and the value is not null. @@ -509,22 +458,14 @@ A bitwise combination of the values, specifying the features to remove. Removes components for selected ASP.NET features from a SQL Server database. - will use the default database, `aspnetdb`. If `server` is `null` or not supplied, will use the default SQL Server instance. - + will use the default database, `aspnetdb`. If `server` is `null` or not supplied, will use the default SQL Server instance. + > [!NOTE] -> The connection to the database server is made with a trusted connection. - - - -## Examples - The following code example shows how to use the method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet5"::: - +> The connection to the database server is made with a trusted connection. + ]]> Unable to connect to the specified database server. @@ -567,22 +508,14 @@ The connection string to use. The connection string is only used to establish a connection to the database server. Specifying a database in the connection string has no effect. Removes components for selected ASP.NET features from a SQL Server database. - will use the default database `aspnetdb`. - + will use the default database `aspnetdb`. + > [!NOTE] -> The connection to the database server is made with a trusted connection. - - - -## Examples - The following code example shows how to use the method of the type. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet3"::: - +> The connection to the database server is made with a trusted connection. + ]]> Unable to connect to the specified database server. @@ -629,14 +562,14 @@ A bitwise combination of the values, specifying the features to remove. Removes components for selected ASP.NET features from a SQL Server database. - will use the default database, `aspnetdb`. If `server` is `null` or not supplied, will use the default SQL Server instance. - + will use the default database, `aspnetdb`. If `server` is `null` or not supplied, will use the default SQL Server instance. + > [!NOTE] -> The connection to the database server is made with a trusted connection. - +> The connection to the database server is made with a trusted connection. + ]]> Unable to connect to the specified database server. @@ -690,21 +623,13 @@ One of the values, specifying the type of session state to remove. Removes components for ASP.NET session state from a SQL Server database. - will use the default SQL Server instance. - - **Note** The connection to the database server is made with a trusted connection. - - - -## Examples - The following code example shows how to use the method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet11"::: - + will use the default SQL Server instance. + +> [!NOTE] +> The connection to the database server is made with a trusted connection. + ]]> The type is and the value is not supplied, or the type is either or and the value is not null. @@ -746,17 +671,7 @@ One of the values, specifying the type of session state to remove. The connection string to use. The connection string is only used to establish a connection to the database server. Specifying a database in the connection string has no effect. Removes components for ASP.NET session state from a SQL Server database. - - method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet9"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet9"::: - - ]]> - + To be added. The type is and the value is not supplied, or the type is either or and the value is not null. Unable to connect to the specified database server. An exception occurred while processing the SQL statements required for the operation. @@ -801,21 +716,13 @@ One of the values, specifying the type of session state to remove. Removes components for ASP.NET session state from a SQL Server database. - will use the default SQL Server instance. - - **Note** The connection to the database server is made with a trusted connection. - - - -## Examples - The following code example shows how to use the method of the class. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Management.SqlServices/CS/usingsqlservices.cs" id="Snippet13"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Management.SqlServices/VB/usingsqlservices.vb" id="Snippet13"::: - + will use the default SQL Server instance. + +> [!NOTE] +> The connection to the database server is made with a trusted connection. + ]]> The type is and the value is not supplied, or the type is either or and the value is not null. diff --git a/xml/System.Web.Security/ActiveDirectoryMembershipProvider.xml b/xml/System.Web.Security/ActiveDirectoryMembershipProvider.xml index 8a0363975be..501882bf0aa 100644 --- a/xml/System.Web.Security/ActiveDirectoryMembershipProvider.xml +++ b/xml/System.Web.Security/ActiveDirectoryMembershipProvider.xml @@ -23,14 +23,14 @@ This class is used by the and classes to provide membership services for an ASP.NET application using an Active Directory (AD) or Active Directory Application Mode (ADAM) server. > [!NOTE] -> Using an ADAM server requires specific configuration. For more information, see the ADAM Configuration section below. +> Using an ADAM server requires specific configuration. For more information, see the ADAM Configuration section below. > [!IMPORTANT] -> The instance works only in the full-trust policy default configuration of ASP.NET. In order to use the instance at any partial-trust level, either you must make changes to the appropriate trust policy file for your application or you must create a "sandbox" assembly that is deployed in the GAC. +> The instance works only in the full-trust policy default configuration of ASP.NET. In order to use the instance at any partial-trust level, either you must make changes to the appropriate trust policy file for your application or you must create a "sandbox" assembly that is deployed in the GAC. > -> The class requires unrestricted permission to run. This permission is not added to any of the partial-trust policy files supplied with ASP.NET. Although adding the permission to a partial-trust policy file will enable use of the class, doing so makes the namespace classes available to any code running in your ASP.NET pages. This option is not recommended for any Web servers that need to run in a secure, locked-down mode. +> The class requires unrestricted permission to run. This permission is not added to any of the partial-trust policy files supplied with ASP.NET. Although adding the permission to a partial-trust policy file will enable use of the class, doing so makes the namespace classes available to any code running in your ASP.NET pages. This option is not recommended for any Web servers that need to run in a secure, locked-down mode. > -> As an alternative, you can create a "sandbox" assembly that calls the class. This assembly can contain either a wrapper class that forwards method calls to the class or a class that derives from the class. In either case, the wrapper class must assert unrestricted permission. Deploy the sandbox assembly in the GAC and mark the assembly with the (APTCA) attribute. This will enable your partially trusted ASP.NET code to call your wrapper class, and since the wrapper class internally asserts the unrestricted permission, your wrapper class will be able to successfully call the provider +> As an alternative, you can create a "sandbox" assembly that calls the class. This assembly can contain either a wrapper class that forwards method calls to the class or a class that derives from the class. In either case, the wrapper class must assert unrestricted permission. Deploy the sandbox assembly in the GAC and mark the assembly with the (APTCA) attribute. This will enable your partially trusted ASP.NET code to call your wrapper class, and since the wrapper class internally asserts the unrestricted permission, your wrapper class will be able to successfully call the provider You must create a [connectionStrings Element (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/bf7sd233(v=vs.100)) entry in the Web.config file that identifies the Active Directory server, Active Directory domain, or ADAM application partition to use. The provider will only operate at domain scope, or in a subscope within a domain. The following table lists allowed connection strings and the scope used. @@ -44,7 +44,7 @@ The following table lists the properties and their default attribute mappings. > [!IMPORTANT] -> The class does not explicitly check that provider attributes are not mapped to core attributes of the user object in the directory. You must ensure that sensitive information from the directory is not exposed through mapped attributes. +> The class does not explicitly check that provider attributes are not mapped to core attributes of the user object in the directory. You must ensure that sensitive information from the directory is not exposed through mapped attributes. |Property|Default directory attribute|Can be mapped?| |--------------|---------------------------------|--------------------| @@ -80,14 +80,14 @@ |`connectionProtection` setting|Effect| |------------------------------------|------------| -||The class will connect to an Active Directory, with these restrictions.

- Any method that sets a password will fail. Active Directory requires a secure connection when changing passwords.
- You must explicitly set the `connectionUsername` and `connectionPassword` attributes using the [add Element for providers for membership (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/whae3t94(v=vs.100)) in the application configuration file; otherwise, the instance will throw a exception.| +||The class will connect to an Active Directory, with these restrictions.

- Any method that sets a password will fail. Active Directory requires a secure connection when changing passwords.
- You must explicitly set the `connectionUsername` and `connectionPassword` attributes using the [add Element for providers for membership (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/whae3t94(v=vs.100)) in the application configuration file; otherwise, the instance will throw a exception.| |`Secure`|The class will attempt to connect to Active Directory using SSL. If SSL fails, a second attempt to connect to Active Directory using sign-and-seal will be made. If both attempts fail, the instance will throw a exception.

Both process credentials and explicit credentials are supported.| The following table shows the effect of the `connectionProtection` attribute when connecting to an ADAM server. |`connectionProtection` setting|Effect| |------------------------------------|------------| -||The class will connect to an ADAM server, with this restriction.

- Any method that sets passwords will fail unless you explicitly configure the ADAM server to allow passwords to be sent and changed over an insecure connection.

Both process credentials and explicit credentials are supported.| +||The class will connect to an ADAM server, with this restriction.

- Any method that sets passwords will fail unless you explicitly configure the ADAM server to allow passwords to be sent and changed over an insecure connection.

Both process credentials and explicit credentials are supported.| |`Secure`|The class will attempt to connect to the ADAM server using SSL. If a connection cannot be made, the instance will throw a exception.

Both process credentials and explicit credentials are supported.| ## ADAM Configuration @@ -101,11 +101,10 @@ |`Secure`|636| ## Examples - The following code examples show the Web.config file for an ASP.NET application configured to use an instance. The first example uses the default mappings for Active Directory attributes, and does not support password-reset security with question-and-answer nor the ability to call search methods. The second example shows all the attribute settings allowed for an instance. - The first example is a simple configuration file using default mappings for Active Directory attributes. +The following example shows the Web.config file for an ASP.NET application configured to use an instance. It uses the default mappings for Active Directory attributes. It doesn't support password-reset security with question-and-answer or the ability to call search methods. -``` +```xml @@ -123,57 +122,6 @@ ``` - This example shows all of the attribute settings that are available for an instance of . - -``` - - - - - - - - - /> - - - - -``` - - `clientSearchTimeout` and `serverSearchTimeout` default to minutes. To change the units, set the `timeoutUnit` attribute value to one of "Days", "Hours", "Minutes", "Seconds", or "Milliseconds". If the attribute is not specified, the default is "Minutes". - ]]> Introduction to ASP.NET Membership @@ -373,9 +321,9 @@ In order to use the method, you must set these additional attributes in your application's configuration file: -- `requiresQuestionAndAnswer` must be `true`. +- `requiresQuestionAndAnswer` must be `true`. -- `attributeMapPasswordQuestion` and `attributeMapPasswordAnswer` must be mapped to attributes in the Active Directory schema. +- `attributeMapPasswordQuestion` and `attributeMapPasswordAnswer` must be mapped to attributes in the Active Directory schema. If the above criteria are not met, a is thrown at initialization. @@ -523,7 +471,7 @@ Leading and trailing spaces are trimmed from all string parameter values except `password`. > [!IMPORTANT] -> You cannot create new users unless the credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "create child instance," "delete child instance," and "set password" access rights. The "delete child instance" access right is required because creating a user is a multi-step process, and if any step of user creation fails, the class will delete the user instance rather than leave a partially constructed user instance in the directory. +> You cannot create new users unless the credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "create child instance," "delete child instance," and "set password" access rights. The "delete child instance" access right is required because creating a user is a multi-step process, and if any step of user creation fails, the class will delete the user instance rather than leave a partially constructed user instance in the directory. ]]> @@ -635,7 +583,7 @@ `username` must be 64 characters or less. > [!IMPORTANT] -> You cannot delete users unless the credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "delete child instances" access right. +> You cannot delete users unless the credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "delete child instances" access right. ]]> @@ -682,55 +630,21 @@ ## Remarks The property indicates whether you can use the method to reset a user's password. The property is set in your application's configuration file using the `enablePasswordReset` attribute of the [membership Element (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) element. - You can only set the property `true` when the following [membership Element (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) element settings have been made. - -- `requiresQuestionAndAnswer` must be `true`. + You can only set the property to `true` when the following [membership Element (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) element settings have been made: -- The Active Directory schema must be modified to contain attributes for storing the password question and answer, as well as the three tracking fields for password-answer change attempts. - -- `attributeMapPasswordQuestion`, `attributeMapPasswordAnswer`, `attributeMapFailedPasswordAnswerCount`, `attributeMapFailedPasswordAnswerTime`, and `attributeMapFailedPasswordAnswerLockoutTime` must be mapped to attributes in the Active Directory schema. +- `requiresQuestionAndAnswer` must be `true`. +- The Active Directory schema must be modified to contain attributes for storing the password question and answer, as well as the three tracking fields for password-answer change attempts. +- `attributeMapPasswordQuestion`, `attributeMapPasswordAnswer`, `attributeMapFailedPasswordAnswerCount`, `attributeMapFailedPasswordAnswerTime`, and `attributeMapFailedPasswordAnswerLockoutTime` must be mapped to attributes in the Active Directory schema. If the above criteria are not met, a is thrown at initialization. When the connection string in the application configuration file specifies an Active Directory domain rather than a specific server, the instance will always connect to the domain controller that has the PDC role for the domain to ensure that password changes take effect and are available when the method is called. > [!NOTE] -> Even if the property is `true`, you cannot reset user passwords unless the credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "reset password" access right. - - - -## Examples - The following code example shows a Web.config entry that configures an instance to enable password resets. It uses the explicit credentials of a user given the "reset password" access right. +> Even if the property is `true`, you cannot reset user passwords unless the credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "reset password" access right. > [!IMPORTANT] -> When you place user credentials in your Web.config file, there are potential security threats. Users with access rights to the directory containing the Web.config file can read the file, and thus see the credentials. For details on how to protect against this threat, see [Encrypting Configuration Information Using Protected Configuration](https://learn.microsoft.com/previous-versions/aspnet/53tyfkaw(v=vs.100)). - -``` - - - - - - - - - - - - -``` +> When you place user credentials in your Web.config file, there are potential security threats. Users with access rights to the directory containing the Web.config file can read the file, and thus see the credentials. For details on how to protect against this threat, see [Encrypting Configuration Information Using Protected Configuration](https://learn.microsoft.com/previous-versions/aspnet/53tyfkaw(v=vs.100)). ]]> @@ -797,11 +711,11 @@ When the property is `false`, the following methods are not available: -- +- -- +- -- +- The provider uses a subtree search starting at the search point specified in the connection string. See the class topic for more information about connection strings. @@ -1016,7 +930,7 @@ The generated password will contain at least the number of non-alphanumeric characters specified in the property. The generated password will not be tested with the regular expression in the property. > [!NOTE] -> The class does not generate passwords that match complexity requirements set in the directory. It is possible to generate a random password that fails the password complexity rules set by the directory. +> The class does not generate passwords that match complexity requirements set in the directory. It is possible to generate a random password that fails the password complexity rules set by the directory. ]]> @@ -1294,7 +1208,7 @@ We recommend that you do not enable searching on production systems until you have confirmed that the search queries issued by the class do not adversely impact your directory server's performance. > [!IMPORTANT] -> The method will run even when the property is `false`. +> The method will run even when the property is `false`. Since the class is designed for a stateless Web environment, it is unable to use the paging optimizations exposed by the underlying APIs. This means that paging operations during searches against large directories are very expensive and should be avoided. Search operations are always issued against the directory server configured in the connection string, or an automatically selected server in the case of a connection string pointing at a domain. The provider does not use a global catalog for its search methods. @@ -1549,7 +1463,7 @@ When the property is `true`, the user must answer the password question to reset their password. The user is allowed a limited number of answer attempts within the time window established by the property. If the number of password answer attempts is greater than or equal to the value stored in the property, the user is locked out of further attempts for the number of minutes stored in the property. > [!NOTE] -> This property does not control the number of failed logon attempts a user can make before being locked out. The Active Directory server handles failed logon attempts and is not affected by the value of this property. +> This property does not control the number of failed logon attempts a user can make before being locked out. The Active Directory server handles failed logon attempts and is not affected by the value of this property. The property is set in your application's configuration file using the `maxInvalidPasswordAttempts` attribute of the [membership Element (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) element. If the property is not set in the application's configuration file, the property is set to the default value of `5`. @@ -1728,7 +1642,7 @@ When the property is `true`, the user must answer the password question to reset their password. If the user fails to supply the correct answer a consecutive number of times equal to the property value within the observation time period specified by the property, the user is locked out of further attempts for the number of minutes contained in the property. > [!NOTE] -> This property does not set the duration a user is locked out after failing to enter a valid password. The Active Directory server handles failed logon attempts and is not affected by the value of this property. We recommend that the property be set to the same value as the account lockout duration specified for too many failed logon attempts in the Active Directory configuration. This will present consistent auto-lockout behavior for users regardless of whether they were locked out due to failed logon attempts or to bad password answers. +> This property does not set the duration a user is locked out after failing to enter a valid password. The Active Directory server handles failed logon attempts and is not affected by the value of this property. We recommend that the property be set to the same value as the account lockout duration specified for too many failed logon attempts in the Active Directory configuration. This will present consistent auto-lockout behavior for users regardless of whether they were locked out due to failed logon attempts or to bad password answers. The property is set in your application's configuration file using the `passwordAnswerAttemptLockoutDuration` attribute of the [membership Element (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) element. If the property is not set in the application's configuration file, the property is set to the default value of 30 minutes. @@ -1889,11 +1803,11 @@ ## Examples The following example shows the [membership Element (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) configuration element in the `system.web` section of the application's Web.config file. It specifies that the application use an instance of the class to provide membership services and sets the `passwordStrengthRegularExpression` attribute to a regular expression that validates that the password meets the following criteria: -- Is greater than seven characters. +- Is greater than seven characters. -- Contains at least one digit. +- Contains at least one digit. -- Contains at least one special (non-alphanumeric) character. +- Contains at least one special (non-alphanumeric) character. If the password does not meet these criteria, the password is not accepted by the membership provider. @@ -1949,49 +1863,13 @@ ## Remarks The property is set in your application's configuration file using the `requiresQuestionAndAnswer` attribute of the [membership Element (ASP.NET Settings Schema)](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) element. If the property is not set in the application's configuration file, the property is set to the default value of `false`. - When the `requiresQuestionAndAnswer` attribute is set to `true`, you must also set these additional attributes. - -- `attributeMapPasswordQuestion` and `attributeMapPasswordAnswer` must be mapped to attributes in the Active Directory schema. - - If the above criteria are not met, a is thrown at initialization. + When the `requiresQuestionAndAnswer` attribute is set to `true`, you must also map `attributeMapPasswordQuestion` and `attributeMapPasswordAnswer` to attributes in the Active Directory schema. Otherwise, a is thrown at initialization. > [!NOTE] -> You can require a password question and answer when creating a user, but set the property to `false` to prevent users from changing their passwords using the class. - - - -## Examples - The following code example shows a Web.config entry that configures an instance to enable password resets. It uses the explicit credentials of a user given the "reset password" access right. +> You can require a password question and answer when creating a user, but set the property to `false` to prevent users from changing their passwords using the class. > [!IMPORTANT] -> When you place user credentials in your Web.config file, there are potential security threats. Users with access rights to the directory containing the Web.config file can read the file, and thus see the credentials. For details on how to protect against this threat, see [Encrypting Configuration Information Using Protected Configuration](https://learn.microsoft.com/previous-versions/aspnet/53tyfkaw(v=vs.100)). - -``` - - - - - - - - - - - - -``` +> When you place user credentials in your Web.config file, there are potential security threats. Users with access rights to the directory containing the Web.config file can read the file, and thus see the credentials. For details on how to protect against this threat, see [Encrypting Configuration Information Using Protected Configuration](https://learn.microsoft.com/previous-versions/aspnet/53tyfkaw(v=vs.100)). ]]> @@ -2089,7 +1967,7 @@ The method is called by the class to reset the password for a user in the Active Directory data store to a new randomly generated value. The new password is returned. > [!NOTE] -> The random password created by the method is not guaranteed to pass the regular expression in the property. However, the random password will meet the criteria established by the and properties. +> The random password created by the method is not guaranteed to pass the regular expression in the property. However, the random password will meet the criteria established by the and properties. If an incorrect answer is supplied to the method, the internal counter that tracks invalid password-answer attempts is incremented by one. This can result in the user being unable to log on until the lock status is cleared by a call to the method. If the correct password answer is supplied and the user is not currently locked out, then the internal counter that tracks invalid password attempts is reset to zero. For more information, see the and properties. @@ -2104,22 +1982,22 @@ When using an ADAM server, the `connectionProtection` attribute can be set to , but only if you explicitly configure the ADAM server to allow password changes over unsecured connections. > [!IMPORTANT] -> You cannot reset passwords unless the credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "reset password" access right. +> You cannot reset passwords unless the credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "reset password" access right. To reset a password, all of the following conditions must be true: -- The property must be set to `true`. +- The property must be set to `true`. -- The Active Directory schema must be modified to contain attributes for storing the password question and answer, and the three tracking fields for password answer changes. +- The Active Directory schema must be modified to contain attributes for storing the password question and answer, and the three tracking fields for password answer changes. -- The `attributeMapPasswordQuestion`, `attributeMapPasswordAnswer`, `attributeMapFailedPasswordAnswerCount`, `attributeMapFailedPasswordAnswerTime`, and `attributeMapFailedPasswordAnswerLockedTime` attributes must be set in the application configuration file. +- The `attributeMapPasswordQuestion`, `attributeMapPasswordAnswer`, `attributeMapFailedPasswordAnswerCount`, `attributeMapFailedPasswordAnswerTime`, and `attributeMapFailedPasswordAnswerLockedTime` attributes must be set in the application configuration file. -- The property must be set to `true`. +- The property must be set to `true`. -- The security context for connecting to the Active Directory data store (either the process account or the explicit credentials) must have sufficient privileges to change passwords. The credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "reset password" access right. +- The security context for connecting to the Active Directory data store (either the process account or the explicit credentials) must have sufficient privileges to change passwords. The credentials used to connect to the Active Directory server have either Domain Administrator rights (not recommended) or the "reset password" access right. > [!NOTE] -> Security policies set on the Active Directory server may make it impossible for the method to generate a password that satisfies the policies. The default implementation of the method will generate passwords that satisfy the default password policies on domain controllers running Windows Server 2003 SP1. If the password cannot be reset due to security policies on the Active Directory server, a is thrown. +> Security policies set on the Active Directory server may make it impossible for the method to generate a password that satisfies the policies. The default implementation of the method will generate passwords that satisfy the default password policies on domain controllers running Windows Server 2003 SP1. If the password cannot be reset due to security policies on the Active Directory server, a is thrown. ]]> @@ -2347,24 +2225,24 @@ However, the instance will connect to the directory using the configured credentials for the following reasons. -- To confirm that a user exists within the search scope as determined by the instance's connection string. The provider uses a subtree search starting at the search point specified in the connection string to determine whether a user exists. The user must exist in the specified container. Credentials that are valid outside the connection string's specified container will not be validated. See the class topic for more information about connection strings. +- To confirm that a user exists within the search scope as determined by the instance's connection string. The provider uses a subtree search starting at the search point specified in the connection string to determine whether a user exists. The user must exist in the specified container. Credentials that are valid outside the connection string's specified container will not be validated. See the class topic for more information about connection strings. -- If the property is `true`, the instance will use the configured credentials to load the user instance to check whether the user has been locked out because they have made too many failed attempts to change the password answer. +- If the property is `true`, the instance will use the configured credentials to load the user instance to check whether the user has been locked out because they have made too many failed attempts to change the password answer. > [!IMPORTANT] -> Connecting to an Active Directory domain controller with the "Guest" account enabled is a potential security threat. All validation attempts made on an Active Directory domain controller with the "Guest" account enabled will succeed. To improve security when using an Active Directory domain controller, you should disable the "Guest" account on the domain controller. +> Connecting to an Active Directory domain controller with the "Guest" account enabled is a potential security threat. All validation attempts made on an Active Directory domain controller with the "Guest" account enabled will succeed. To improve security when using an Active Directory domain controller, you should disable the "Guest" account on the domain controller. The instance will attempt a concurrent bind against Active Directory when one of the following conditions is met: -- The property is set to . +- The property is set to . -- The property is set to and SSL is chosen by the instance to secure the connection. +- The property is set to and SSL is chosen by the instance to secure the connection. In addition, for a concurrent bind to be made, the following conditions must be true: -- The directory server must be running on Windows Server 2003. +- The directory server must be running on Windows Server 2003. -- The operating system of the Web server running the instance must support concurrent binds (for example, Windows Server 2003). +- The operating system of the Web server running the instance must support concurrent binds (for example, Windows Server 2003). When a concurrent bind is used, the last logon date for the user is not updated in the directory; therefore, the property cannot be relied on. diff --git a/xml/System.Web.Security/FormsAuthentication.xml b/xml/System.Web.Security/FormsAuthentication.xml index 730e12e16f4..95307643933 100644 --- a/xml/System.Web.Security/FormsAuthentication.xml +++ b/xml/System.Web.Security/FormsAuthentication.xml @@ -40,12 +40,10 @@ The class provides access to methods and properties that you can use in an application that authenticates users. The method redirects a browser to the configured for users to log into an application. The method redirects an authenticated user back to the original protected URL that was requested or to the . There are also methods that enable you to manage forms-authentication tickets, if needed. - - ## Examples The following code example shows the Web.config file for an ASP.NET application that uses the ASP.NET membership provider for forms authentication and requires all users to be authenticated. -``` +```xml @@ -149,47 +147,10 @@ to verify the credentials. For more information, see [Managing Users by Using Membership](https://learn.microsoft.com/previous-versions/aspnet/tw292whz(v=vs.100)). - - For improved security, you can encrypt passwords stored in the configuration file for an application by using the method. - - - -## Examples - The following code example shows user credentials stored in the Web.config file for an application. The password values have been hashed using the method. - - This example uses SHA1. Due to collision problems with SHA1, Microsoft recommends SHA256. - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - The following code example shows a login page that uses the method to validate user credentials. - -> [!IMPORTANT] -> This example contains a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see [Script Exploits Overview](https://learn.microsoft.com/previous-versions/aspnet/w1sw53ds(v=vs.100)). - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.FormsAuthentication/CS/logincs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.FormsAuthentication/VB/loginvb.aspx" id="Snippet1"::: +This method is obsolete. The recommended alternative is to use the Membership APIs, such as . For more information, see [Managing Users by Using Membership](https://learn.microsoft.com/previous-versions/aspnet/tw292whz(v=vs.100)). ]]> - ASP.NET Web Application Security
@@ -466,7 +427,7 @@ > [!NOTE] > When you redirect pages across applications, you must make sure that specific attributes in the [forms](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1d3t3c61(v%3dvs.100)) configuration element are duplicated across the authenticated applications. For more information and an example, see [Forms Authentication Across Applications](https://learn.microsoft.com/previous-versions/aspnet/eb0zx8fc(v=vs.100)). - + > [!IMPORTANT] > When cross-application redirects are allowed, your site is vulnerable to an exploit that directs users to a malicious Web site but uses the login page for your site. Always verify that the redirect URL that is returned by the method is a URL that you expect so that you can make sure that you allow redirects only to approved Web sites. You must also verify that the redirect URL uses the appropriate protocol (HTTP or HTTPS). To perform these verifications, you can add a postback event handler to your login page, or you can add a handler for the event of the control. @@ -840,20 +801,8 @@ This method does not create a cookie. method creates a hashed password value that can be used when storing forms-authentication credentials in the configuration file for an application. - - Authentication credentials stored in the configuration file for an application are used by the method to verify passwords for users of an application. Alternatively, you can use ASP.NET membership to store user credentials. For more information, see [Managing Users by Using Membership](https://learn.microsoft.com/previous-versions/aspnet/tw292whz(v=vs.100)). - - -## Examples - The following code example takes a user name, password, and hash type and displays the [credentials](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/e01fc50a(v%3dvs.100)) section of the configuration that includes the user definition and hashed password. - -> [!IMPORTANT] -> This example contains a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see [Script Exploits Overview](https://learn.microsoft.com/previous-versions/aspnet/w1sw53ds(v=vs.100)). - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/FormsAuthenticationHashPassword/CS/formsauthenticationhashpasswordcs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/FormsAuthenticationHashPassword/VB/formsauthenticationhashpasswordvb.aspx" id="Snippet1"::: +This method is obsolete. Alternatively, you can use ASP.NET membership to store user credentials. For more information, see [Managing Users by Using Membership](https://learn.microsoft.com/previous-versions/aspnet/tw292whz(v=vs.100)). ]]> @@ -865,7 +814,6 @@ This method does not create a cookie. is . is not a valid value. - ASP.NET Web Application Security
diff --git a/xml/System.Web.Security/MembershipUser.xml b/xml/System.Web.Security/MembershipUser.xml index 57795932959..6e228ff75a5 100644 --- a/xml/System.Web.Security/MembershipUser.xml +++ b/xml/System.Web.Security/MembershipUser.xml @@ -165,14 +165,6 @@ The `name`, `email`, and `passwordQuestion` parameters are all trimmed before being used. - - -## Examples - The following code example shows an implementation of the method for a membership provider. The method constructs a object that is returned when the user is successfully added to the data store. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.MembershipUser.Constructor/CS/newuser.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUser.Constructor/VB/newuser.vb" id="Snippet1"::: - ]]> diff --git a/xml/System.Web.Security/MembershipUserCollection.xml b/xml/System.Web.Security/MembershipUserCollection.xml index 880132c2821..95a85ca682c 100644 --- a/xml/System.Web.Security/MembershipUserCollection.xml +++ b/xml/System.Web.Security/MembershipUserCollection.xml @@ -41,22 +41,22 @@ A collection of objects. - is returned from the , , and methods of the class. The objects returned by the , , and methods contain a snapshot of user information in the membership data store. That is, changes to the membership user information in a are not reflected in the membership data store. To modify membership user information in the membership data store, use the , and methods of the class. - + is returned from the , , and methods of the class. The objects returned by the , , and methods contain a snapshot of user information in the membership data store. That is, changes to the membership user information in a are not reflected in the membership data store. To modify membership user information in the membership data store, use the , and methods of the class. + > [!NOTE] -> If you are not familiar with the membership features of ASP.NET, see [Introduction to Membership](https://learn.microsoft.com/previous-versions/aspnet/yh26yfzy(v=vs.100)) before continuing. For a list of other topics related to membership, see [Managing Users by Using Membership](https://learn.microsoft.com/previous-versions/aspnet/tw292whz(v=vs.100)). - - - -## Examples - The following code example returns a list of membership users with a count of the number of users currently online. For an example of an ASP.NET application configured to use membership, see the class. - +> If you are not familiar with the membership features of ASP.NET, see [Introduction to Membership](https://learn.microsoft.com/previous-versions/aspnet/yh26yfzy(v=vs.100)) before continuing. For a list of other topics related to membership, see [Managing Users by Using Membership](https://learn.microsoft.com/previous-versions/aspnet/tw292whz(v=vs.100)). + + + +## Examples + The following code example returns a list of membership users with a count of the number of users currently online. For an example of an ASP.NET application configured to use membership, see the class. + [!code-aspx-csharp[System.Web.Security.SqlMembershipProvider#5](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.SqlMembershipProvider/CS/ShowUserscs.aspx#5)] - [!code-aspx-vb[System.Web.Security.SqlMembershipProvider#5](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.SqlMembershipProvider/VB/ShowUsersvb.aspx#5)] - + [!code-aspx-vb[System.Web.Security.SqlMembershipProvider#5](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.SqlMembershipProvider/VB/ShowUsersvb.aspx#5)] + ]]> Managing Users By Using Membership @@ -81,19 +81,11 @@ Creates a new, empty membership user collection. - is constructed by membership provider implementers and returned from the and methods of the abstract class. - - - -## Examples - The following code example shows a sample implementation. - - [!code-csharp[System.Web.Security.IMembershipProvider#15](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovidergetallusers.cs#15)] - [!code-vb[System.Web.Security.IMembershipProvider#15](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovidergetallusers.vb#15)] - + is constructed by membership provider implementers and returned from the and methods of the abstract class. + ]]> Managing Users By Using ASP.NET Membership @@ -125,19 +117,11 @@ A object to add to the collection. Adds the specified membership user to the collection. - method is commonly used by membership provider implementations of the , , and methods of the abstract class. - - - -## Examples - The following code example shows a sample implementation. - - [!code-csharp[System.Web.Security.IMembershipProvider#15](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovidergetallusers.cs#15)] - [!code-vb[System.Web.Security.IMembershipProvider#15](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovidergetallusers.vb#15)] - + method is commonly used by membership provider implementations of the , , and methods of the abstract class. + ]]> The collection is read-only. @@ -169,14 +153,14 @@ Removes all membership user objects from the collection. - before replacing it with the results of the method. - + before replacing it with the results of the method. + [!code-csharp[System.Web.Security.MembershipUserCollection#4](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/CS/snippetscs.aspx#4)] - [!code-vb[System.Web.Security.MembershipUserCollection#4](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/VB/snippetsvb.aspx#4)] - + [!code-vb[System.Web.Security.MembershipUserCollection#4](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/VB/snippetsvb.aspx#4)] + ]]> Managing Users By Using ASP.NET Membership @@ -239,14 +223,14 @@ Gets the number of membership user objects in the collection. The number of objects in the collection. - Managing Users By Using ASP.NET Membership @@ -279,19 +263,19 @@ Gets an enumerator that can iterate through the membership user collection. An for the entire . - . - - - -## Examples - The following code example uses the returned from the method to iterate through a . - + . + + + +## Examples + The following code example uses the returned from the method to iterate through a . + [!code-csharp[System.Web.Security.MembershipUserCollection#7](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/CS/snippetscs.aspx#7)] - [!code-vb[System.Web.Security.MembershipUserCollection#7](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/VB/snippetsvb.aspx#7)] - + [!code-vb[System.Web.Security.MembershipUserCollection#7](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/VB/snippetsvb.aspx#7)] + ]]> Managing Users By Using ASP.NET Membership @@ -323,11 +307,11 @@ Gets a value indicating whether the membership user collection is thread safe. Always because thread-safe membership user collections are not supported. - Managing Users Using ASP.NET Membership @@ -360,19 +344,19 @@ Gets the membership user in the collection referenced by the specified user name. A object representing the user specified by . - object returned by property contains a snapshot of user information in the membership data store. That is, changes to the membership user information in the are not reflected in the membership data store. To modify membership user information in the membership data store, use the , , and methods. - - - -## Examples - The following code example displays all membership user names in a and shows specific membership information for the selected user name. - + object returned by property contains a snapshot of user information in the membership data store. That is, changes to the membership user information in the are not reflected in the membership data store. To modify membership user information in the membership data store, use the , , and methods. + + + +## Examples + The following code example displays all membership user names in a and shows specific membership information for the selected user name. + [!code-aspx-csharp[System.Web.Security.MembershipUserCollection#2](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/CS/itemcs.aspx#2)] - [!code-aspx-vb[System.Web.Security.MembershipUserCollection#2](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/VB/itemvb.aspx#2)] - + [!code-aspx-vb[System.Web.Security.MembershipUserCollection#2](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/VB/itemvb.aspx#2)] + ]]> Managing Users By Using ASP.NET Membership @@ -431,19 +415,19 @@ Makes the contents of the membership user collection read-only. - are considered read-only, as they are a snapshot of the membership user information in the membership data store. Membership user information is modified using the , and methods. The method marks the as read-only so that objects cannot be added to or removed from the collection. Property values for the objects are not marked as read-only. That is, you can modify the property values of a in the regardless of whether the collection has been marked as read-only by the method. - - - -## Examples - The following code example returns all of the users from the membership data store. The returned is marked as read-only based on a `Boolean` parameter specified by the caller. - + are considered read-only, as they are a snapshot of the membership user information in the membership data store. Membership user information is modified using the , and methods. The method marks the as read-only so that objects cannot be added to or removed from the collection. Property values for the objects are not marked as read-only. That is, you can modify the property values of a in the regardless of whether the collection has been marked as read-only by the method. + + + +## Examples + The following code example returns all of the users from the membership data store. The returned is marked as read-only based on a `Boolean` parameter specified by the caller. + [!code-csharp[System.Web.Security.MembershipUserCollection#5](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/CS/snippetscs.aspx#5)] - [!code-vb[System.Web.Security.MembershipUserCollection#5](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/VB/snippetsvb.aspx#5)] - + [!code-vb[System.Web.Security.MembershipUserCollection#5](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.MembershipUserCollection/VB/snippetsvb.aspx#5)] + ]]> Managing Users By Using ASP.NET Membership @@ -475,11 +459,11 @@ Gets the synchronization root. Always , because synchronization of membership user collections is not supported. - Managing Users By Using ASP.NET Membership @@ -521,14 +505,14 @@ is less than 0. - is multidimensional. - - -or- - - is greater than or equal to the length of . - - -or- - + is multidimensional. + + -or- + + is greater than or equal to the length of . + + -or- + The number of elements in the source is greater than the available space from to the end of the destination array. The type of the source cannot be cast automatically to the type of the destination array. diff --git a/xml/System.Web.Security/ValidatePasswordEventArgs.xml b/xml/System.Web.Security/ValidatePasswordEventArgs.xml index 6da908bc6d1..08b0159c887 100644 --- a/xml/System.Web.Security/ValidatePasswordEventArgs.xml +++ b/xml/System.Web.Security/ValidatePasswordEventArgs.xml @@ -29,25 +29,25 @@ Provides event data for the event of the class. - event is raised when the , , or method of a membership provider is called. - - You can handle the event to validate password formats and values for membership users. - - You can cancel the current , , or action by setting the property to `true` during the event. - - If you cancel the current action by setting the property to `true`, you can set the property to an exception that describes the reason for the password-validation failure. The calling method will throw the exception that the property is set to. If the property is `null`, the caller will throw a generic password-validation failure exception. - - - -## Examples - The following code example shows a event that validates the format of the password for the user and cancels the action if the password does not match the required format. - + event is raised when the , , or method of a membership provider is called. + + You can handle the event to validate password formats and values for membership users. + + You can cancel the current , , or action by setting the property to `true` during the event. + + If you cancel the current action by setting the property to `true`, you can set the property to an exception that describes the reason for the password-validation failure. The calling method will throw the exception that the property is set to. If the property is `null`, the caller will throw a generic password-validation failure exception. + + + +## Examples + The following code example shows a event that validates the format of the password for the user and cancels the action if the password does not match the required format. + [!code-csharp[System.Web.Security.Membership#11](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.Membership/CS/CreateUser3cs.aspx#11)] - [!code-vb[System.Web.Security.Membership#11](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.Membership/VB/CreateUser3vb.aspx#11)] - + [!code-vb[System.Web.Security.Membership#11](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.Membership/VB/CreateUser3vb.aspx#11)] + ]]> Introduction to ASP.NET Membership @@ -81,19 +81,10 @@ if the event is occurring while a new user is being created; otherwise, . Creates a new instance of the class. - constructor is used by a membership provider implementation in the , , and method implementations. - - - -## Examples - The following code example shows a sample implementation that creates a new object to pass to the event. - - [!code-csharp[System.Web.Security.IMembershipProvider#4](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/CS/imembershipprovider.cs#4)] - [!code-vb[System.Web.Security.IMembershipProvider#4](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.IMembershipProvider/VB/imembershipprovider.vb#4)] - + constructor is used by a membership provider implementation in the , , and method implementations. + ]]> Implementing a Membership Provider @@ -134,21 +125,21 @@ if the current create-user, change-password, or reset-password action will be canceled; otherwise, . The default is . - property is used to cancel the current , , or action. You can cancel the current action by setting the property to `true` during the event. - - If you cancel the current action by setting the property to `true`, you can set the property to an exception that describes the reason for the password-validation failure. The calling method will throw the exception that the property is set to. If the property is `null`, the caller will throw a generic password-validation failure exception. - - - -## Examples - The following code example shows a event that validates the format of the password for the user and cancels the action if the password does not match the required format. - + property is used to cancel the current , , or action. You can cancel the current action by setting the property to `true` during the event. + + If you cancel the current action by setting the property to `true`, you can set the property to an exception that describes the reason for the password-validation failure. The calling method will throw the exception that the property is set to. If the property is `null`, the caller will throw a generic password-validation failure exception. + + + +## Examples + The following code example shows a event that validates the format of the password for the user and cancels the action if the password does not match the required format. + [!code-csharp[System.Web.Security.Membership#11](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.Membership/CS/CreateUser3cs.aspx#11)] - [!code-vb[System.Web.Security.Membership#11](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.Membership/VB/CreateUser3vb.aspx#11)] - + [!code-vb[System.Web.Security.Membership#11](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.Membership/VB/CreateUser3vb.aspx#11)] + ]]> Introduction to ASP.NET Membership @@ -187,21 +178,21 @@ Gets or sets an exception that describes the reason for the password-validation failure. An that describes the reason for the password-validation failure. - property is used when the current , , or action has been canceled by setting the property to `true`. - - The property is set to an exception that describes the reason for the password-validation failure. The calling method will throw the exception that the property is set to. If the property is `null`, the caller will throw a generic password-validation failure exception. - - - -## Examples - The following code example shows a event that validates the format of the password for the user and cancels the action if the password does not match the required format. - + property is used when the current , , or action has been canceled by setting the property to `true`. + + The property is set to an exception that describes the reason for the password-validation failure. The calling method will throw the exception that the property is set to. If the property is `null`, the caller will throw a generic password-validation failure exception. + + + +## Examples + The following code example shows a event that validates the format of the password for the user and cancels the action if the password does not match the required format. + [!code-csharp[System.Web.Security.Membership#11](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.Membership/CS/CreateUser3cs.aspx#11)] - [!code-vb[System.Web.Security.Membership#11](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.Membership/VB/CreateUser3vb.aspx#11)] - + [!code-vb[System.Web.Security.Membership#11](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.Membership/VB/CreateUser3vb.aspx#11)] + ]]> Introduction to ASP.NET Membership @@ -269,25 +260,25 @@ Gets the password for the current create-user, change-password, or reset-password action. The password for the current create-user, change-password, or reset-password action. - event is raised when the , , or method of a membership provider is called. - - You can handle the event to validate password formats and values for membership users. - - You can cancel the current , , or action by setting the property to `true` during the event. - - If you cancel the current action by setting the property to `true`, you can set the property to an exception that describes the reason for the password-validation failure. The calling method will throw the exception that the property is set to. If the property is `null`, the caller will throw a generic password-validation failure exception. - - - -## Examples - The following code example shows a event that validates the format of the password for the user and cancels the action if the password does not match the required format. - + event is raised when the , , or method of a membership provider is called. + + You can handle the event to validate password formats and values for membership users. + + You can cancel the current , , or action by setting the property to `true` during the event. + + If you cancel the current action by setting the property to `true`, you can set the property to an exception that describes the reason for the password-validation failure. The calling method will throw the exception that the property is set to. If the property is `null`, the caller will throw a generic password-validation failure exception. + + + +## Examples + The following code example shows a event that validates the format of the password for the user and cancels the action if the password does not match the required format. + [!code-csharp[System.Web.Security.Membership#11](~/snippets/csharp/VS_Snippets_WebNet/System.Web.Security.Membership/CS/CreateUser3cs.aspx#11)] - [!code-vb[System.Web.Security.Membership#11](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.Membership/VB/CreateUser3vb.aspx#11)] - + [!code-vb[System.Web.Security.Membership#11](~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.Security.Membership/VB/CreateUser3vb.aspx#11)] + ]]> Introduction to ASP.NET Membership diff --git a/xml/System.Web.UI.WebControls/ChangePassword.xml b/xml/System.Web.UI.WebControls/ChangePassword.xml index b3f01c378a8..2f660f51402 100644 --- a/xml/System.Web.UI.WebControls/ChangePassword.xml +++ b/xml/System.Web.UI.WebControls/ChangePassword.xml @@ -39,274 +39,274 @@ Provides a user interface that enable users to change their Web site password. - -## Introduction - Use the control on a page to enable your Web site users to change the passwords they use to log on to your Web site. - + +## Introduction + Use the control on a page to enable your Web site users to change the passwords they use to log on to your Web site. + > [!NOTE] -> If you are not familiar with the set of login controls available in ASP.NET, read [ASP.NET Login Controls Overview](https://learn.microsoft.com/previous-versions/aspnet/ms178329(v=vs.100)) before continuing. For a list of other topics related to login controls and membership, see [Managing Users by Using Membership](https://learn.microsoft.com/previous-versions/aspnet/tw292whz(v=vs.100)). - +> If you are not familiar with the set of login controls available in ASP.NET, read [ASP.NET Login Controls Overview](https://learn.microsoft.com/previous-versions/aspnet/ms178329(v=vs.100)) before continuing. For a list of other topics related to login controls and membership, see [Managing Users by Using Membership](https://learn.microsoft.com/previous-versions/aspnet/tw292whz(v=vs.100)). + > [!IMPORTANT] -> Transmitting passwords over HTTP is a potential security threat. HTTP transmissions can be viewed or compromised by malicious users. To improve security when using login controls, you should use HTTPS protocol with secure sockets layer (SSL) encryption to ensure that the user's password cannot be read during postback. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - - The control uses the membership provider defined in the property to change the password stored in the membership provider data store for the Web site. If you do not assign a membership provider, the control uses the default membership provider defined in the [membership](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) section of the Web.config file. The control enables users to perform the following actions: - -- Change their password if they are logged on. - -- Change their password if they are not logged on, as long as the page that contains the control allows anonymous access and the property is `true`. - -- Change the password for a user account, even if they are logged on as a different user. This requires the property to be `true`. - - Setting the property to `true` displays the User Name text box, which allows the user to type in a user name. If the user is logged on, the control is populated with the name of the logged-on user. After the password for the given user name is changed, the user is logged on to the account associated with the changed password, even if the user was not logged on to that account previously. - +> Transmitting passwords over HTTP is a potential security threat. HTTP transmissions can be viewed or compromised by malicious users. To improve security when using login controls, you should use HTTPS protocol with secure sockets layer (SSL) encryption to ensure that the user's password cannot be read during postback. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + + The control uses the membership provider defined in the property to change the password stored in the membership provider data store for the Web site. If you do not assign a membership provider, the control uses the default membership provider defined in the [membership](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/1b9hw62f(v=vs.100)) section of the Web.config file. The control enables users to perform the following actions: + +- Change their password if they are logged on. + +- Change their password if they are not logged on, as long as the page that contains the control allows anonymous access and the property is `true`. + +- Change the password for a user account, even if they are logged on as a different user. This requires the property to be `true`. + + Setting the property to `true` displays the User Name text box, which allows the user to type in a user name. If the user is logged on, the control is populated with the name of the logged-on user. After the password for the given user name is changed, the user is logged on to the account associated with the changed password, even if the user was not logged on to that account previously. + > [!IMPORTANT] -> Accepting user input is a potential security threat. Malicious users can send data that is intended to expose vulnerabilities or run programs that try generated passwords. To improve security when working with user input, you should use the validation features of your control and secure any data providers that are configured for your control. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)), [Basic Security Practices for Web Applications](https://learn.microsoft.com/previous-versions/aspnet/zdh19h94(v=vs.100)), and [Securing Membership](https://learn.microsoft.com/previous-versions/aspnet/ms178398(v=vs.100)). - - -## Sending Email Messages - The control can be configured to use email services to send the new password to the user. To send email messages to users from any of ASP.NET Web server controls, you must configure an email server in the Web.config file for your application. For more information, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). - - Email messages are configured using the class. You must set the property to instruct ASP.NET to send email. - +> Accepting user input is a potential security threat. Malicious users can send data that is intended to expose vulnerabilities or run programs that try generated passwords. To improve security when working with user input, you should use the validation features of your control and secure any data providers that are configured for your control. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)), [Basic Security Practices for Web Applications](https://learn.microsoft.com/previous-versions/aspnet/zdh19h94(v=vs.100)), and [Securing Membership](https://learn.microsoft.com/previous-versions/aspnet/ms178398(v=vs.100)). + + +## Sending Email Messages + The control can be configured to use email services to send the new password to the user. To send email messages to users from any of ASP.NET Web server controls, you must configure an email server in the Web.config file for your application. For more information, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). + + Email messages are configured using the class. You must set the property to instruct ASP.NET to send email. + > [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - +> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + > [!NOTE] -> It is not possible to guarantee that a user will receive or view an email message. To verify that a user has received a message, provide a confirmation link in the email message that lets the user confirm that the notification was received. - - -## Views - The control has two states, or views: - -- Change Password view Requests the current password, and requires the user to type the new password twice for confirmation. If you allow users who are not logged on to change their passwords, set the property to `true` to display the control in Change Password view. The control allows the user to provide their registered user name. If there is an error when changing the password, an error message is displayed in the Change Password view, allowing the user to try again. - -- Success view Provides confirmation that the password has been changed. - +> It is not possible to guarantee that a user will receive or view an email message. To verify that a user has received a message, provide a confirmation link in the email message that lets the user confirm that the notification was received. + + +## Views + The control has two states, or views: + +- Change Password view Requests the current password, and requires the user to type the new password twice for confirmation. If you allow users who are not logged on to change their passwords, set the property to `true` to display the control in Change Password view. The control allows the user to provide their registered user name. If there is an error when changing the password, an error message is displayed in the Change Password view, allowing the user to try again. + +- Success view Provides confirmation that the password has been changed. + > [!IMPORTANT] - > The functionality for changing passwords and for continue and cancel is attached to any button that has the correct command name, regardless of which view the button is placed on. For example, a button with the value `commandname=changepassword` in the Success view will attempt to change the password and result in an exception. - - -## Styles and Templates - You can use an extensive set of style properties to customize the appearance of the control. Alternatively, you can apply custom templates to the two views if you need complete control over the appearance of the control. If you define a template for a view, the properties are applied. For a list of the controls that you must set in the view templates, see the and properties. The control examines the content in the template and throws an exception if a required control is not found, is not named correctly, or is of the wrong type. For example, if you use the content in the template and set the property to `true`, the will throw an exception if a or some other control is not found for the user name. - - The following table lists the control style properties and describes which UI element they affect. For a list of the properties to which each style applies, see the individual style property. - -| style property|UI element| -|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------| -||Cancel button on the Change Password view.| -||Change Password button on the Change Password view.| -||Continue button on the Success view.| -||Error text displayed to the user.| -||Hyperlinks to other pages.| -||Instructional text on the page that describes how to use the control.| -||Labels for all input fields, such as text boxes.| -||Hints for providing an acceptable password for the Web site.| -||Text displayed to the user when the password has been successfully changed.| -||Text entry input fields.| -||Titles for the Change Password and Success views.| - - -## Applying CSS Styles - The control lets you specify CSS style rules in markup. If you use templates to customize the appearance of the control, you can specify CSS styles in the markup in the templates. In that case, no extra outer table is required. You can prevent the table from being rendered by setting the property to `false`. - - -## Validation Groupings - The control uses a validation group so that other fields on the same page as the control can be validated separately. By default, the property of the control is used as the name of the validation group. For example, a control with the ID `"ChangePassword1"` will use a validation group name of `ChangePassword1` as well. To set the validation group that the control is part of, you must create a template with the control, and then change the validation group name. - - To show error messages if a user leaves a control empty, add a control to the page. Set the property of the control to the property of the control. - - -## Access Keys and Tab Indexes - For information about how to use the property and the property of a control, see [Accessibility in Visual Studio and ASP.NET](https://learn.microsoft.com/previous-versions/ms228004(v=vs.140)) and [ASP.NET Controls and Accessibility](https://learn.microsoft.com/previous-versions/ms227996(v=vs.140)). - - -## Accessibility - For information about how to configure this control so that it generates markup that conforms to accessibility standards, see [Accessibility in Visual Studio and ASP.NET](https://learn.microsoft.com/previous-versions/ms228004(v=vs.140)) and [ASP.NET Controls and Accessibility](https://learn.microsoft.com/previous-versions/ms227996(v=vs.140)). - - -## Accessing Controls During Page_Load and Page_Init - control properties represented by text boxes, such as and , are accessible during all phases of the page life cycle. In particular, during the Page_Init and Page_Load phases, these properties have the same value they had when the control was rendered. If the user changes the value of the property by modifying the text box, the new value will be available when the changed event is raised, which occurs after the Page_Load phase. Therefore, if you set the value of the property in the Page_Init phase or Page_Load phase and provide a custom handler for a event, any change that the user makes in the text box overrides the value set in the Page_Init or Page_Load phase. - - -## Declarative Syntax - -``` - -         -         -         - -         -         -         -         -         -         -         -                 -                         -                 -         -         -         - -         -         -         -         -         - -``` - - - -## Examples - The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: - -- Are greater than six characters. - -- Contain at least one digit. - -- Contain at least one special (non-alphanumeric) character. - - The password requirements contained in the property are displayed to the user. - - If the password entered by the user does not meet the requirements of the property, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. - + > The functionality for changing passwords and for continue and cancel is attached to any button that has the correct command name, regardless of which view the button is placed on. For example, a button with the value `commandname=changepassword` in the Success view will attempt to change the password and result in an exception. + + +## Styles and Templates + You can use an extensive set of style properties to customize the appearance of the control. Alternatively, you can apply custom templates to the two views if you need complete control over the appearance of the control. If you define a template for a view, the properties are applied. For a list of the controls that you must set in the view templates, see the and properties. The control examines the content in the template and throws an exception if a required control is not found, is not named correctly, or is of the wrong type. For example, if you use the content in the template and set the property to `true`, the will throw an exception if a or some other control is not found for the user name. + + The following table lists the control style properties and describes which UI element they affect. For a list of the properties to which each style applies, see the individual style property. + +| style property|UI element| +|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------| +||Cancel button on the Change Password view.| +||Change Password button on the Change Password view.| +||Continue button on the Success view.| +||Error text displayed to the user.| +||Hyperlinks to other pages.| +||Instructional text on the page that describes how to use the control.| +||Labels for all input fields, such as text boxes.| +||Hints for providing an acceptable password for the Web site.| +||Text displayed to the user when the password has been successfully changed.| +||Text entry input fields.| +||Titles for the Change Password and Success views.| + + +## Applying CSS Styles + The control lets you specify CSS style rules in markup. If you use templates to customize the appearance of the control, you can specify CSS styles in the markup in the templates. In that case, no extra outer table is required. You can prevent the table from being rendered by setting the property to `false`. + + +## Validation Groupings + The control uses a validation group so that other fields on the same page as the control can be validated separately. By default, the property of the control is used as the name of the validation group. For example, a control with the ID `"ChangePassword1"` will use a validation group name of `ChangePassword1` as well. To set the validation group that the control is part of, you must create a template with the control, and then change the validation group name. + + To show error messages if a user leaves a control empty, add a control to the page. Set the property of the control to the property of the control. + + +## Access Keys and Tab Indexes + For information about how to use the property and the property of a control, see [Accessibility in Visual Studio and ASP.NET](https://learn.microsoft.com/previous-versions/ms228004(v=vs.140)) and [ASP.NET Controls and Accessibility](https://learn.microsoft.com/previous-versions/ms227996(v=vs.140)). + + +## Accessibility + For information about how to configure this control so that it generates markup that conforms to accessibility standards, see [Accessibility in Visual Studio and ASP.NET](https://learn.microsoft.com/previous-versions/ms228004(v=vs.140)) and [ASP.NET Controls and Accessibility](https://learn.microsoft.com/previous-versions/ms227996(v=vs.140)). + + +## Accessing Controls During Page_Load and Page_Init + control properties represented by text boxes, such as and , are accessible during all phases of the page life cycle. In particular, during the Page_Init and Page_Load phases, these properties have the same value they had when the control was rendered. If the user changes the value of the property by modifying the text box, the new value will be available when the changed event is raised, which occurs after the Page_Load phase. Therefore, if you set the value of the property in the Page_Init phase or Page_Load phase and provide a custom handler for a event, any change that the user makes in the text box overrides the value set in the Page_Init or Page_Load phase. + + +## Declarative Syntax + +``` + +         +         +         + +         +         +         +         +         +         +         +                 +                         +                 +         +         +         + +         +         +         +         +         + +``` + + + +## Examples + The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: + +- Are greater than six characters. + +- Contain at least one digit. + +- Contain at least one special (non-alphanumeric) character. + + The password requirements contained in the property are displayed to the user. + + If the password entered by the user does not meet the requirements of the property, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. + > [!NOTE] -> The new password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - +> The new password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/CS/changepasswordpasswordregexcs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: - + :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: + ]]> @@ -350,27 +350,27 @@ Initializes a new instance of the class. - property to define a regular expression that checks passwords to ensure that they meet the following criteria: - -- Are greater than six characters. - -- Contain at least one digit. - -- Contain at least one special (non-alphanumeric) character. - - The password requirements contained in the property are displayed to the user. - - If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. - + property to define a regular expression that checks passwords to ensure that they meet the following criteria: + +- Are greater than six characters. + +- Contain at least one digit. + +- Contain at least one special (non-alphanumeric) character. + + The password requirements contained in the property are displayed to the user. + + If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. + > [!NOTE] -> The new password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - +> The new password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/CS/changepasswordpasswordregexcs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: - + :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: + ]]> @@ -413,11 +413,11 @@ Gets or sets the amount of padding, in pixels, inside the border and the designated area for the control. The number of pixels of space between the contents of a control and the control's border. The default value is 1. - property is stored in view state. - + property is stored in view state. + ]]> The value of the property is less than -1. @@ -479,15 +479,15 @@ Represents the value of the Cancel button. This field is read-only. - field to represent the `CommandName` value of the Cancel button. This is useful when configuring any button to mimic the functionality of the Cancel button of the control. - - To assign cancel functionality to any control contained in the control, set the property of the button to the string that is contained in the field. - - The Cancel button can appear on the ChangePassword template or the Success template. Clicking the Cancel button on the Success template will not undo the password change; it will clear the text boxes. To add custom functionality to the Cancel button, create an event handler for the event. - + field to represent the `CommandName` value of the Cancel button. This is useful when configuring any button to mimic the functionality of the Cancel button of the control. + + To assign cancel functionality to any control contained in the control, set the property of the button to the string that is contained in the field. + + The Cancel button can appear on the ChangePassword template or the Success template. Clicking the Cancel button on the Success template will not undo the password change; it will clear the text boxes. To add custom functionality to the Cancel button, create an event handler for the event. + ]]> @@ -586,27 +586,27 @@ Gets a reference to a collection of properties that define the appearance of the Cancel button on the control. A object that defines the appearance of the Cancel button. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color of the Cancel button. The color can be any of the properties.| -|`BorderColor`|The color of the border around the Cancel button. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the Cancel button. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` setting is greater than 2.| -|`BorderWidth`|The width of the border around the Cancel button.| -|`CssClass`|The cascading style sheet (CSS) class used to render the Cancel button. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the Cancel button text in bold type.| -|`Font-Italic`|`true` to display the Cancel button text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the Cancel button text with a line above it.| -|`Font-Size`|The size of the text in the Cancel button as a object.| -|`Font-Strikeout`|`true` to display the Cancel button text as crossed out.| -|`Font-Underline`|`true` to display the Cancel button text with an underline.| -|`ForeColor`|The color of the text in the Cancel button. The color can be any of the properties.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color of the Cancel button. The color can be any of the properties.| +|`BorderColor`|The color of the border around the Cancel button. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the Cancel button. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` setting is greater than 2.| +|`BorderWidth`|The width of the border around the Cancel button.| +|`CssClass`|The cascading style sheet (CSS) class used to render the Cancel button. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the Cancel button text in bold type.| +|`Font-Italic`|`true` to display the Cancel button text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the Cancel button text with a line above it.| +|`Font-Size`|The size of the text in the Cancel button as a object.| +|`Font-Strikeout`|`true` to display the Cancel button text as crossed out.| +|`Font-Underline`|`true` to display the Cancel button text with an underline.| +|`ForeColor`|The color of the text in the Cancel button. The color can be any of the properties.| + ]]> ASP.NET Login Controls Overview @@ -645,13 +645,13 @@ Gets or sets the text displayed on the Cancel button. The text to display on the Cancel button. The default is "Cancel". - property is "Cancel". - - The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + property is "Cancel". + + The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -690,11 +690,11 @@ Gets or sets the type of button to use for the Cancel button when rendering the control. A object that defines the type of button to render for the Cancel button. The property value can be one of the three enumeration values: , , or . The default is . - property gets or sets the type (`Button`, `Image`, or `Link)` of Cancel button to use when rendering the control. - + property gets or sets the type (`Button`, `Image`, or `Link)` of Cancel button to use when rendering the control. + ]]> The specified is not one of the values. @@ -750,11 +750,11 @@ Gets or sets the URL of the page that the user is shown after clicking the Cancel button in the control. The URL of the page the user is redirected to after clicking the Cancel button. The default is . - and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - + and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -783,19 +783,19 @@ Occurs when the password is changed for a user account. - event is raised after the password is changed by the membership provider specified in the property. After the event is raised, the following occurs: - -- If the property is set, the control attempts to send an email message to the user. - -- The user is either redirected to the Web site specified in the property or the control template specified in the property is displayed. - - The new authorization token for the user is set after the event but before the event. - - For more information about handling events, see [Handling and Raising Events](/dotnet/standard/events/). - + event is raised after the password is changed by the membership provider specified in the property. After the event is raised, the following occurs: + +- If the property is set, the control attempts to send an email message to the user. + +- The user is either redirected to the Web site specified in the property or the control template specified in the property is displayed. + + The new authorization token for the user is set after the event but before the event. + + For more information about handling events, see [Handling and Raising Events](/dotnet/standard/events/). + ]]> @@ -829,15 +829,15 @@ Represents the value of the Change Password button. This field is read-only. - field to represent the `CommandName` value of the Change Password button. This is useful when configuring any button to mimic the functionality of the Change Password button of the control. The Change Password button completes the last step in the control. - - To assign change-password functionality to any control contained in the control, set the property of the button to the string that is contained in the field. - - The Change Password button can appear on the ChangePassword template or the Success template. In both cases, clicking the Change Password button calls the membership provider to change the password. To add custom functionality to the Change Password button, create an event handler for the event. - + field to represent the `CommandName` value of the Change Password button. This is useful when configuring any button to mimic the functionality of the Change Password button of the control. The Change Password button completes the last step in the control. + + To assign change-password functionality to any control contained in the control, set the property of the button to the string that is contained in the field. + + The Change Password button can appear on the ChangePassword template or the Success template. In both cases, clicking the Change Password button calls the membership provider to change the password. To add custom functionality to the Change Password button, create an event handler for the event. + ]]> @@ -934,29 +934,29 @@ Gets a reference to a collection of properties that define the appearance of the Change Password button on the control. A object that defines the appearance of the Change Password button. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color of the Change Password button. The color can be any of the properties.| -|`BorderColor`|The color of the border around the Change Password button. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the Change Password button. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the Change Password button.| -|`CssClass`|The cascading style sheet (CSS) class used to render the Change Password button. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the Change Password button text in bold type.| -|`Font-Italic`|`true` to display the Change Password button text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the Change Password button text with a line above it.| -|`Font-Size`|The size of the text in the Change Password button as a object.| -|`Font-Strikeout`|`true` to display the Change Password button text as crossed out.| -|`Font-Underline`|`true` to display the Change Password button text with an underline.| -|`ForeColor`|The color of the text in the Change Password button. The color can be any of the properties.| -|`Height`|A that represents the height of the Change Password button.| -|`Width`|A that represents the width of the Change Password button.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color of the Change Password button. The color can be any of the properties.| +|`BorderColor`|The color of the border around the Change Password button. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the Change Password button. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the Change Password button.| +|`CssClass`|The cascading style sheet (CSS) class used to render the Change Password button. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the Change Password button text in bold type.| +|`Font-Italic`|`true` to display the Change Password button text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the Change Password button text with a line above it.| +|`Font-Size`|The size of the text in the Change Password button as a object.| +|`Font-Strikeout`|`true` to display the Change Password button text as crossed out.| +|`Font-Underline`|`true` to display the Change Password button text with an underline.| +|`ForeColor`|The color of the text in the Change Password button. The color can be any of the properties.| +|`Height`|A that represents the height of the Change Password button.| +|`Width`|A that represents the width of the Change Password button.| + ]]> ASP.NET Login Controls Overview @@ -995,11 +995,11 @@ Gets or sets the text displayed on the Change Password button. The text to display on the Change Password button. The default is "Change Password". - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -1035,11 +1035,11 @@ Gets or sets the type of button to use when rendering the Change Password button of the control. A object that defines the type of button to render for the Change Password button. The property value can be one of the three enumeration values: , , or . The default is . - property gets or sets the type (`Button`, `Image`, or `Link)` of the Change Password button to use when rendering the control. - + property gets or sets the type (`Button`, `Image`, or `Link)` of the Change Password button to use when rendering the control. + ]]> The specified is not one of the values. @@ -1072,13 +1072,13 @@ Occurs when there is an error changing the password for the user account. - event is raised when the membership provider specified in the property encounters an error while attempting to change the password for a user account. This can occur if the user enters an incorrect current password or an invalid new password. The specified object does not indicate the reason why changing the password failed, only that the password was not changed. - - Use the event to perform custom actions when the password is not changed. - + event is raised when the membership provider specified in the property encounters an error while attempting to change the password for a user account. This can occur if the user enters an incorrect current password or an invalid new password. The specified object does not indicate the reason why changing the password failed, only that the password was not changed. + + Use the event to perform custom actions when the password is not changed. + ]]> @@ -1119,15 +1119,15 @@ Gets or sets the message that is shown when the user's password is not changed. The error message to display when the attempt to change the user's password is not successful. The default is "Your attempt to change passwords was unsuccessful. Please try again." - property is displayed when the membership provider rejects the password entered by the user. - - The object does not return a reason for rejecting the new password. Use the event to examine the rejected password if you want to provide the user with a tip on how to enter an acceptable password (for example, to indicate that a strong password must be provided). - - The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + property is displayed when the membership provider rejects the password entered by the user. + + The object does not return a reason for rejecting the new password. Use the event to examine the rejected password if you want to provide the user with a tip on how to enter an acceptable password (for example, to indicate that a strong password must be provided). + + The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -1176,41 +1176,41 @@ Gets or sets the object used to display the Change Password view of the control. An object that contains the template for displaying the control in the Change Password view. The default is . - property specifies the object used by the control. For more information, see [How To: Create ASP.NET Web Server Control Templates Dynamically](https://learn.microsoft.com/previous-versions/aspnet/0e39s2ck(v=vs.100)). - - A template is a set of HTML elements and controls that make up the layout for a particular portion of a control. Templates differ from styles: - -- Templates define the content of a section of a control. - -- Styles specify the appearance of elements in the control. - - For more information, see [Web Server Controls Templates](https://learn.microsoft.com/previous-versions/aspnet/h59db326(v=vs.100)) and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - - The following table lists the templates and the corresponding control view that are supported by the control. - -|Template name|Control view| -|-------------------|------------------| -||Change Password| -||Success| - - You can also create or modify the template for a control in your .aspx file. For more information, see [How to: Create ASP.NET Web Control Templates Declaratively](https://learn.microsoft.com/previous-versions/aspnet/3326cdex(v=vs.100)) and [How To: Create ASP.NET Web Server Control Templates Dynamically](https://learn.microsoft.com/previous-versions/aspnet/0e39s2ck(v=vs.100)). The procedures in those topics do not require you to configure the property. If you do configure the template, the following table lists the required and optional controls for the template. - -|Control ID|Control type|Required/optional| -|----------------|------------------|------------------------| -|`Cancel`|Any control that causes event bubbling (passing the event up the server control hierarchy), such as the , , and controls. The button command name must be set to the control ID.|Optional| -|`ChangePassword`|Any control that causes event bubbling (passing the event up the server control hierarchy), such as the , , and controls. The button command name must be set to the control ID.|Optional| -|`ConfirmNewPassword`|Any type that supports the interface, such as the class.|Optional| -|`Continue`|Any control that causes event bubbling (passing the event up the server control hierarchy), such as the , , and controls. The button command name must be set to the control ID. This control appears on the Success template.|Optional| -|`CurrentPassword`|Any type that supports the interface, such as the class.|Required| -|`FailureText`|Any type that supports the interface.|Optional| -|`NewPassword`|Any type that supports the interface, such as the class.|Required| -|`UserName`|Any type that supports the interface.|Required if is `true`. Must be absent if is `false`.| - - The control throws an exception if the template does not contain the required controls. No exception is thrown if you give an optional control ID to a control of the wrong type; however, the control is subsequently ignored by the control. - + property specifies the object used by the control. For more information, see [How To: Create ASP.NET Web Server Control Templates Dynamically](https://learn.microsoft.com/previous-versions/aspnet/0e39s2ck(v=vs.100)). + + A template is a set of HTML elements and controls that make up the layout for a particular portion of a control. Templates differ from styles: + +- Templates define the content of a section of a control. + +- Styles specify the appearance of elements in the control. + + For more information, see [Web Server Controls Templates](https://learn.microsoft.com/previous-versions/aspnet/h59db326(v=vs.100)) and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + + The following table lists the templates and the corresponding control view that are supported by the control. + +|Template name|Control view| +|-------------------|------------------| +||Change Password| +||Success| + + You can also create or modify the template for a control in your .aspx file. For more information, see [How to: Create ASP.NET Web Control Templates Declaratively](https://learn.microsoft.com/previous-versions/aspnet/3326cdex(v=vs.100)) and [How To: Create ASP.NET Web Server Control Templates Dynamically](https://learn.microsoft.com/previous-versions/aspnet/0e39s2ck(v=vs.100)). The procedures in those topics do not require you to configure the property. If you do configure the template, the following table lists the required and optional controls for the template. + +|Control ID|Control type|Required/optional| +|----------------|------------------|------------------------| +|`Cancel`|Any control that causes event bubbling (passing the event up the server control hierarchy), such as the , , and controls. The button command name must be set to the control ID.|Optional| +|`ChangePassword`|Any control that causes event bubbling (passing the event up the server control hierarchy), such as the , , and controls. The button command name must be set to the control ID.|Optional| +|`ConfirmNewPassword`|Any type that supports the interface, such as the class.|Optional| +|`Continue`|Any control that causes event bubbling (passing the event up the server control hierarchy), such as the , , and controls. The button command name must be set to the control ID. This control appears on the Success template.|Optional| +|`CurrentPassword`|Any type that supports the interface, such as the class.|Required| +|`FailureText`|Any type that supports the interface.|Optional| +|`NewPassword`|Any type that supports the interface, such as the class.|Required| +|`UserName`|Any type that supports the interface.|Required if is `true`. Must be absent if is `false`.| + + The control throws an exception if the template does not contain the required controls. No exception is thrown if you give an optional control ID to a control of the wrong type; however, the control is subsequently ignored by the control. + ]]> @@ -1285,11 +1285,11 @@ Gets or sets the text displayed at the top of the control in Change Password view. The text to display at the top of the control. The default is "Change Your Password". - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -1318,29 +1318,17 @@ Occurs before the password for a user account is changed by the membership provider. - event is raised before the membership provider specified in the property is called to change the password for a user account. - - Use the event to perform any processing that is necessary before changing the password, such as checking the new password to make sure it is not in a list of common passwords. The new authorization token for the user is set after the event but before the event. - - The event can be canceled by setting the property of the object to `true` if the event handler determines that the membership provider should not be called. - - For more information about handling events, see [Handling and Raising Events](/dotnet/standard/events/). - - - -## Examples - The following code example shows how to use an ASP.NET page that uses a control, and includes a handler for the event named `ChangingPassword`. The code in the event handler compares the old password stored in the property to the new password stored in . If the two passwords are the same, changing the password fails. - - The control sets the property to `true` to enable users to enter their user name. This means that the user does not have to log on to view the page. - - The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/VB/changepassword_vb.aspx" id="Snippet1"::: - + event is raised before the membership provider specified in the property is called to change the password for a user account. + + Use the event to perform any processing that is necessary before changing the password, such as checking the new password to make sure it is not in a list of common passwords. The new authorization token for the user is set after the event but before the event. + + The event can be canceled by setting the property of the object to `true` if the event handler determines that the membership provider should not be called. + + For more information about handling events, see [Handling and Raising Events](/dotnet/standard/events/). + ]]> @@ -1393,20 +1381,20 @@ Gets the duplicate password entered by the user. The duplicate new password string entered by the user. - property contains the duplicate new password entered by the user. - - You can use the property to define the requirements for the new password. This regular expression is used to enforce password rules on the client side. - - The is not related to the password enforcement that can be configured at the data store level and enforced on the server side. The password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - + property contains the duplicate new password entered by the user. + + You can use the property to define the requirements for the new password. This regular expression is used to enforce password rules on the client side. + + The is not related to the password enforcement that can be configured at the data store level and enforced on the server side. The password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + > [!IMPORTANT] -> Transmitting passwords over HTTP is a potential security threat. HTTP transmissions can be viewed or compromised by malicious users. To improve security when using login controls, you should use the HTTPS protocol with secure sockets layer (SSL) encryption to ensure that the user's password cannot be read during postback. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - - This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - +> Transmitting passwords over HTTP is a potential security threat. HTTP transmissions can be viewed or compromised by malicious users. To improve security when using login controls, you should use the HTTPS protocol with secure sockets layer (SSL) encryption to ensure that the user's password cannot be read during postback. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + + This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + ]]> @@ -1447,11 +1435,11 @@ Gets or sets the label text for the text box. The text to display with the text box. The default is "Confirm New Password:". - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -1487,13 +1475,13 @@ Gets or sets the message that is displayed when the new password and the duplicate password entered by the user are not identical. The error message displayed when the new password and confirmed password are not identical. The default is "The confirm New Password entry must match the New Password entry." - control requires the user to enter the new password twice because the password characters are masked on the screen as the user types them. If the user does not enter the same password in both the New Password text box and the Confirm New Password text box, the message in the property is displayed. - - The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + control requires the user to enter the new password twice because the password characters are masked on the screen as the user types them. If the user does not enter the same password in both the New Password text box and the Confirm New Password text box, the message in the property is displayed. + + The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -1531,11 +1519,11 @@ Gets or sets the error message that is displayed when the Confirm New Password text box is left empty. The error message that is displayed when users attempt to change their password without entering the new password in the input box. - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -1593,15 +1581,15 @@ Represents value of the Continue button. This field is read-only. - field to represent the `CommandName` value of the Continue button. This is useful when configuring any button to mimic the functionality of the Continue button of the control. - - To assign continue functionality to any control contained in the control, set the property of the button to the string that is contained in the field. - - The Continue button can appear on the ChangePassword template or the Success template. Clicking the Continue button redirects the user to the URL stored in the property. To add custom functionality to the Continue button, create an event handler for the event. - + field to represent the `CommandName` value of the Continue button. This is useful when configuring any button to mimic the functionality of the Continue button of the control. + + To assign continue functionality to any control contained in the control, set the property of the button to the string that is contained in the field. + + The Continue button can appear on the ChangePassword template or the Success template. Clicking the Continue button redirects the user to the URL stored in the property. To add custom functionality to the Continue button, create an event handler for the event. + ]]> @@ -1700,29 +1688,29 @@ Gets a reference to a collection of properties that define the appearance of the Continue button on the Success view of the control. A object that defines the appearance of the Continue button. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color of the Continue button. The color can be any of the properties.| -|`BorderColor`|The color of the border around the Continue button. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the Continue button. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the Continue button.| -|`CssClass`|The cascading style sheet (CSS) class used to render the Continue button. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the Continue button text in bold type.| -|`Font-Italic`|`true` to display the Continue button text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the Continue button text with a line above it.| -|`Font-Size`|The size of the text in the Continue button as a object.| -|`Font-Strikeout`|`true` to display the Continue button text as crossed out.| -|`Font-Underline`|`true` to display the Continue button text with an underline.| -|`ForeColor`|The color of the text in the Continue button. The color can be any of the properties.| -|`Height`|A that represents the height of the Continue button.| -|`Width`|A that represents the width of the Continue button.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color of the Continue button. The color can be any of the properties.| +|`BorderColor`|The color of the border around the Continue button. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the Continue button. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the Continue button.| +|`CssClass`|The cascading style sheet (CSS) class used to render the Continue button. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the Continue button text in bold type.| +|`Font-Italic`|`true` to display the Continue button text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the Continue button text with a line above it.| +|`Font-Size`|The size of the text in the Continue button as a object.| +|`Font-Strikeout`|`true` to display the Continue button text as crossed out.| +|`Font-Underline`|`true` to display the Continue button text with an underline.| +|`ForeColor`|The color of the text in the Continue button. The color can be any of the properties.| +|`Height`|A that represents the height of the Continue button.| +|`Width`|A that represents the width of the Continue button.| + ]]> ASP.NET Login Controls Overview @@ -1761,11 +1749,11 @@ Gets or sets the text that is displayed on the Continue button on the Success view of the control. The text to display on the Continue button. The default is "Continue". - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -1801,11 +1789,11 @@ Gets or sets the type of button to use when rendering the Continue button for the control. A object that defines the type of button to render for the Continue button. The property value can be one of the three enumeration values: , , or . The default is . - property gets or sets the type (`Button`, `Image`, or `Link)` of the change password button to use when rendering the control. - + property gets or sets the type (`Button`, `Image`, or `Link)` of the change password button to use when rendering the control. + ]]> The specified is not one of the values. @@ -1861,15 +1849,15 @@ Gets or sets the URL of the page that the user will see after clicking the Continue button on the Success view. The URL of the page the user is redirected to after clicking the Continue button. The default is . - property contains the URL of the Web page that users will see after successfully changing their password. By setting the , you can control the first page that users see after changing their password. - - If the property is the default, an field, when the user clicks the Continue button, the page is refreshed and any values on the form are cleared. - - This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - + property contains the URL of the Web page that users will see after successfully changing their password. By setting the , you can control the first page that users see after changing their password. + + If the property is the default, an field, when the user clicks the Continue button, the page is refreshed and any values on the form are cleared. + + This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -1899,25 +1887,25 @@ Creates the individual controls that make up the control in preparation for posting back or rendering. - method creates instances of the controls that make up the control and creates default event handlers for their events. - + method creates instances of the controls that make up the control and creates default event handlers for their events. + ]]> - The property is set to , the contains a control that implements the interface, and the property of the control is set to "UserName". - - -or- - - The property is set to , the does not contain a control that implements the interface, and the property of the control is set to "UserName". - - -or- - - The does not contain a control that implements the interface, and the property of the control is set to "CurrentPassword". - - -or- - + The property is set to , the contains a control that implements the interface, and the property of the control is set to "UserName". + + -or- + + The property is set to , the does not contain a control that implements the interface, and the property of the control is set to "UserName". + + -or- + + The does not contain a control that implements the interface, and the property of the control is set to "CurrentPassword". + + -or- + The does not contain a control that implements the interface, and the property of the control is set to "NewPassword". ASP.NET Login Controls Overview Customizing Appearance and Behavior of the ASP.NET Login Controls @@ -2004,11 +1992,11 @@ Gets or sets the text of the link to the Web page that contains a control for the Web site. The text to display next to the link to the Web page that contains a control for the Web site. The default is . - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -2102,28 +2090,16 @@ Gets the current password for the user. The current password entered by the user. - property contains the current password entered by the user. - + property contains the current password entered by the user. + > [!IMPORTANT] -> Transmitting passwords over HTTP is a potential security threat. HTTP transmissions can be viewed or compromised by malicious users. To improve security when using login controls, you should use HTTPS protocol with secure sockets layer (SSL) encryption to ensure that the user's password cannot be read during postback. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - - This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - - - -## Examples - The following code example shows how to use an ASP.NET page that uses a control, and includes a handler for the event named `ChangingPassword`. The code in the `ChangingPassword` handler compares the old password stored in the property to the new password stored in . If the two passwords are the same, changing the password fails. - - The control sets the property to `true` to enable users to enter their user name. This means that the user does not have to log on to view the page. - - The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/VB/changepassword_vb.aspx" id="Snippet1"::: - +> Transmitting passwords over HTTP is a potential security threat. HTTP transmissions can be viewed or compromised by malicious users. To improve security when using login controls, you should use HTTPS protocol with secure sockets layer (SSL) encryption to ensure that the user's password cannot be read during postback. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + + This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + ]]> @@ -2164,30 +2140,21 @@ if the control should display the ; otherwise, . The default is . - control can display a control to accept the user name. - - You must set the property to `true` if the control will be displayed to users who are not logged on; otherwise, the user will not be able to specify a user name. - - - -## Examples - The following code example shows how to set the property to display the control to users who are not logged on to the Web site. - + control can display a control to accept the user name. + + You must set the property to `true` if the control will be displayed to users who are not logged on; otherwise, the user will not be able to specify a user name. + + + +## Examples + The following code example shows how to set the property to display the control to users who are not logged on to the Web site. + :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/ChangePasswordDisplayUserName/CS/changepassworddisplayusernamecs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordDisplayUserName/VB/changepassworddisplayusernamevb.aspx" id="Snippet1"::: - - The following code example shows how to use an ASP.NET page that uses a control, and includes a handler for the event named `ChangingPassword`. The code in the `ChangingPassword` handler compares the old password stored in the property to the new password stored in . If the two passwords are the same, changing the password fails. - - The control sets the property to `true` to enable the user to enter their user name. This means that the user does not have to log on to view the page. - - The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/VB/changepassword_vb.aspx" id="Snippet1"::: - + :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordDisplayUserName/VB/changepassworddisplayusernamevb.aspx" id="Snippet1"::: + ]]> ASP.NET Login Controls Overview @@ -2277,11 +2244,11 @@ Gets or sets the text of the link to the user profile editing page for the Web site. The text to display for the link to the user profile editing page for the Web site. The default is . - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -2378,29 +2345,29 @@ Gets a reference to a collection of properties that define the appearance of error messages on the control. A object that contains the properties that define the appearance of error messages on the control. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color that appears behind the error message text. The color can be any of the properties.| -|`BorderColor`|The color of the border around the error message text. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the error message text. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the error message text.| -|`CssClass`|The cascading style sheet (CSS) class used to render the error message text. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the error message text in bold type.| -|`Font-Italic`|`true` to display the error message text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the error message text with a line above it.| -|`Font-Size`|The size of the text in the error message as a object.| -|`Font-Strikeout`|`true` to display the error message text as crossed out.| -|`Font-Underline`|`true` to display the error message text with an underline.| -|`ForeColor`|The color of the text in the error message text. The color can be any of the properties.| -|`Height`|A that represents the height of the error message text.| -|`Width`|A that represents the width of the error message text.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color that appears behind the error message text. The color can be any of the properties.| +|`BorderColor`|The color of the border around the error message text. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the error message text. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the error message text.| +|`CssClass`|The cascading style sheet (CSS) class used to render the error message text. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the error message text in bold type.| +|`Font-Italic`|`true` to display the error message text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the error message text with a line above it.| +|`Font-Size`|The size of the text in the error message as a object.| +|`Font-Strikeout`|`true` to display the error message text as crossed out.| +|`Font-Underline`|`true` to display the error message text with an underline.| +|`ForeColor`|The color of the text in the error message text. The color can be any of the properties.| +|`Height`|A that represents the height of the error message text.| +|`Width`|A that represents the width of the error message text.| + ]]> ASP.NET Login Controls Overview @@ -2490,11 +2457,11 @@ Gets or sets the link text to the Change Password help page for the Web site. The text to display for the link to the Change Password help page for the Web site. The default is . - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -2591,29 +2558,29 @@ Gets a reference to a collection of properties that define the appearance of hyperlinks on the control. A object that contains the properties that define the appearance of hyperlinks on the control. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color behind the hyperlink text. The color can be any of the properties.| -|`BorderColor`|The color of the border around the hyperlinks. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the hyperlinks. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the hyperlinks.| -|`CssClass`|The cascading style sheet (CSS) class used to render the hyperlinks. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the hyperlinks text in bold type.| -|`Font-Italic`|`true` to display the hyperlinks text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the hyperlinks text with a line above it.| -|`Font-Size`|The size of the text in the hyperlinks as a object.| -|`Font-Strikeout`|`true` to display the hyperlinks text as crossed out.| -|`Font-Underline`|`true` to display the hyperlinks text with an underline.| -|`ForeColor`|The color of the text in the hyperlinks. The color can be any of the properties.| -|`Height`|A that represents the height of the hyperlinks.| -|`Width`|A that represents the width of the hyperlinks.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color behind the hyperlink text. The color can be any of the properties.| +|`BorderColor`|The color of the border around the hyperlinks. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the hyperlinks. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the hyperlinks.| +|`CssClass`|The cascading style sheet (CSS) class used to render the hyperlinks. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the hyperlinks text in bold type.| +|`Font-Italic`|`true` to display the hyperlinks text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the hyperlinks text with a line above it.| +|`Font-Size`|The size of the text in the hyperlinks as a object.| +|`Font-Strikeout`|`true` to display the hyperlinks text as crossed out.| +|`Font-Underline`|`true` to display the hyperlinks text with an underline.| +|`ForeColor`|The color of the text in the hyperlinks. The color can be any of the properties.| +|`Height`|A that represents the height of the hyperlinks.| +|`Width`|A that represents the width of the hyperlinks.| + ]]> ASP.NET Login Controls Overview @@ -2656,15 +2623,15 @@ Gets or sets informational text that appears on the control between the and the input boxes. The informational text to display on the control between the and the input boxes. The default is . - property gets or sets informational text that appears on the control. The default is . - - Use this property to display general information about your control. You can also use the property to display instructions about password requirements specified in the membership provider or in the property. - - The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + property gets or sets informational text that appears on the control. The default is . + + Use this property to display general information about your control. You can also use the property to display instructions about password requirements specified in the membership provider or in the property. + + The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -2712,29 +2679,29 @@ Gets a reference to a collection of properties that define the appearance of the instructional text on the control. A object that contains the properties that define the appearance of the instructional text contained in the property. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color behind the instructional text. The color can be any of the properties.| -|`BorderColor`|The color of the border around the instructional text. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the instructional text. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the instructional text.| -|`CssClass`|The cascading style sheet (CSS) class used to render the instructional text. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the instructional text in bold type.| -|`Font-Italic`|`true` to display the instructional text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the instructional text with a line above it.| -|`Font-Size`|The size of the text in the instructional text as a object.| -|`Font-Strikeout`|`true` to display the instructional text as crossed out.| -|`Font-Underline`|`true` to display the instructional text with an underline.| -|`ForeColor`|The color of the text in the instructional text. The color can be any of the properties.| -|`Height`|A that represents the height of the instructional text.| -|`Width`|A that represents the width of the instructional text.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color behind the instructional text. The color can be any of the properties.| +|`BorderColor`|The color of the border around the instructional text. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the instructional text. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the instructional text.| +|`CssClass`|The cascading style sheet (CSS) class used to render the instructional text. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the instructional text in bold type.| +|`Font-Italic`|`true` to display the instructional text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the instructional text with a line above it.| +|`Font-Size`|The size of the text in the instructional text as a object.| +|`Font-Strikeout`|`true` to display the instructional text as crossed out.| +|`Font-Underline`|`true` to display the instructional text with an underline.| +|`ForeColor`|The color of the text in the instructional text. The color can be any of the properties.| +|`Height`|A that represents the height of the instructional text.| +|`Width`|A that represents the width of the instructional text.| + ]]> ASP.NET Login Controls Overview @@ -2785,29 +2752,29 @@ Gets a reference to a collection of objects that define the appearance of text box labels on the control. A object that contains the properties that define the appearance of text box labels on the control. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color behind the text box labels. The color can be any of the properties.| -|`BorderColor`|The color of the border around the text box labels. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the text box labels. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the text box labels.| -|`CssClass`|The cascading style sheet (CSS) class used to render the text box labels. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the text box labels text in bold type.| -|`Font-Italic`|`true` to display the text box labels text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the text box labels text with a line above it.| -|`Font-Size`|The size of the text in the text box labels as a object.| -|`Font-Strikeout`|`true` to display the text box labels text as crossed out.| -|`Font-Underline`|`true` to display the text box labels text with an underline.| -|`ForeColor`|The color of the text in the text box labels. The color can be any of the properties.| -|`Height`|A that represents the height of the text box labels.| -|`Width`|A that represents the width of the text box labels.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color behind the text box labels. The color can be any of the properties.| +|`BorderColor`|The color of the border around the text box labels. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the text box labels. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the text box labels.| +|`CssClass`|The cascading style sheet (CSS) class used to render the text box labels. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the text box labels text in bold type.| +|`Font-Italic`|`true` to display the text box labels text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the text box labels text with a line above it.| +|`Font-Size`|The size of the text in the text box labels as a object.| +|`Font-Strikeout`|`true` to display the text box labels text as crossed out.| +|`Font-Underline`|`true` to display the text box labels text with an underline.| +|`ForeColor`|The color of the text in the text box labels. The color can be any of the properties.| +|`Height`|A that represents the height of the text box labels.| +|`Width`|A that represents the width of the text box labels.| + ]]> ASP.NET Login Controls Overview @@ -2843,11 +2810,11 @@ An that represents the control state to restore. Restores control state information from a previous page request that was saved by the method. - method when you need to specify how a custom server control restores its control state. For more information, see [Server Control Custom State Management](https://learn.microsoft.com/previous-versions/aspnet/ms178650(v=vs.100)). - + method when you need to specify how a custom server control restores its control state. For more information, see [Server Control Custom State Management](https://learn.microsoft.com/previous-versions/aspnet/ms178650(v=vs.100)). + ]]> @@ -2878,11 +2845,11 @@ An that represents the control state to restore. Restores view state information from a previous page request that was saved by the method. - method when you need to specify how a custom server control restores its view state. For more information, see [Server Control Custom State Management](https://learn.microsoft.com/previous-versions/aspnet/ms178650(v=vs.100)). - + method when you need to specify how a custom server control restores its view state. For more information, see [Server Control Custom State Management](https://learn.microsoft.com/previous-versions/aspnet/ms178650(v=vs.100)). + ]]> The parameter cannot be resolved to a valid . @@ -2929,41 +2896,41 @@ Gets a reference to a collection of properties that define the email message that is sent to users after they have changed their password. A reference to a object that defines the email message sent to a new user. - property returns a reference to a group of properties that you use to define the format and content of the email message sent to users after they have changed their password. Common settings include the subject line and the sender's return address. For a complete list of properties, see . - - The property is read-only; however, you can set the properties of the object it returns. You can set these properties in the form *property*`-`*subproperty*, where *subproperty* represents a property of the class (for example, `MailDefinition-Subject`). You can also set the properties programmatically in the form *Property*`.`*Subproperty* (for example,`MailDefinition.Subject`). - - An email message is sent only if the user has an email address registered with the membership provider and if the property of the property points to a valid file. If the property is set, the property must be set to an email address; otherwise, an exception is thrown. - - If the email message is created from the object, it will make the substitutions shown in the following table. The substitution text is case-insensitive. - -|Substitution text|Replaced with| -|-----------------------|-------------------| -|**<%** `UserName` **%>**|The Web site user name of the user.| -|**\<%** *Password* **%>**|The new password for the user.| - - If the property of the object is `true`, the contents of the mail message will be HTML-encoded to guard against cross-site scripting security vulnerabilities for the message recipient. - - You can use the event to modify the object that is created by the object. - + property returns a reference to a group of properties that you use to define the format and content of the email message sent to users after they have changed their password. Common settings include the subject line and the sender's return address. For a complete list of properties, see . + + The property is read-only; however, you can set the properties of the object it returns. You can set these properties in the form *property*`-`*subproperty*, where *subproperty* represents a property of the class (for example, `MailDefinition-Subject`). You can also set the properties programmatically in the form *Property*`.`*Subproperty* (for example,`MailDefinition.Subject`). + + An email message is sent only if the user has an email address registered with the membership provider and if the property of the property points to a valid file. If the property is set, the property must be set to an email address; otherwise, an exception is thrown. + + If the email message is created from the object, it will make the substitutions shown in the following table. The substitution text is case-insensitive. + +|Substitution text|Replaced with| +|-----------------------|-------------------| +|**<%** `UserName` **%>**|The Web site user name of the user.| +|**\<%** *Password* **%>**|The new password for the user.| + + If the property of the object is `true`, the contents of the mail message will be HTML-encoded to guard against cross-site scripting security vulnerabilities for the message recipient. + + You can use the event to modify the object that is created by the object. + > [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - - This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - - - -## Examples - The following code example shows how to use the property to define an email message that is sent to users who change their passwords. It assumes that there is a file called `MailFile.txt` that contains the text of the email message to send. - - To be able to send email messages to users, you must configure an email server in the Web.config file for your application. For more information, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). - +> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + + This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + + + +## Examples + The following code example shows how to use the property to define an email message that is sent to users who change their passwords. It assumes that there is a file called `MailFile.txt` that contains the text of the email message to send. + + To be able to send email messages to users, you must configure an email server in the Web.config file for your application. For more information, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). + :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/ChangePasswordMailDefinition/CS/changepasswordmaildefinitioncs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordMailDefinition/VB/changepasswordmaildefinitionvb.aspx" id="Snippet1"::: - + :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordMailDefinition/VB/changepasswordmaildefinitionvb.aspx" id="Snippet1"::: + ]]> The property is not set to an email address. @@ -3007,15 +2974,15 @@ Gets or sets the membership provider that is used to manage member information. The name of the for the control. The default is the membership provider for the application. - property gets or sets the membership provider that is used to look up member information. If the property is `null` or empty, the default membership provider, `AspNetSqlMembershipProvider`, is used. For more information about the membership providers available to ASP.NET applications, see [Membership Providers](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)). - - The new password must meet the minimum requirements set by the membership provider in the , , and properties. If the password does not meet these requirements, the event is raised. - - This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - + property gets or sets the membership provider that is used to look up member information. If the property is `null` or empty, the default membership provider, `AspNetSqlMembershipProvider`, is used. For more information about the membership providers available to ASP.NET applications, see [Membership Providers](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)). + + The new password must meet the minimum requirements set by the membership provider in the , , and properties. If the password does not meet these requirements, the event is raised. + + This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + ]]> @@ -3068,30 +3035,18 @@ Gets the new password entered by the user. The new password entered by the user. - property contains the new password entered by the user. - - You can use the property to define the requirements for the new password. This regular expression is used to enforce password rules on the client side. The is not related to the password enforcement that can be configured at the data store level. The password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - + property contains the new password entered by the user. + + You can use the property to define the requirements for the new password. This regular expression is used to enforce password rules on the client side. The is not related to the password enforcement that can be configured at the data store level. The password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + > [!IMPORTANT] -> Transmitting passwords over HTTP is a potential security threat. HTTP transmissions can be viewed or compromised by malicious users. To improve security when using login controls, you should use HTTPS protocol with secure sockets layer (SSL) encryption to ensure that the user's password cannot be read during postback. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - - This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - - - -## Examples - The following code example shows how to use an ASP.NET page that uses a control, and includes a handler for the event named `ChangingPassword`. `ChangingPassword` compares the old password stored in the property to the new password stored in . If they are the same, changing the password fails. - - The control sets the property to `true` to enable the user to enter their user name. This means that the user does not have to log on to view the page. - - The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/VB/changepassword_vb.aspx" id="Snippet1"::: - +> Transmitting passwords over HTTP is a potential security threat. HTTP transmissions can be viewed or compromised by malicious users. To improve security when using login controls, you should use HTTPS protocol with secure sockets layer (SSL) encryption to ensure that the user's password cannot be read during postback. For more information, see [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + + This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + ]]> @@ -3136,11 +3091,11 @@ Gets or sets the label text for the New Password text box. The text to display next to the New Password text box. The default is "New Password:". - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -3174,40 +3129,40 @@ Gets or sets the regular expression that is used to validate the password provided by the user. The regular expression string used to validate the new password provided by the user. The default is . - property to define the requirements for passwords that are used to validate user accounts on your Web site. This regular expression is used to enforce password rules on the client side. The is not related to the password enforcement that can be configured at the data store level. The password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - - To display requirements to the user, set the property. - - If the password entered does not pass the regular expression contained in the property, the text contained in the property is displayed to the user. - - If the password is rejected by the membership provider, the text contained in the property is displayed. - - A common use of password standards is to force users to select strong passwords. As a best practice, enforce password rules at the data level in the membership provider. The property allows for the convenience of checking the password on the client side, but does not lock out users who make repeated attempts to log on. To improve security, configure your membership provider to restrict the number of attempts a user may make to log on. For more information, see [Securing Membership](https://learn.microsoft.com/previous-versions/aspnet/ms178398(v=vs.100)). - - - -## Examples - The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: - -- Are greater than six characters. - -- Contain at least one digit. - -- Contain at least one special (non-alphanumeric) character. - - The password requirements contained in the property are displayed to the user. - - If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. - + property to define the requirements for passwords that are used to validate user accounts on your Web site. This regular expression is used to enforce password rules on the client side. The is not related to the password enforcement that can be configured at the data store level. The password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + + To display requirements to the user, set the property. + + If the password entered does not pass the regular expression contained in the property, the text contained in the property is displayed to the user. + + If the password is rejected by the membership provider, the text contained in the property is displayed. + + A common use of password standards is to force users to select strong passwords. As a best practice, enforce password rules at the data level in the membership provider. The property allows for the convenience of checking the password on the client side, but does not lock out users who make repeated attempts to log on. To improve security, configure your membership provider to restrict the number of attempts a user may make to log on. For more information, see [Securing Membership](https://learn.microsoft.com/previous-versions/aspnet/ms178398(v=vs.100)). + + + +## Examples + The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: + +- Are greater than six characters. + +- Contain at least one digit. + +- Contain at least one special (non-alphanumeric) character. + + The password requirements contained in the property are displayed to the user. + + If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. + > [!NOTE] -> The new password must also meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - +> The new password must also meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/CS/changepasswordpasswordregexcs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: - + :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: + ]]> @@ -3245,34 +3200,34 @@ Gets or sets the error message that is shown when the password entered does not pass the regular expression criteria defined in the property. The error message shown when the password entered does not pass the regular expression defined in the . The default is . - property to inform the user that the password entered does not pass the regular expression defined in the property. - - The is not related to the password enforcement that can be configured at the data store level. The new password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - - - -## Examples - The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: - -- Are greater than six characters. - -- Contain at least one digit. - -- Contain at least one special (non-alphanumeric) character. - - The password requirements contained in the property are displayed to the user. - - If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. - + property to inform the user that the password entered does not pass the regular expression defined in the property. + + The is not related to the password enforcement that can be configured at the data store level. The new password must meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + + + +## Examples + The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: + +- Are greater than six characters. + +- Contain at least one digit. + +- Contain at least one special (non-alphanumeric) character. + + The password requirements contained in the property are displayed to the user. + + If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. + > [!NOTE] -> The new password must also meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - +> The new password must also meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/CS/changepasswordpasswordregexcs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: - + :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: + ]]> @@ -3312,32 +3267,32 @@ Gets or sets the error message that is displayed when the user leaves the New Password text box empty. The error message to display if the user leaves the New Password text box empty. The default is "New Password is required." - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - - - -## Examples - The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: - -- Are greater than six characters. - -- Contain at least one digit. - -- Contain at least one special (non-alphanumeric) character. - - The password requirements contained in the property are displayed to the user. - - If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + + + +## Examples + The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: + +- Are greater than six characters. + +- Contain at least one digit. + +- Contain at least one special (non-alphanumeric) character. + + The password requirements contained in the property are displayed to the user. + + If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. + > [!NOTE] -> The new password must also meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - +> The new password must also meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/CS/changepasswordpasswordregexcs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: - + :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: + ]]> @@ -3378,11 +3333,11 @@ if the event has been canceled; otherwise, . The default is . - control contains child controls for the Change Password and Success views. Rather than each button raising an event individually, events from the nested controls are bubbled (that is, they are sent to the naming container). The naming container in turn raises a generic event called `ItemCommand` with parameter values that allow you to determine which individual control raised the original event. By responding to this single event, you can avoid writing event-handling methods for individual child controls. - + control contains child controls for the Change Password and Success views. Rather than each button raising an event individually, events from the nested controls are bubbled (that is, they are sent to the naming container). The naming container in turn raises a generic event called `ItemCommand` with parameter values that allow you to determine which individual control raised the original event. By responding to this single event, you can avoid writing event-handling methods for individual child controls. + ]]> Server Event Handling in ASP.NET Web Pages @@ -3444,19 +3399,19 @@ An object that contains the event data. Raises the event after the password is changed. - method is called after the password is changed by the membership provider specified in the property. After the method is called, the following occurs: - -- If the property is set, the control attempts to send an email message to the user. - -- The user is either redirected to the Web site specified in the property or the control template specified in the property is displayed. - - Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). - - The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. - + method is called after the password is changed by the membership provider specified in the property. After the method is called, the following occurs: + +- If the property is set, the control attempts to send an email message to the user. + +- The user is either redirected to the Web site specified in the property or the control template specified in the property is displayed. + + Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). + + The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. + ]]> @@ -3498,17 +3453,17 @@ An object that contains the event data. Raises the event when the user's password is not changed. - method is called when the membership provider specified in the property encounters an error while attempting to change the user's password. The specified object does not indicate the reason why changing the password failed, only that the password was not changed. - - Use the method to perform a custom action when the user's password is not changed. - - Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). - - The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. - + method is called when the membership provider specified in the property encounters an error while attempting to change the user's password. The specified object does not indicate the reason why changing the password failed, only that the password was not changed. + + Use the method to perform a custom action when the user's password is not changed. + + Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). + + The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. + ]]> @@ -3550,31 +3505,19 @@ A object containing the event data. Raises the event before the user's password is changed by the membership provider. - method is called before the membership provider specified in the property is called to change the user's password. - - Use the method to perform any processing that is necessary before changing the password, such as checking the new password to make sure it is not in a list of common passwords. - - The method can cancel the event by setting the property of the object passed as the *e* parameter to `true`. - - Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). - - The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. - - - -## Examples - The following code example shows how to use an ASP.NET page that uses a control, and includes a handler for the event named `ChangingPassword`. `ChangingPassword` compares the old password stored in the property to the new password stored in . If the two passwords are the same, changing the password fails. - - The control sets the property to `true` to enable the user to enter their user name. This means that the user does not have to log on to view the page. - - The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword.OnChangingPassword/VB/changepassword_vb.aspx" id="Snippet1"::: - + method is called before the membership provider specified in the property is called to change the user's password. + + Use the method to perform any processing that is necessary before changing the password, such as checking the new password to make sure it is not in a list of common passwords. + + The method can cancel the event by setting the property of the object passed as the *e* parameter to `true`. + + Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). + + The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. + ]]> @@ -3649,11 +3592,11 @@ An object containing the event data. Raises the event for the control to allow the control to register itself with the page. - method, regardless of whether it is a child or parent to the control. Other Web server controls are not certain to be created and ready for access. - + method, regardless of whether it is a child or parent to the control. Other Web server controls are not certain to be created and ready for access. + ]]> @@ -3721,69 +3664,66 @@ A object containing the event data. Raises the event before an email message is sent to the SMTP server for processing. The SMTP server then sends the email message to the user. - method to modify the email message that is sent to users after they change their password. The property of the object will be sent to the SMTP server for processing. Modify the properties of the object to modify the email message. - - Email messages are created only when the property of the object specified by the property points to a valid file name. - + method to modify the email message that is sent to users after they change their password. The property of the object will be sent to the SMTP server for processing. Modify the properties of the object to modify the email message. + + Email messages are created only when the property of the object specified by the property points to a valid file name. + > [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - - Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). - - The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. This is done in the`SendingMail` event handler. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - +> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + + Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). + + The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. + + + +## Examples + The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). + + If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. This is done in the`SendingMail` event handler. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. + + If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. + + Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the previous example code. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: + + The following example code can be used as the ChangePasswordMail.htm file for the previous example code. + > [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - +> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + +``` + + + +
+ +

Your password for the account named "<%Username%>" has changed.

+ +

+ If you did not initiate this change, please call 1-206-555-0100. +

+ +

+ + Log In + +

+ +

+ Please read our attached Privacy Notice. +

+ +
+ + +``` + ]]>
@@ -3825,68 +3765,19 @@ A object containing the event data. Raises the event when an email message cannot be sent to the user. - method is called when the SMTP mail system raises an exception while attempting to send an email message after a user has changed a password. - - Examine the property of the object passed as the `e` parameter to determine the actual cause of the exception. The most common reason is a configuration error in the `smtp` section of the Web.config file. - - You must set the property of the object passed as the `e` parameter to `true` to signal that the exception has been taken care of; otherwise, the exception is thrown again. - - Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). - - The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. This is done in the`SendingMail` event handler. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the previous example code. - -> [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - + method is called when the SMTP mail system raises an exception while attempting to send an email message after a user has changed a password. + + Examine the property of the object passed as the `e` parameter to determine the actual cause of the exception. The most common reason is a configuration error in the `smtp` section of the Web.config file. + + You must set the property of the object passed as the `e` parameter to `true` to signal that the exception has been taken care of; otherwise, the exception is thrown again. + + Raising an event invokes the event handler through a delegate. For more information, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). + + The method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. + ]]>
@@ -3942,29 +3833,29 @@ Gets a reference to a collection of properties that define the appearance of hint text that appears on the control. A object that contains the properties that define the appearance of the text contained in the property. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color behind the hint text. The color can be any of the properties.| -|`BorderColor`|The color of the border around the hint text. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the hint text. The style can be "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", or "Outset". The default is "NotSet". Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the hint text.| -|`CssClass`|The cascading style sheet (CSS) class used to render the hint text. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the hint text in bold type.| -|`Font-Italic`|`true` to display the hint text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the hint text with a line above it.| -|`Font-Size`|The size of the text in the hint text as a object.| -|`Font-Strikeout`|`true` to display the hint text as crossed out.| -|`Font-Underline`|`true` to display the hint text with an underline.| -|`ForeColor`|The color of the text in the hint text. The color can be any of the properties.| -|`Height`|A that represents the height of the hint text.| -|`Width`|A that represents the width of the hint text.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color behind the hint text. The color can be any of the properties.| +|`BorderColor`|The color of the border around the hint text. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the hint text. The style can be "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", or "Outset". The default is "NotSet". Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the hint text.| +|`CssClass`|The cascading style sheet (CSS) class used to render the hint text. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the hint text in bold type.| +|`Font-Italic`|`true` to display the hint text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the hint text with a line above it.| +|`Font-Size`|The size of the text in the hint text as a object.| +|`Font-Strikeout`|`true` to display the hint text as crossed out.| +|`Font-Underline`|`true` to display the hint text with an underline.| +|`ForeColor`|The color of the text in the hint text. The color can be any of the properties.| +|`Height`|A that represents the height of the hint text.| +|`Width`|A that represents the width of the hint text.| + ]]> @@ -4009,34 +3900,34 @@ Gets or sets informational text about the requirements for creating a password for the Web site. The informational text to display about the criteria for the new password. The default is . - property gets or sets informational text about the requirements for creating a password for the Web site. Use this property to describe the requirements for the new password that are specified in the property. - - The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - - - -## Examples - The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: - -- Are greater than six characters. - -- Contain at least one digit. - -- Contain at least one special (non-alphanumeric) character. - - The password requirements contained in the property are displayed to the user. - - If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. - + property gets or sets informational text about the requirements for creating a password for the Web site. Use this property to describe the requirements for the new password that are specified in the property. + + The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + + + +## Examples + The following code example shows how to set the property to define a regular expression that checks passwords to ensure that they meet the following criteria: + +- Are greater than six characters. + +- Contain at least one digit. + +- Contain at least one special (non-alphanumeric) character. + + The password requirements contained in the property are displayed to the user. + + If the password entered by the user does not meet the criteria, the text contained in the property is displayed to the user. If a new password is not entered, the text contained in the property is displayed to the user. + > [!NOTE] -> The new password must also meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. - +> The new password must also meet the minimum requirements set by the [membership provider](https://learn.microsoft.com/previous-versions/aspnet/sx3h274z(v=vs.100)) in the , , and properties. If the password does not meet these requirements, the event is raised. + :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/CS/changepasswordpasswordregexcs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: - + :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/ChangePasswordNewPasswordRegex/VB/changepasswordpasswordregexvb.aspx" id="Snippet1"::: + ]]> @@ -4075,11 +3966,11 @@ Gets or sets the label text for the Current Password text box. The text to display next to the Current Password text box. The default is "Password:". - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -4168,11 +4059,11 @@ Gets or sets the text of the link to the Web page that contains the control. The text to display for the link to the Web page that contains the control. The default is . - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -4257,13 +4148,13 @@ Gets or sets the error message that is displayed when the user leaves the Current Password text box empty. The error message to display if the user leaves the Current Password text box empty. - property gets or sets the error message that is displayed when the user leaves the Current Password text box empty. - - The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + property gets or sets the error message that is displayed when the user leaves the Current Password text box empty. + + The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -4324,11 +4215,11 @@ if the control encloses rendered HTML in a element; otherwise, . The default is . - apply to all the HTML that is rendered for the control, ASP.NET encloses the rendered HTML in a `table` element. If you do not want the outer `table` element to be rendered, set this property to `false`. In that case, if you try to set inline style properties that apply to the whole control, an exception is thrown. - + apply to all the HTML that is rendered for the control, ASP.NET encloses the rendered HTML in a `table` element. If you do not want the outer `table` element to be rendered, set this property to `false`. In that case, if you try to set inline style properties that apply to the whole control, an exception is thrown. + ]]>
@@ -4354,18 +4245,18 @@ Saves any server control state changes that have occurred since the time the page was posted back to the server. The server control's current state; otherwise, . - method to save state information required for the operation of the control. This control state data is stored separately from the view state data for the control. - - Custom controls using control state must call the method on the object before saving control state. - + method to save state information required for the operation of the control. This control state data is stored separately from the view state data for the control. + + Custom controls using control state must call the method on the object before saving control state. + ]]> - When control state is saved, a string object is returned to the client as a variable that is stored in an HTML <input type="hidden" /> element. Override the method to extract the state information to use in the control. - + When control state is saved, a string object is returned to the client as a variable that is stored in an HTML <input type="hidden" /> element. Override the method to extract the state information to use in the control. + Control state is intended for small amounts of critical data, such as a page index or a keyword. Using control state for large amounts of data can adversely affect page performance. @@ -4392,13 +4283,13 @@ Saves any server control view state changes that have occurred since the time the page was posted back to the server. The server control's current view state; otherwise, . - control. These values are automatically placed in the property for the control, which is an instance of the class. The value for the property is then persisted to a string object after the save state stage of the control life cycle. For more information, see [ASP.NET Page Life Cycle Overview](https://learn.microsoft.com/previous-versions/aspnet/ms178472(v=vs.100)). - - When view state is saved, this string object is returned to the client as a variable that is stored in an HTML `` element. When you author custom server controls, you can improve efficiency by overriding the method and modifying the property for the control. - + control. These values are automatically placed in the property for the control, which is an instance of the class. The value for the property is then persisted to a string object after the save state stage of the control life cycle. For more information, see [ASP.NET Page Life Cycle Overview](https://learn.microsoft.com/previous-versions/aspnet/ms178472(v=vs.100)). + + When view state is saved, this string object is returned to the client as a variable that is stored in an HTML `` element. When you author custom server controls, you can improve efficiency by overriding the method and modifying the property for the control. + ]]> @@ -4423,69 +4314,18 @@ Occurs before the user is sent an email confirmation that the password has been changed. - control will send an email message confirming that the password has been changed when the property defines an email message to send. - - The email message contains automatic replacement fields for the user name and password. You can use the event to modify the email message before it is sent to the user. - -> [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - - For more information about handling events, see [Handling and Raising Events](/dotnet/standard/events/). - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. - - The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. This is done in the`SendingMail` event handler. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the previous example code. - + control will send an email message confirming that the password has been changed when the property defines an email message to send. + + The email message contains automatic replacement fields for the user name and password. You can use the event to modify the email message before it is sent to the user. + > [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - +> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + + For more information about handling events, see [Handling and Raising Events](/dotnet/standard/events/). + ]]>
@@ -4520,64 +4360,15 @@ Occurs when there is an SMTP error sending an email message to the user. - event is raised when the SMTP mail provider throws an exception when trying to send an email message after users have changed their password. The most common reason that this event is raised is that the `smtp` section of the Web.config file is incorrect. For more information about the `smtp` section, see [\ Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/smtp-element-network-settings). - - The default event handler does not catch or handle the SMTP error from the mail system. Your event handler must set the property of the object to `true` in order to stop the error from being displayed to users. - - For more information about handling events, see [Handling and Raising Events](/dotnet/standard/events/). - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. This is done in the`SendingMail` event handler. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the previous example code. - -> [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - + + The default event handler does not catch or handle the SMTP error from the mail system. Your event handler must set the property of the object to `true` in order to stop the error from being displayed to users. + + For more information about handling events, see [Handling and Raising Events](/dotnet/standard/events/). + ]]>
@@ -4660,13 +4451,13 @@ Gets or sets the URL of the page that is shown to users after they have changed their password successfully. The URL of the destination page after the password is changed. The default is . - property when you want users to be redirected to a specific page of your Web site after successfully changing their passwords. If the property is not set (set is the default), the page containing the control is refreshed and the property is displayed. If the property is set, the Success view is not displayed. - - This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - + property when you want users to be redirected to a specific page of your Web site after successfully changing their passwords. If the property is not set (set is the default), the page containing the control is refreshed and the property is displayed. If the property is set, the Success view is not displayed. + + This property cannot be set by themes or style sheet themes. For more information, see and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + ]]> @@ -4715,28 +4506,28 @@ Gets or sets the object that is used to display the Success and Change Password views of the control. An object that contains the template for displaying the Success and Change Password views of the control. The default is . - property specifies the object that is used by the control. The property is accessible only when using a code-behind file. For more information, see [How To: Create ASP.NET Web Server Control Templates Dynamically](https://learn.microsoft.com/previous-versions/aspnet/0e39s2ck(v=vs.100)). - - A template is a set of HTML elements and controls that make up the layout for a particular portion of a control. Templates differ from styles: - -- Templates define the content of a section of a control. - -- Styles specify the appearance of elements in the control. - - For more information, see [Web Server Controls Templates](https://learn.microsoft.com/previous-versions/aspnet/h59db326(v=vs.100)) and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). - - The control supports the following templates, which are applied to the corresponding control view. - -|Template name|Control view| -|-------------------|------------------| -||Change Password view| -||Success view| - - You can also create or modify the template for a control in your .aspx file. For more information, see [How to: Create ASP.NET Web Control Templates Declaratively](https://learn.microsoft.com/previous-versions/aspnet/3326cdex(v=vs.100)). - + property specifies the object that is used by the control. The property is accessible only when using a code-behind file. For more information, see [How To: Create ASP.NET Web Server Control Templates Dynamically](https://learn.microsoft.com/previous-versions/aspnet/0e39s2ck(v=vs.100)). + + A template is a set of HTML elements and controls that make up the layout for a particular portion of a control. Templates differ from styles: + +- Templates define the content of a section of a control. + +- Styles specify the appearance of elements in the control. + + For more information, see [Web Server Controls Templates](https://learn.microsoft.com/previous-versions/aspnet/h59db326(v=vs.100)) and [ASP.NET Themes and Skins](https://learn.microsoft.com/previous-versions/aspnet/ykzx33wh(v=vs.100)). + + The control supports the following templates, which are applied to the corresponding control view. + +|Template name|Control view| +|-------------------|------------------| +||Change Password view| +||Success view| + + You can also create or modify the template for a control in your .aspx file. For more information, see [How to: Create ASP.NET Web Control Templates Declaratively](https://learn.microsoft.com/previous-versions/aspnet/3326cdex(v=vs.100)). + ]]> @@ -4810,13 +4601,13 @@ Gets or sets the text that is displayed on the Success view between the and the Continue button. The text to display on the Success view between the and the Continue button. The default is . - property gets or sets the text that is displayed on the Success view. The default is "Your password has been changed!". - - The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + property gets or sets the text that is displayed on the Success view. The default is "Your password has been changed!". + + The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -4864,29 +4655,29 @@ Gets a collection of properties that define the appearance of text on the Success view. A object that contains the properties that define the appearance of the text contained in the property. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color behind the Success view text. The color can be any of the properties.| -|`BorderColor`|The color of the border around the Success view text. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the Success view text. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the Success view text.| -|`CssClass`|The cascading style sheet (CSS) class used to render the Success view text. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the Success view text in bold type.| -|`Font-Italic`|`true` to display the Success view text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the Success view text with a line above it.| -|`Font-Size`|The size of the text in the Success view text as a object.| -|`Font-Strikeout`|`true` to display the Success view text as crossed out.| -|`Font-Underline`|`true` to display the Success view text with an underline.| -|`ForeColor`|The color of the text in the Success view text. The color can be any of the properties.| -|`Height`|A that represents the height of the Success view text.| -|`Width`|A that represents the width of the Success view text.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color behind the Success view text. The color can be any of the properties.| +|`BorderColor`|The color of the border around the Success view text. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the Success view text. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the Success view text.| +|`CssClass`|The cascading style sheet (CSS) class used to render the Success view text. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the Success view text in bold type.| +|`Font-Italic`|`true` to display the Success view text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the Success view text with a line above it.| +|`Font-Size`|The size of the text in the Success view text as a object.| +|`Font-Strikeout`|`true` to display the Success view text as crossed out.| +|`Font-Underline`|`true` to display the Success view text with an underline.| +|`ForeColor`|The color of the text in the Success view text. The color can be any of the properties.| +|`Height`|A that represents the height of the Success view text.| +|`Width`|A that represents the width of the Success view text.| + ]]> ASP.NET Login Controls Overview @@ -4925,13 +4716,13 @@ Gets or sets the title of the Success view. The text to display as the title in the Success view of the control. The default is "Change Password Complete". - property gets or sets the title of the Success view. The default is "Change Password Complete". - - The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + property gets or sets the title of the Success view. The default is "Change Password Complete". + + The value of this property, when set, can be saved automatically to a resource file by using a designer tool. For more information, see and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> ASP.NET Login Controls Overview @@ -4961,15 +4752,15 @@ Gets the value that corresponds to a control. This property is used primarily by control developers. The value for the control. Always returns . - property to determine the value that is associated with a control. - - The property allows the output stream to write the appropriate HTML markup for the control. - - This property is used primarily by control developers. - + property to determine the value that is associated with a control. + + The property allows the output stream to write the appropriate HTML markup for the control. + + This property is used primarily by control developers. + ]]> @@ -5021,29 +4812,29 @@ Gets a reference to a collection of properties that define the appearance of text box controls on the control. A object that defines the appearance of text box controls on the control. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The background color of text boxes. The color can be any of the properties.| -|`BorderColor`|The color of the border around the text boxes. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the text boxes. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the text boxes.| -|`CssClass`|The cascading style sheet (CSS) class used to render the text boxes. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the text boxes text in bold type.| -|`Font-Italic`|`true` to display the text boxes text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the text boxes text with a line above it.| -|`Font-Size`|The size of the text in the text boxes as a object.| -|`Font-Strikeout`|`true` to display the text boxes text as crossed out.| -|`Font-Underline`|`true` to display the text boxes text with an underline.| -|`ForeColor`|The color of the text in the text boxes. The color can be any of the properties.| -|`Height`|A that represents the height of the text boxes.| -|`Width`|A that represents the width of the text boxes.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The background color of text boxes. The color can be any of the properties.| +|`BorderColor`|The color of the border around the text boxes. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the text boxes. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the text boxes.| +|`CssClass`|The cascading style sheet (CSS) class used to render the text boxes. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the text boxes text in bold type.| +|`Font-Italic`|`true` to display the text boxes text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the text boxes text with a line above it.| +|`Font-Size`|The size of the text in the text boxes as a object.| +|`Font-Strikeout`|`true` to display the text boxes text as crossed out.| +|`Font-Underline`|`true` to display the text boxes text with an underline.| +|`ForeColor`|The color of the text in the text boxes. The color can be any of the properties.| +|`Height`|A that represents the height of the text boxes.| +|`Width`|A that represents the width of the text boxes.| + ]]> ASP.NET Login Controls Overview @@ -5094,29 +4885,29 @@ Gets a reference to a collection of properties that define the appearance of titles on the control. A object that contains the properties that define the appearance of error messages titles on the control. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color behind the titles. The color can be any of the properties.| -|`BorderColor`|The color of the border around the titles. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the titles. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the titles.| -|`CssClass`|The cascading style sheet (CSS) class used to render the titles. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the titles text in bold type.| -|`Font-Italic`|`true` to display the titles text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the titles text with a line above it.| -|`Font-Size`|The size of the text in the titles as a object.| -|`Font-Strikeout`|`true` to display the titles text as crossed out.| -|`Font-Underline`|`true` to display the titles text with an underline.| -|`ForeColor`|The color of the text in the titles. The color can be any of the properties.| -|`Height`|A that represents the height of the titles.| -|`Width`|A that represents the width of the titles.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color behind the titles. The color can be any of the properties.| +|`BorderColor`|The color of the border around the titles. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the titles. The style can be `"None"`, `"Dotted"`, `"Dashed"`, `"Solid"`, `"Double"`, `"Groove"`, `"Ridge"`, `"Inset"`, or `"Outset"`. The default is `"NotSet"`. Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the titles.| +|`CssClass`|The cascading style sheet (CSS) class used to render the titles. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the titles text in bold type.| +|`Font-Italic`|`true` to display the titles text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the titles text with a line above it.| +|`Font-Size`|The size of the text in the titles as a object.| +|`Font-Strikeout`|`true` to display the titles text as crossed out.| +|`Font-Underline`|`true` to display the titles text with an underline.| +|`ForeColor`|The color of the text in the titles. The color can be any of the properties.| +|`Height`|A that represents the height of the titles.| +|`Width`|A that represents the width of the titles.| + ]]> ASP.NET Login Controls Overview @@ -5181,60 +4972,13 @@ Gets or sets the Web site user name for which to change the password. The user name for which to change the password. - property gets the Web site user name for which to change the password. You can also use the property just to get the user name from within the control, without changing the password. Additionally, the property can be used from within an email message that has been created to send email from the control by using the string "\<%UserName%>" in the body of the email message. - + property gets the Web site user name for which to change the password. You can also use the property just to get the user name from within the control, without changing the password. Additionally, the property can be used from within an email message that has been created to send email from the control by using the string "\<%UserName%>" in the body of the email message. + To allow the user to type in a user name, set the property to `true`. If a user is already authenticated, they don't need to enter a user name. - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. This is done in the`SendingMail` event handler. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the previous example code. - -> [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - + ]]>
Securing Login Controls @@ -5268,11 +5012,11 @@ Gets or sets the label for the User Name text box. The text to display next to the User Name textbox. The default string is "User Name:". - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -5309,11 +5053,11 @@ Gets or sets the error message that is displayed when the user leaves the User Name text box empty. The error message to display if the user leaves the User Name text box empty. The default string is "User Name is required.". - and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). - + and [Globalization and Localization](https://learn.microsoft.com/previous-versions/aspnet/c6zyy3s9(v=vs.100)). + ]]> @@ -5362,29 +5106,29 @@ Gets a reference to a collection of properties that define the appearance of error messages that are associated with any input validation used by the control. A object that defines the appearance of error messages that are associated with any input validation used by the control. The default is . - property. - -|Setting|Description| -|-------------|-----------------| -|`BackColor`|The color behind the error messages. The color can be any of the properties.| -|`BorderColor`|The color of the border around the error messages. The color can be any of the properties.| -|`BorderStyle`|The style of the border around the error messages. The style can be "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", or "Outset". The default is "NotSet". Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| -|`BorderWidth`|The width of the border around the error messages.| -|`CssClass`|The cascading style sheet (CSS) class used to render the error messages. If other settings are specified, they will override a style sheet setting.| -|`Font-Bold`|`true` to display the error messages text in bold type.| -|`Font-Italic`|`true` to display the error messages text in italic type.| -|`Font-Names`|The name of the font face.| -|`Font-Overline`|`true` to display the error messages text with a line above it.| -|`Font-Size`|The size of the text in the error messages as a object.| -|`Font-Strikeout`|`true` to display the error messages text as crossed out.| -|`Font-Underline`|`true` to display the error messages text with an underline.| -|`ForeColor`|The color of the text in the error messages. The color can be any of the properties.| -|`Height`|A that represents the height of the error messages.| -|`Width`|A that represents the width of the error messages.| - + property. + +|Setting|Description| +|-------------|-----------------| +|`BackColor`|The color behind the error messages. The color can be any of the properties.| +|`BorderColor`|The color of the border around the error messages. The color can be any of the properties.| +|`BorderStyle`|The style of the border around the error messages. The style can be "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", or "Outset". The default is "NotSet". Some styles do not show up clearly unless the `BorderWidth` value is greater than 2.| +|`BorderWidth`|The width of the border around the error messages.| +|`CssClass`|The cascading style sheet (CSS) class used to render the error messages. If other settings are specified, they will override a style sheet setting.| +|`Font-Bold`|`true` to display the error messages text in bold type.| +|`Font-Italic`|`true` to display the error messages text in italic type.| +|`Font-Names`|The name of the font face.| +|`Font-Overline`|`true` to display the error messages text with a line above it.| +|`Font-Size`|The size of the text in the error messages as a object.| +|`Font-Strikeout`|`true` to display the error messages text as crossed out.| +|`Font-Underline`|`true` to display the error messages text with an underline.| +|`ForeColor`|The color of the text in the error messages. The color can be any of the properties.| +|`Height`|A that represents the height of the error messages.| +|`Width`|A that represents the width of the error messages.| + ]]> ASP.NET Login Controls Overview diff --git a/xml/System.Web.UI.WebControls/EmbeddedMailObject.xml b/xml/System.Web.UI.WebControls/EmbeddedMailObject.xml index f9a43512124..1f163a32b4a 100644 --- a/xml/System.Web.UI.WebControls/EmbeddedMailObject.xml +++ b/xml/System.Web.UI.WebControls/EmbeddedMailObject.xml @@ -23,88 +23,38 @@ Represents an item to embed in an email message constructed using the class. - represents an item to embed in a mail message. These embedded items can be image files such as company logos. Each embedded item is specified by an identifier and a path. - - To ensure that an embedded object is displayed correctly within the email message file, the following conditions must be met: - -- The mail message is in HTML format. - -- The item is an image file (.jpg, .gif, .bmp, and so on). - -- The HTML-formatted body file specified in the property contains a reference to the image file using the following syntax: - - ``` - Alternate Text. - ``` - - If an is added to a mail message and does not fulfill all of the requirements specified previously, it will most likely be displayed as an attachment in the mail message. If an item is referenced by an identifier in the mail message but not included as an embedded item, it will appear as a broken attachment when the mail is viewed. - - The stores a collection of objects for a single mail message. The is used by the property of the object to create the mail message. - - Mail messages that allow embedded objects are configurable in the following Web controls by setting their properties declaratively: - -- - -- - -- - + represents an item to embed in a mail message. These embedded items can be image files such as company logos. Each embedded item is specified by an identifier and a path. + + To ensure that an embedded object is displayed correctly within the email message file, the following conditions must be met: + +- The mail message is in HTML format. + +- The item is an image file (.jpg, .gif, .bmp, and so on). + +- The HTML-formatted body file specified in the property contains a reference to the image file using the following syntax: + + ``` + Alternate Text. + ``` + + If an is added to a mail message and does not fulfill all of the requirements specified previously, it will most likely be displayed as an attachment in the mail message. If an item is referenced by an identifier in the mail message but not included as an embedded item, it will appear as a broken attachment when the mail is viewed. + + The stores a collection of objects for a single mail message. The is used by the property of the object to create the mail message. + + Mail messages that allow embedded objects are configurable in the following Web controls by setting their properties declaratively: + +- + +- + +- + > [!NOTE] -> The values in the and objects are not stored in view state. This protects against malicious users discovering path information for your server. - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the preceding example code. - -> [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - - -``` - +> The values in the and objects are not stored in view state. This protects against malicious users discovering path information for your server. + ]]>
@@ -152,11 +102,11 @@ Initializes a new instance of the class. - property. To get or set the path to the embedded item, use the property. Both properties must be set to successfully embed the item in the mail message. - + property. To get or set the path to the embedded item, use the property. Both properties must be set to successfully embed the item in the mail message. + ]]> @@ -185,62 +135,57 @@ The path used to retrieve an item to embed in the mail message. For more information, see . Initializes a new instance of the class, using the specified identifier name and path to populate the object. - control, and includes an event handler for the event named `SendingMail`. This code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - The following code example demonstrates using an .aspx page. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword/VB/changepassword_vb.aspx" id="Snippet1"::: - - The following code example demonstrates using a code-behind file. - + control, and includes an event handler for the event named `SendingMail`. This code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). + + If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. + + If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. + + The following code example demonstrates using a code-behind file. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword/CS/changepassword.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword/VB/changepassword.vb" id="Snippet2"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ChangePassword/VB/changepassword.vb" id="Snippet2"::: + + Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. + :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the preceding example code. - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: + + The following example code can be used as the ChangePasswordMail.htm file for the preceding example code. + > [!IMPORTANT] -> Sending user account names or passwords in an email message is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - +> Sending user account names or passwords in an email message is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). + +``` + + + +
+ +

Your password for the account named "<%Username%>" has changed.

+ +

+ If you did not initiate this change, please call 1-206-555-0100. +

+ +

+ + Log In + +

+ +

+ Please read our attached Privacy Notice. +

+ +
+ + +``` + ]]>
@@ -282,68 +227,19 @@ Gets or sets the name that is used as the identifier of the item to be embedded in a mail message constructed with the class. Returns the identifier of the item to embed in a mail message. - property specifies an identifier for an item to embed in a mail message constructed declaratively with the class. The identifier is used to map the item contained in the property to its appropriate location in the body of the file specified in the property, using the following syntax: - -``` -Alternate Text -``` - - Typically, the item is an image file. The default for the property is an empty string. - - It is a best practice for accessibility design to set the alternate text property in your mail message for any embedded images. - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the preceding example code. - -> [!IMPORTANT] -> Sending user account names or passwords in an email message is a potential security threat. Email messages are sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - + property specifies an identifier for an item to embed in a mail message constructed declaratively with the class. The identifier is used to map the item contained in the property to its appropriate location in the body of the file specified in the property, using the following syntax: + +``` +Alternate Text +``` + + Typically, the item is an image file. The default for the property is an empty string. + + It is a best practice for accessibility design to set the alternate text property in your mail message for any embedded images. + ]]>
@@ -396,62 +292,13 @@ Gets or sets the path that is used to retrieve an item to embed in a mail message constructed with the class. Returns the path to the item to embed in a mail message. - property specifies the path to the item you want to embed in the mail message constructed declaratively with the object. The file path in must be a path such as C:\MyServer\Banner.gif. Typically, the embedded item is an image file. If an image file is referenced by its identifier in the mail message but not included in the message, the image appears as a broken attachment when the email message is viewed. - - It is a best practice for accessibility design to set the alternate text property in your mail message for any embedded images. - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the preceding example code. - -> [!IMPORTANT] -> Sending user account names or passwords in an email message is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - + property specifies the path to the item you want to embed in the mail message constructed declaratively with the object. The file path in must be a path such as C:\MyServer\Banner.gif. Typically, the embedded item is an image file. If an image file is referenced by its identifier in the mail message but not included in the message, the image appears as a broken attachment when the email message is viewed. + + It is a best practice for accessibility design to set the alternate text property in your mail message for any embedded images. + ]]>
diff --git a/xml/System.Web.UI.WebControls/EmbeddedMailObjectsCollection.xml b/xml/System.Web.UI.WebControls/EmbeddedMailObjectsCollection.xml index a0b1061b503..d70c3c38c9f 100644 --- a/xml/System.Web.UI.WebControls/EmbeddedMailObjectsCollection.xml +++ b/xml/System.Web.UI.WebControls/EmbeddedMailObjectsCollection.xml @@ -27,71 +27,20 @@ Represents an ordered set of objects. - stores references to items that will be embedded in an email message. The embedded items can be image files such as company logos. The is used by the property of the object. - - Email messages that allow embedded objects are configurable in the following Web controls by setting their properties declaratively: - -- - -- - -- - + stores references to items that will be embedded in an email message. The embedded items can be image files such as company logos. The is used by the property of the object. + + Email messages that allow embedded objects are configurable in the following Web controls by setting their properties declaratively: + +- +- +- + > [!NOTE] -> The values in the and objects are not stored in view state. This protects against malicious users discovering path information for your server. - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendingMail`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - - The following example code can be used as the ChangePasswordMail.htm file for the preceding example code. - -> [!IMPORTANT] -> Sending user account names or passwords in email is a potential security threat. Email messages are typically sent in plain text and can be read by special network "sniffing" applications. To improve security, use the mitigations that are described in [Securing Login Controls](https://learn.microsoft.com/previous-versions/aspnet/ms178346(v=vs.100)). - -``` - - - -
- -

Your password for the account named "<%Username%>" has changed.

- -

- If you did not initiate this change, please call 1-206-555-0100. -

- -

- - Log In - -

- -

- Please read our attached Privacy Notice. -

- -
- - -``` - +> The values in the and objects are not stored in view state. This protects against malicious users discovering path information for your server. + ]]>
@@ -190,11 +139,11 @@ if the contains ; otherwise, . - method to identify the position of the in the . - + method to identify the position of the in the . + ]]> @@ -297,11 +246,11 @@ An object to insert into the . Inserts an into the object at the specified index position. - . If `index` equals the number of items in the , `value` is appended to the end. - + . If `index` equals the number of items in the , `value` is appended to the end. + ]]> The specified is out of range of the collection. @@ -338,30 +287,30 @@ Returns a specific element of a , identified by its position. Returns the at the location specified by the parameter. - property is the default property for a collection. Therefore, the following lines of code are equivalent: - -```vb -myObject = myCollection(index) -myObject = myCollection.Item(index) -``` - -```csharp -myObject = myCollection[index]; -myObject = myCollection.Item[index]; -``` - + property is the default property for a collection. Therefore, the following lines of code are equivalent: + +```vb +myObject = myCollection(index) +myObject = myCollection.Item(index) +``` + +```csharp +myObject = myCollection[index]; +myObject = myCollection.Item[index]; +``` + ]]> - is less than zero. - - -or- - + is less than zero. + + -or- + is equal to or greater than the number of items in the collection. @@ -419,11 +368,11 @@ myObject = myCollection.Item[index]; The to remove from the . Removes the first occurrence of the specified from the . - method uses the information contained in the to identify the item to remove from the collection. - + method uses the information contained in the to identify the item to remove from the collection. + ]]> diff --git a/xml/System.Web.UI.WebControls/ParameterCollection.xml b/xml/System.Web.UI.WebControls/ParameterCollection.xml index 37e0886e98d..ae6bc2602c9 100644 --- a/xml/System.Web.UI.WebControls/ParameterCollection.xml +++ b/xml/System.Web.UI.WebControls/ParameterCollection.xml @@ -187,17 +187,6 @@ ## Remarks Use the method to create and append a object with a default value to the end of the collection. This implementation of the method creates the object using the name and default value specified by the `name` and `value` parameters, respectively, and appends it to the collection. - - -## Examples - The following code example demonstrates how the method can be used to add new objects to a collection by supplying the `name` and `value` parameters. In this example, a object is added to an Update command of an Access data source control that is bound to the value of a control. - -> [!IMPORTANT] -> This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see [Script Exploits Overview](https://learn.microsoft.com/previous-versions/aspnet/w1sw53ds(v=vs.100)). - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/CS/paramcoll2cs.aspx" id="Snippet2"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/VB/paramcoll2vb.aspx" id="Snippet2"::: - ]]> @@ -273,14 +262,6 @@ ## Remarks Use the method to create and append a strongly typed object with a default value to the end of the collection. This implementation of the method creates the object using the name, type and value specified by the `name`, `type` and `value` parameters, respectively, and appends it to the collection. - - -## Examples - The following code example demonstrates how the method can be used to add new objects to a collection by supplying the `name`, `value`, and `type` parameters. In this example, a object is added to an Update command of an Access data source control that provides the value of the current system time. The parameter is added with the of . - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/CS/paramcoll2cs.aspx" id="Snippet2"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.ParameterCollection_2/VB/paramcoll2vb.aspx" id="Snippet2"::: - ]]> diff --git a/xml/System.Web.UI.WebControls/SendMailErrorEventArgs.xml b/xml/System.Web.UI.WebControls/SendMailErrorEventArgs.xml index 0d1a8eb18ce..5638dffeca5 100644 --- a/xml/System.Web.UI.WebControls/SendMailErrorEventArgs.xml +++ b/xml/System.Web.UI.WebControls/SendMailErrorEventArgs.xml @@ -17,40 +17,23 @@ Provides data for the event of controls such as the control, the control, and the control. - object contains an error message that is raised by the SMTP mail provider when an email message cannot be sent by the control, or the control. In such a case, the object is sent to the . - - Create a delegate to handle the event. Handling the event allows your Web application to continue to run even though an exception has occurred. This is useful when it is not critical to send an email message. For example, if the exception occurs when a user is working through a multi-step wizard, it can be advantageous to log the error, display an informative message to the user, and allow the user to complete the wizard. - - Examine the property to determine the actual cause of the exception. The most common reason for the exception is a configuration error in the [<smtp> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/smtp-element-network-settings) of the machine configuration file. Although an error like this is typically discovered during the development and debugging of an application, mail servers can fail unexpectedly in a production environment, and you must determine whether you want the entire application to fail in that situation. If not, handling the event allows your application to proceed. - - You must set the property to `true` to signal that the exception has been handled; otherwise, the exception is rethrown, and will include the original call stack and error message. - - If you do not create an event handler for the event, or if you create an event handler but leave the property set to `false`, your Web application will stop running if an error occurs when sending an email message, and ASP.NET will display an error message. - - The method also allows derived classes to handle the event, instead of this being done by the . This is the preferred technique for handling the event in a class that is derived from or . - - For more information about handling events, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named SendMailError. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - + object contains an error message that is raised by the SMTP mail provider when an email message cannot be sent by the control, or the control. In such a case, the object is sent to the . + + Create a delegate to handle the event. Handling the event allows your Web application to continue to run even though an exception has occurred. This is useful when it is not critical to send an email message. For example, if the exception occurs when a user is working through a multi-step wizard, it can be advantageous to log the error, display an informative message to the user, and allow the user to complete the wizard. + + Examine the property to determine the actual cause of the exception. The most common reason for the exception is a configuration error in the [<smtp> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/smtp-element-network-settings) of the machine configuration file. Although an error like this is typically discovered during the development and debugging of an application, mail servers can fail unexpectedly in a production environment, and you must determine whether you want the entire application to fail in that situation. If not, handling the event allows your application to proceed. + + You must set the property to `true` to signal that the exception has been handled; otherwise, the exception is rethrown, and will include the original call stack and error message. + + If you do not create an event handler for the event, or if you create an event handler but leave the property set to `false`, your Web application will stop running if an error occurs when sending an email message, and ASP.NET will display an error message. + + The method also allows derived classes to handle the event, instead of this being done by the . This is the preferred technique for handling the event in a class that is derived from or . + + For more information about handling events, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). + ]]> @@ -132,32 +115,15 @@ Returns the exception thrown by an SMTP mail service when an email message cannot be sent. An object that contains the exception. - property contains the exception that is thrown by the SMTP mail provider when an email message cannot be sent by the control or the . The most common reason for this exception is a configuration error in the [<smtp> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/smtp-element-network-settings) of the machine configuration file, which produces the following exception message: `The transport failed to connect to the server.` - - Exceptions are not thrown if there is an error in the email message when embedding a file using . Instead, the embedded file appears broken when the mail message is viewed. - - You must set the object, passed as the `e` parameter of , to `true` to signal that the exception has been handled; otherwise, the exception is rethrown, and includes the original call stack and error message. - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendMailError`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - + property contains the exception that is thrown by the SMTP mail provider when an email message cannot be sent by the control or the . The most common reason for this exception is a configuration error in the [<smtp> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/smtp-element-network-settings) of the machine configuration file, which produces the following exception message: `The transport failed to connect to the server.` + + Exceptions are not thrown if there is an error in the email message when embedding a file using . Instead, the embedded file appears broken when the mail message is viewed. + + You must set the object, passed as the `e` parameter of , to `true` to signal that the exception has been handled; otherwise, the exception is rethrown, and includes the original call stack and error message. + ]]> @@ -197,34 +163,17 @@ Indicates if the SMTP exception that is contained in the property has been handled. - If , the exception is consumed and handled by the delegate. If , the exception is rethrown, including the original call stack and error message. - + If , the exception is consumed and handled by the delegate. If , the exception is rethrown, including the original call stack and error message. + The default is . - property indicates if the has been handled. The exception is raised by the SMTP mail provider when an email message cannot be sent by the control or the . The most common reason for the exception is a configuration error in the [<smtp> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/smtp-element-network-settings) of the machine configuration file. Although an error like this is typically discovered during the development and debugging of an application, mail servers can fail unexpectedly in a production environment, and you must determine whether you want the entire application to fail in that situation. If not, handling the event allows your application to proceed. - - If you do not create an event handler for the event, or if you create an event handler but leave the property set to `false`, your Web application will stop running if an error occurs when sending an email message, and ASP.NET will display an error message. Handling the event allows your Web application to continue to run even though an exception has occurred. This is useful when it is not critical to send an email message. For example, if the exception occurs when a user is working through a multi-step wizard, it can be advantageous to log the error, display an informative message to the user, and allow the user to complete the wizard. - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendMailError`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code in the `SendingMail` event handler attempts to send an email message to the user to confirm the change. SMTP must already be configured on the server in order for this code example to work. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - + property indicates if the has been handled. The exception is raised by the SMTP mail provider when an email message cannot be sent by the control or the . The most common reason for the exception is a configuration error in the [<smtp> Element (Network Settings)](/dotnet/framework/configure-apps/file-schema/network/smtp-element-network-settings) of the machine configuration file. Although an error like this is typically discovered during the development and debugging of an application, mail servers can fail unexpectedly in a production environment, and you must determine whether you want the entire application to fail in that situation. If not, handling the event allows your application to proceed. + + If you do not create an event handler for the event, or if you create an event handler but leave the property set to `false`, your Web application will stop running if an error occurs when sending an email message, and ASP.NET will display an error message. Handling the event allows your Web application to continue to run even though an exception has occurred. This is useful when it is not critical to send an email message. For example, if the exception occurs when a user is working through a multi-step wizard, it can be advantageous to log the error, display an informative message to the user, and allow the user to complete the wizard. + ]]> diff --git a/xml/System.Web.UI.WebControls/SendMailErrorEventHandler.xml b/xml/System.Web.UI.WebControls/SendMailErrorEventHandler.xml index ffa52054aa8..f5fc7c49bdd 100644 --- a/xml/System.Web.UI.WebControls/SendMailErrorEventHandler.xml +++ b/xml/System.Web.UI.WebControls/SendMailErrorEventHandler.xml @@ -25,36 +25,19 @@ A object that contains the event data. Represents the method that handles the event of controls such as the control, the control, and the control. - delegate, you identify the method that will handle the event. To associate the event with the event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate from the event. For more information about event-handler delegates, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). - - Handling the `SendMailError` event allows your Web application to continue running, even if an exception occurs when trying to send an email message. For example, this is useful if the exception occurs when a user is working through a multi-step wizard. It is preferable to log the error, display an informative message to the user, and allow the user to complete the wizard rather than terminate the application. - - If you do not create an event handler for the event, or if you create an event handler but leave the property set to `false`, your Web application will stop running if an error occurs when sending an email message, and ASP.NET will display an error message. - - The method also allows derived classes to handle the event instead of the . This is the preferred technique for handling the event in a class that is derived from or . - - For more information about handling events, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). - - - -## Examples - The following code example demonstrates an ASP.NET page that uses a Web control, and includes an event handler for the event named `SendMailError`. The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. For more information, see [How to: Implement Simple Forms Authentication](https://learn.microsoft.com/previous-versions/aspnet/xdt4thhy(v=vs.100)). - - If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. This is done in the `SendingMail` event handler. For information about how to configure an SMTP server, see [How to: Install and Configure SMTP Virtual Servers in IIS 6.0](https://learn.microsoft.com/previous-versions/aspnet/8b83ac7t(v=vs.100)). For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message. - - If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the `SendMailError` function is called. A message is displayed to the user. In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. See the code example below to create the specified event source. For more information about creating an event source, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). The property of the object is set to `true` to indicate that the error has been handled. - - :::code language="aspx-csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/CS/changepassword_cs.aspx" id="Snippet1"::: - :::code language="aspx-vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Web.UI.WebControls.SendMailErrorEventHandler/VB/changepassword_vb.aspx" id="Snippet1"::: - - Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. This event source must exist in order for the first code example to work correctly. The following code example requires Administrator privileges. - - :::code language="csharp" source="~/snippets/csharp/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/CS/createeventsource.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_WebNet/System.Diagnostics.EventLog.CreateEventSource/VB/createeventsource.vb" id="Snippet1"::: - + delegate, you identify the method that will handle the event. To associate the event with the event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate from the event. For more information about event-handler delegates, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). + + Handling the `SendMailError` event allows your Web application to continue running, even if an exception occurs when trying to send an email message. For example, this is useful if the exception occurs when a user is working through a multi-step wizard. It is preferable to log the error, display an informative message to the user, and allow the user to complete the wizard rather than terminate the application. + + If you do not create an event handler for the event, or if you create an event handler but leave the property set to `false`, your Web application will stop running if an error occurs when sending an email message, and ASP.NET will display an error message. + + The method also allows derived classes to handle the event instead of the . This is the preferred technique for handling the event in a class that is derived from or . + + For more information about handling events, see [Server Event Handling in ASP.NET Web Forms Pages](https://learn.microsoft.com/previous-versions/aspnet/xax2hw3x(v=vs.100)). + ]]>