Click here to Skip to main content
15,897,187 members
Articles / Web Development / ASP.NET

Generate Stored Procedure Wrapper Methods and Associated Wrapper Classes

Rate me:
Please Sign up or sign in to vote.
3.00/5 (7 votes)
28 Sep 2008CPOL5 min read 45.6K   362   36  
This tool helps developers generate their ADO.NET stored procedure wrapper methods and any related strongly-typed data object class.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class SprocMethodGen : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            //Get input parameters table and bind to grid view
            DataTable inputTable = GetInputParametersTable();
            inputParamsGridView.DataSource = inputTable;
            inputParamsGridView.DataBind();

            //Get result columns table and bind to grid view
            DataTable outputTable = GetOutputColumnsTable();
            outputColumnsGridView.DataSource = outputTable;
            outputColumnsGridView.DataBind();
        }
    }

    /// <summary>
    /// Creates and fills a datatable using the input of the controls on the input parameters grid view.
    /// This makes it easy to modify the contents of the gridview by modifying the table row data and rebinding.
    /// </summary>
    /// <returns>Datatable containing GridView values</returns>
    private DataTable GetInputParametersTable()
    {
        DataTable inputTable = new DataTable();
        inputTable.Columns.AddRange(new DataColumn[] { new DataColumn("Parameter_name_SQL"), new DataColumn("Method_Parameter_name_CSharp"), new DataColumn("DataType"), new DataColumn("Nullable", typeof(Boolean)) });

        for (int i = 0; i < inputParamsGridView.Rows.Count; i++)
        {
            inputTable.Rows.Add(
                ((TextBox)inputParamsGridView.Rows[i].Controls[0].Controls[1]).Text,
                ((TextBox)inputParamsGridView.Rows[i].Controls[1].Controls[1]).Text,
                ((DropDownList )inputParamsGridView.Rows[i].Controls[2].Controls[1]).SelectedValue,
                ((CheckBox)inputParamsGridView.Rows[i].Controls[3].Controls[1]).Checked);
        }

        return inputTable;
        
    }

    /// <summary>
    /// Creates and fills a datatable using the input of the controls on the output columns grid view.
    /// This makes it easy to modify the contents of the gridview by modifying the table row data and rebinding
    /// </summary>
    /// <returns>Datatable containing GridView values</returns>
    private DataTable GetOutputColumnsTable()
    {
        DataTable outputTable = new DataTable();
        outputTable.Columns.AddRange(new DataColumn[] { new DataColumn("Column_Name"), new DataColumn("Class_Property_Name"), new DataColumn("DataType"), new DataColumn("Nullable", typeof(Boolean))});

        for (int i = 0; i < outputColumnsGridView.Rows.Count; i++)
        {
            outputTable.Rows.Add(
                ((TextBox)outputColumnsGridView.Rows[i].Controls[0].Controls[1]).Text,
                ((TextBox)outputColumnsGridView.Rows[i].Controls[1].Controls[1]).Text,
                ((DropDownList)outputColumnsGridView.Rows[i].Controls[2].Controls[1]).SelectedValue,
                ((CheckBox)outputColumnsGridView.Rows[i].Controls[3].Controls[1]).Checked);
        }

        return outputTable;

    }

    /// <summary>
    /// Hides or shows resultsColumnsPanel, readOnlyFirstRow and panelResultType whenever Execution type changes.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlExecutionType_SelectedIndexChanged(object sender, EventArgs e)
    {
        resultColumnsPanel.Visible = readOnlyFirstRow.Visible = ddlExecutionType.SelectedValue.ToLowerInvariant() == "executereader" ? true : false;
        panelResultType.Visible = ddlExecutionType.SelectedValue.ToLowerInvariant() == "executescalar" ? true : false;
    }

    /// <summary>
    /// Adds a row to the input parameters table.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void addInputParamButton_Click(object sender, EventArgs e)
    {
        DataTable inputTable = GetInputParametersTable();
        inputTable.Rows.Add("","","String",true);
        inputParamsGridView.DataSource = inputTable;
        inputParamsGridView.DataBind();
        ShowHideInputHelpLabel();

    }

    /// <summary>
    /// Removes a row from the input parameters table.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void removeInputParamsButton_Click(object sender, EventArgs e)
    {
        DataTable inputTable = GetInputParametersTable();
        int rowindex = ((GridViewRow)((Control)(sender)).Parent.Parent).RowIndex;
        inputTable.Rows.RemoveAt(rowindex);
        inputParamsGridView.DataSource = inputTable;
        inputParamsGridView.DataBind();
        ShowHideInputHelpLabel();

    }

    /// <summary>
    /// Adds a row to the results column table
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void addOutputColumnButton_Click(object sender, EventArgs e)
    {
        DataTable outputTable = GetOutputColumnsTable();
        outputTable.Rows.Add("", "", "String", true);
        outputColumnsGridView.DataSource = outputTable;
        outputColumnsGridView.DataBind();
        ShowHideResultsWrapperClassPanel();

    }

    /// <summary>
    /// Removes a row from the results column table
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void removeOutputColumnsButton_Click(object sender, EventArgs e)
    {
        DataTable outputTable = GetOutputColumnsTable();
        int rowindex = ((GridViewRow)((Control)(sender)).Parent.Parent).RowIndex;
        outputTable.Rows.RemoveAt(rowindex);
        outputColumnsGridView.DataSource = outputTable;
        outputColumnsGridView.DataBind();
        ShowHideResultsWrapperClassPanel();
    }
    /// <summary>
    /// Creates a MethodGenerator object and displays the generated code.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void generateCodeButton_Click(object sender, EventArgs e)
    {
        
        if (IsValid)
        {
            //Create an instance of the MethodGenerator object using information specified by the user.
            MethodGenerator metgen = new MethodGenerator(
                (ExecutionMethods)Enum.Parse(typeof(ExecutionMethods), ddlExecutionType.SelectedValue),
                (DataProviders)Enum.Parse(typeof(DataProviders), ddlDataProvider.SelectedValue),
                readOnlyFirstRow.Checked,
                sprocNameTextBox.Text,
                methodNameTextBox.Text,
                (DataTypes)Enum.Parse(typeof(DataTypes), ddlResultType.SelectedValue),
                resultIsNullable.Checked,
                methodReturnsSprocRetVal.Checked,
                dataWrapperClassName.Text,
                (DotNETVersions)Enum.Parse(typeof(DotNETVersions), ddlDotNetVersion.SelectedValue));

            //Add input parameters to the InputParameters collection
            DataTable inputTable = GetInputParametersTable();

            foreach (DataRow row in inputTable.Rows)
            {
                metgen.InputParameters.Add(new MethodGenerator.Parameter((string)row["Parameter_name_SQL"], (string)row["Method_Parameter_name_CSharp"], (DataTypes)Enum.Parse(typeof(DataTypes), (string)row["DataType"]), (bool)row["Nullable"]));
            }

            //Add result columns to the ResultColumns collection
            DataTable outputTable = GetOutputColumnsTable();
            foreach (DataRow row in outputTable.Rows)
            {
                metgen.ResultColumns.Add(new MethodGenerator.ResultData((string)row["Column_Name"], (string)row["Class_Property_Name"], (DataTypes)Enum.Parse(typeof(DataTypes), (string)row["DataType"]), (bool)row["Nullable"]));
            }

            //Get and display the generated code
            codePanel.Visible = true;
            CodeText.Text = metgen.Code;
            CodeText.Focus();
        }

    }

    /// <summary>
    /// Shows or Hides resultsHelpLabel and dataWrapperClassNamepanel
    /// </summary>
    private void ShowHideResultsWrapperClassPanel()
    {
        resultsHelpLabel.Visible = (outputColumnsGridView.Rows.Count > 0);
        dataWrapperClassNamePanel.Visible = (outputColumnsGridView.Rows.Count > 1);
    }

    /// <summary>
    /// outputColumnValidator valdation method.
    /// This makes sure that at least one output column was specified if ExecuteReader is selected
    /// </summary>
    /// <param name="source"></param>
    /// <param name="args"></param>
    protected void outputColumnValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = !(outputColumnsGridView.Rows.Count == 0 && ddlExecutionType.SelectedValue.ToUpperInvariant() == "EXECUTEREADER");

    }

    /// <summary>
    /// Shows inputHelpLabel if the input parameters is greater than zero, Hides the label otherwise
    /// </summary>
    private void ShowHideInputHelpLabel()
    {
        inputHelpLabel.Visible = (inputParamsGridView.Rows.Count  > 0);
        
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
Sunny has been developing software for the Microsoft-based platforms since the MS-DOS days. He has coded in C, VB (4 to 6) and C#. He enjoys designing and developing server-side .NET distributed applications.

He currently works for a Fortune 500 company. When he's not coding, he likes reading, hanging out with friends and sight-seeing.

Comments and Discussions