Default.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// The code-behind file for Default.aspx.
/// </summary>
public partial class _Default : Page
{
    /// <summary>
    /// Updates a person.  This method executes when the Update button is
    /// clicked.
    /// </summary>
    /// <param name="sender">The event source (not used).</param>
    /// <param name="e">The event arguments (not used).</param>
    protected void UpdatePerson(object sender, EventArgs e)
    {
        // Always check if the page is valid before updating the user
        // (server-side validation).
        if (!this.Page.IsValid)
        {
            // In case of an error, redirect the user to the error page.
            this.Response.Redirect("Error.aspx", false);
            return;
        }

        // Check for any kind of error updating the user.
        try
        {
            // Create a new SQL connection.
            using (SqlConnection connection = Common.NewConnection())
            {
                // Open the connection.
                connection.Open();

                // Create a new command for the stored procedure.
                using (SqlCommand command = NewProcedureCommand(connection))
                {
                    // This is a stored procedure.
                    command.CommandType = CommandType.StoredProcedure;

                    // Store null if the middle name is not set.
                    object middleName =
                        string.IsNullOrEmpty(this.myMiddleName.Text)
                        ? null
                        : this.myMiddleName.Text;

                    // Add the person information to the procedure parameters.
                    AddParameter(command, int.Parse(this.myPersonListBox.SelectedValue), "@PersonId", SqlDbType.Int);
                    AddParameter(command, this.myFirstName.Text, "@FirstName", SqlDbType.NVarChar, 20);
                    AddParameter(command, this.myLastName.Text, "@LastName", SqlDbType.NVarChar, 20);
                    AddParameter(command, middleName, "@MiddleName", SqlDbType.NChar, 1);
                    AddParameter(command, DateTime.Parse(this.myBirthday.Text), "@DateOfBirth", SqlDbType.DateTime);
                    AddParameter(command, myEmploymentStatus.SelectedValue, "@EmploymentStatus", SqlDbType.NChar, 1);
                    AddParameter(command, decimal.Parse(this.myMoney.Text), "@Money", SqlDbType.Money);

                    // The stored procedure does not return a value.
                    command.ExecuteNonQuery();

                    // Get the id of the person and save it as session
                    // data for the Success.aspx page.
                    this.Session[Common.PersonIdKey] =
                        this.myPersonListBox.SelectedValue;
                }
            }

            // Redirect to the Success.aspx page since there were no errors.
            this.Response.Redirect("Success.aspx", false);
            return;
        }
        catch (SqlException error)
        {
            this.Session[Common.ErrorMessageKey] =
                "Unexpected SQL error: " + error.Message;
        }
        catch (Exception error)
        {
            this.Session[Common.ErrorMessageKey] =
                "Unexpected error: " + error.Message;
        }

        // Arriving here indicates there was an error performing the update.
        // Redirect to the error page.
        this.Response.Redirect("Error.aspx", false);
    }

    /// <summary>
    /// Validates a string as a date.
    /// </summary>
    /// <param name="source">The event source.</param>
    /// <param name="args">The event arguments.</param>
    protected void ValidateDate(
        object source,
        ServerValidateEventArgs args)
    {
        DateTime temp;

        // The string must be a valid date.
        this.SaveValidation(
            source,
            args,
            DateTime.TryParse(args.Value, out temp));
    }

    /// <summary>
    /// Validates a string as an employment status (T or F are valid).
    /// </summary>
    /// <param name="source">The event source.</param>
    /// <param name="args">The event arguments.</param>
    protected void ValidateEmploymentStatus(
        object source,
        ServerValidateEventArgs args)
    {
        // The value must be an F or a P.
        this.SaveValidation(
            source,
            args,
            args.Value == "F" || args.Value == "P");
    }

    /// <summary>
    /// Validates a string as an integer.
    /// </summary>
    /// <param name="source">The event source.</param>
    /// <param name="args">The event arguments.</param>
    protected void ValidateInteger(
        object source,
        ServerValidateEventArgs args)
    {
        int temp;

        // The value must be a valid, positive integer.
        this.SaveValidation(
            source,
            args,
            int.TryParse(args.Value, out temp) && temp > 0);
    }

    /// <summary>
    /// Validates a string as money (a float).
    /// </summary>
    /// <param name="source">The event source.</param>
    /// <param name="args">The event arguments.</param>
    protected void ValidateMoney(
        object source,
        ServerValidateEventArgs args)
    {
        float temp;

        // The value must be a valid, positive float.
        this.SaveValidation(
            source,
            args,
            float.TryParse(args.Value, out temp) && temp >= 0.0f);
    }

    /// <summary>
    /// Validates the first or last name, which must be between 1 and 20
    /// characters.
    /// </summary>
    /// <param name="source">The event source.</param>
    /// <param name="args">The event arguments.</param>
    protected void ValidateName(
        object source,
        ServerValidateEventArgs args)
    {
        string temp = args.Value ?? string.Empty;

        // The length must be between 1 and 20.
        this.SaveValidation(
            source,
            args,
            temp.Length >= 1 && temp.Length <= 20);
    }

    /// <summary>
    /// A helper function that saves a validation result into the event
    /// arguments.
    /// </summary>
    /// <param name="source">The event source.</param>
    /// <param name="args">The event arguments.</param>
    /// <param name="isValid">
    /// True indicates the validation was successful.</param>
    private void SaveValidation(
        object source,
        ServerValidateEventArgs args,
        bool isValid)
    {
        // Assign the value and check if it fails.
        if (!(args.IsValid = isValid))
        {
            // Save the error message for the validator into the session data
            // so it is displayed properly by the Error.aspx page.
            this.Session.Add(
                Common.ErrorMessageKey,
                ((IValidator)source).ErrorMessage);
        }
    }

    /// <summary>
    /// Adds a parameter and value to a command for the stored procedure.
    /// </summary>
    /// <param name="command">The SQL command.</param>
    /// <param name="value">The value to add (null is okay).</param>
    /// <param name="parameterName">The name of the parameter.</param>
    /// <param name="databaseType">The database type.</param>
    private static void AddParameter(
        SqlCommand command,
        object value,
        string parameterName,
        SqlDbType databaseType)
    {
        // Use DBNull.Value for null values.
        value = value ?? DBNull.Value;

        SqlParameter parameter = command.Parameters.Add(
            parameterName,
            databaseType);

        parameter.Value = value;
    }

    /// <summary>
    /// Adds a parameter and value to a command for the stored procedure.
    /// </summary>
    /// <param name="command">The SQL command.</param>
    /// <param name="value">The value to add (null is okay).</param>
    /// <param name="parameterName">The name of the parameter.</param>
    /// <param name="databaseType">The database type.</param>
    /// <param name="size">The database type size</param>
    private static void AddParameter(
        SqlCommand command,
        object value,
        string parameterName,
        SqlDbType databaseType,
        int size)
    {
        // Use DBNull.Value for null values.
        value = value ?? DBNull.Value;

        SqlParameter parameter = command.Parameters.Add(
            parameterName,
            databaseType,
            size);

        parameter.Value = value;
    }

    /// <summary>
    /// Creates and returns a new SQL command for the UpdatePersonInstance
    /// stored procedure.
    /// </summary>
    /// <param name="connection">The SQL connection.</param>
    /// <returns>The SQL command for the stored procedure.</returns>
    private static SqlCommand NewProcedureCommand(SqlConnection connection)
    {
        return new SqlCommand("UpdatePersonInstance", connection);
    }
}
Valid HTML 4.01 Valid CSS