Click here to Skip to main content
15,886,026 members
Articles / Database Development / SQL Server

agStoredProc

Rate me:
Please Sign up or sign in to vote.
4.20/5 (10 votes)
19 Nov 20042 min read 66.4K   1.1K   49  
With agStoredProc, you can generate a C# class out of all the stored procedures in a MS-SQL database. No Microsoft ApplicationBlocks needed.
/*
 *This app was developed by Alexander German (agerman77@hotmail.com)	
 * I could have used Microsoft ApplicationBlocks but at that time I
 * didnt know this existed.
 * I, the author, cannot be held liable for any damage that this program
 * causes to your computer. It is all up to you to use it or not.
 * Thanks in advance.
 */

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace agStoredProc
{
	
	public class Form1 : System.Windows.Forms.Form
	{
		#region		Code generated by the Designer
		private System.ComponentModel.Container components = null;
		private System.Windows.Forms.Button btnCreate;
		private System.Windows.Forms.RichTextBox tbClass;
		private System.Windows.Forms.TabControl tabControl1;
		private System.Windows.Forms.TabPage tabPage1;
		private System.Windows.Forms.TabPage tabPage2;
		private System.Windows.Forms.Label lblConString;
		private System.Windows.Forms.TextBox tbConnection;
		private System.Windows.Forms.Label lblClass;
		private System.Windows.Forms.TextBox tbClassname;
		private System.Windows.Forms.Label lblNamespace;
		private System.Windows.Forms.TextBox tbNamespace;
		private System.Windows.Forms.TextBox tbDatabase;
		private System.Windows.Forms.Label lblDatabase;
		private System.Windows.Forms.Label lblExceptions;
		private System.Windows.Forms.TextBox tbSystemException;
		private System.Windows.Forms.TextBox tbSqlException;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.CheckBox cbSqlException;
		private System.Windows.Forms.CheckBox cbSystemException;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.LinkLabel linkLabel1;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.Button btnSave;
		private System.Windows.Forms.SaveFileDialog saveFile;
		private System.Windows.Forms.Label lblMessage;
		private System.Windows.Forms.Label label7;
#endregion
	
		string _namespace, _class;
		string connection = "";
		
		public Form1()
		{
			InitializeComponent();
		}

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
	
		private void InitializeComponent()
		{
			System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
			this.btnCreate = new System.Windows.Forms.Button();
			this.tbClass = new System.Windows.Forms.RichTextBox();
			this.tabControl1 = new System.Windows.Forms.TabControl();
			this.tabPage1 = new System.Windows.Forms.TabPage();
			this.lblConString = new System.Windows.Forms.Label();
			this.tbConnection = new System.Windows.Forms.TextBox();
			this.lblClass = new System.Windows.Forms.Label();
			this.tbClassname = new System.Windows.Forms.TextBox();
			this.lblNamespace = new System.Windows.Forms.Label();
			this.tbNamespace = new System.Windows.Forms.TextBox();
			this.tbDatabase = new System.Windows.Forms.TextBox();
			this.lblDatabase = new System.Windows.Forms.Label();
			this.tabPage2 = new System.Windows.Forms.TabPage();
			this.label7 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.label1 = new System.Windows.Forms.Label();
			this.tbSqlException = new System.Windows.Forms.TextBox();
			this.tbSystemException = new System.Windows.Forms.TextBox();
			this.lblExceptions = new System.Windows.Forms.Label();
			this.cbSqlException = new System.Windows.Forms.CheckBox();
			this.cbSystemException = new System.Windows.Forms.CheckBox();
			this.label3 = new System.Windows.Forms.Label();
			this.linkLabel1 = new System.Windows.Forms.LinkLabel();
			this.label4 = new System.Windows.Forms.Label();
			this.label5 = new System.Windows.Forms.Label();
			this.label6 = new System.Windows.Forms.Label();
			this.btnSave = new System.Windows.Forms.Button();
			this.saveFile = new System.Windows.Forms.SaveFileDialog();
			this.lblMessage = new System.Windows.Forms.Label();
			this.tabControl1.SuspendLayout();
			this.tabPage1.SuspendLayout();
			this.tabPage2.SuspendLayout();
			this.SuspendLayout();
			// 
			// btnCreate
			// 
			this.btnCreate.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.btnCreate.Location = new System.Drawing.Point(544, 144);
			this.btnCreate.Name = "btnCreate";
			this.btnCreate.TabIndex = 0;
			this.btnCreate.Text = "Create class";
			this.btnCreate.Click += new System.EventHandler(this.btnCreate_Click);
			// 
			// tbClass
			// 
			this.tbClass.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.tbClass.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.tbClass.Location = new System.Drawing.Point(0, 176);
			this.tbClass.Name = "tbClass";
			this.tbClass.Size = new System.Drawing.Size(832, 336);
			this.tbClass.TabIndex = 10;
			this.tbClass.Text = "";
			// 
			// tabControl1
			// 
			this.tabControl1.Controls.Add(this.tabPage1);
			this.tabControl1.Controls.Add(this.tabPage2);
			this.tabControl1.Location = new System.Drawing.Point(8, 16);
			this.tabControl1.Name = "tabControl1";
			this.tabControl1.SelectedIndex = 0;
			this.tabControl1.Size = new System.Drawing.Size(528, 152);
			this.tabControl1.TabIndex = 13;
			// 
			// tabPage1
			// 
			this.tabPage1.Controls.Add(this.lblConString);
			this.tabPage1.Controls.Add(this.tbConnection);
			this.tabPage1.Controls.Add(this.lblClass);
			this.tabPage1.Controls.Add(this.tbClassname);
			this.tabPage1.Controls.Add(this.lblNamespace);
			this.tabPage1.Controls.Add(this.tbNamespace);
			this.tabPage1.Controls.Add(this.tbDatabase);
			this.tabPage1.Controls.Add(this.lblDatabase);
			this.tabPage1.Location = new System.Drawing.Point(4, 22);
			this.tabPage1.Name = "tabPage1";
			this.tabPage1.Size = new System.Drawing.Size(520, 126);
			this.tabPage1.TabIndex = 0;
			this.tabPage1.Text = "Main Settings";
			// 
			// lblConString
			// 
			this.lblConString.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.lblConString.Location = new System.Drawing.Point(8, 72);
			this.lblConString.Name = "lblConString";
			this.lblConString.Size = new System.Drawing.Size(240, 16);
			this.lblConString.TabIndex = 20;
			this.lblConString.Text = "Connection String in SqlConnection Objects";
			// 
			// tbConnection
			// 
			this.tbConnection.Location = new System.Drawing.Point(88, 88);
			this.tbConnection.Name = "tbConnection";
			this.tbConnection.Size = new System.Drawing.Size(416, 20);
			this.tbConnection.TabIndex = 19;
			this.tbConnection.Text = "";
			// 
			// lblClass
			// 
			this.lblClass.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.lblClass.Location = new System.Drawing.Point(288, 48);
			this.lblClass.Name = "lblClass";
			this.lblClass.Size = new System.Drawing.Size(40, 16);
			this.lblClass.TabIndex = 18;
			this.lblClass.Text = "Class";
			// 
			// tbClassname
			// 
			this.tbClassname.Location = new System.Drawing.Point(336, 40);
			this.tbClassname.Name = "tbClassname";
			this.tbClassname.Size = new System.Drawing.Size(168, 20);
			this.tbClassname.TabIndex = 17;
			this.tbClassname.Text = "";
			// 
			// lblNamespace
			// 
			this.lblNamespace.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.lblNamespace.Location = new System.Drawing.Point(8, 48);
			this.lblNamespace.Name = "lblNamespace";
			this.lblNamespace.Size = new System.Drawing.Size(72, 16);
			this.lblNamespace.TabIndex = 16;
			this.lblNamespace.Text = "Namespace";
			// 
			// tbNamespace
			// 
			this.tbNamespace.Location = new System.Drawing.Point(88, 40);
			this.tbNamespace.Name = "tbNamespace";
			this.tbNamespace.Size = new System.Drawing.Size(184, 20);
			this.tbNamespace.TabIndex = 15;
			this.tbNamespace.Text = "";
			// 
			// tbDatabase
			// 
			this.tbDatabase.Location = new System.Drawing.Point(88, 8);
			this.tbDatabase.Name = "tbDatabase";
			this.tbDatabase.Size = new System.Drawing.Size(416, 20);
			this.tbDatabase.TabIndex = 14;
			this.tbDatabase.Text = ((string)(configurationAppSettings.GetValue("DatabaseConnection.Text", typeof(string))));
			// 
			// lblDatabase
			// 
			this.lblDatabase.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.lblDatabase.Location = new System.Drawing.Point(8, 8);
			this.lblDatabase.Name = "lblDatabase";
			this.lblDatabase.Size = new System.Drawing.Size(72, 32);
			this.lblDatabase.TabIndex = 13;
			this.lblDatabase.Text = "Database Connection";
			// 
			// tabPage2
			// 
			this.tabPage2.Controls.Add(this.label7);
			this.tabPage2.Controls.Add(this.label2);
			this.tabPage2.Controls.Add(this.label1);
			this.tabPage2.Controls.Add(this.tbSqlException);
			this.tabPage2.Controls.Add(this.tbSystemException);
			this.tabPage2.Controls.Add(this.lblExceptions);
			this.tabPage2.Controls.Add(this.cbSqlException);
			this.tabPage2.Controls.Add(this.cbSystemException);
			this.tabPage2.Location = new System.Drawing.Point(4, 22);
			this.tabPage2.Name = "tabPage2";
			this.tabPage2.Size = new System.Drawing.Size(520, 126);
			this.tabPage2.TabIndex = 1;
			this.tabPage2.Text = "Exceptions";
			// 
			// label7
			// 
			this.label7.BackColor = System.Drawing.Color.Ivory;
			this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label7.Location = new System.Drawing.Point(143, 6);
			this.label7.Name = "label7";
			this.label7.Size = new System.Drawing.Size(361, 24);
			this.label7.TabIndex = 7;
			this.label7.Text = "Custom text for the Exceptions.                                                  " +
				"                                    For example: Exception was found: + myExcept" +
				"ion.Message;";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(48, 88);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(216, 23);
			this.label2.TabIndex = 6;
			this.label2.Text = "Error Message when throwing Exception:";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(48, 48);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(216, 23);
			this.label1.TabIndex = 5;
			this.label1.Text = "Error Message when throwing Exception:";
			// 
			// tbSqlException
			// 
			this.tbSqlException.Location = new System.Drawing.Point(272, 80);
			this.tbSqlException.Name = "tbSqlException";
			this.tbSqlException.Size = new System.Drawing.Size(232, 20);
			this.tbSqlException.TabIndex = 4;
			this.tbSqlException.Text = ((string)(configurationAppSettings.GetValue("SqlException.Text", typeof(string))));
			// 
			// tbSystemException
			// 
			this.tbSystemException.Location = new System.Drawing.Point(272, 40);
			this.tbSystemException.Name = "tbSystemException";
			this.tbSystemException.Size = new System.Drawing.Size(232, 20);
			this.tbSystemException.TabIndex = 3;
			this.tbSystemException.Text = ((string)(configurationAppSettings.GetValue("SystemException.Text", typeof(string))));
			// 
			// lblExceptions
			// 
			this.lblExceptions.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.lblExceptions.Location = new System.Drawing.Point(8, 8);
			this.lblExceptions.Name = "lblExceptions";
			this.lblExceptions.Size = new System.Drawing.Size(120, 16);
			this.lblExceptions.TabIndex = 2;
			this.lblExceptions.Text = "Managed Exceptions";
			// 
			// cbSqlException
			// 
			this.cbSqlException.Checked = true;
			this.cbSqlException.CheckState = System.Windows.Forms.CheckState.Checked;
			this.cbSqlException.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.cbSqlException.Location = new System.Drawing.Point(16, 64);
			this.cbSqlException.Name = "cbSqlException";
			this.cbSqlException.TabIndex = 1;
			this.cbSqlException.Text = "SqlException";
			// 
			// cbSystemException
			// 
			this.cbSystemException.Checked = true;
			this.cbSystemException.CheckState = System.Windows.Forms.CheckState.Checked;
			this.cbSystemException.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.cbSystemException.Location = new System.Drawing.Point(16, 24);
			this.cbSystemException.Name = "cbSystemException";
			this.cbSystemException.Size = new System.Drawing.Size(120, 24);
			this.cbSystemException.TabIndex = 0;
			this.cbSystemException.Text = "System.Exception";
			this.cbSystemException.CheckedChanged += new System.EventHandler(this.cbSystemException_CheckedChanged);
			// 
			// label3
			// 
			this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.label3.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label3.Location = new System.Drawing.Point(738, 128);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(72, 16);
			this.label3.TabIndex = 14;
			this.label3.Text = "Developed by: ";
			// 
			// linkLabel1
			// 
			this.linkLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.linkLabel1.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.linkLabel1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.linkLabel1.Location = new System.Drawing.Point(720, 142);
			this.linkLabel1.Name = "linkLabel1";
			this.linkLabel1.Size = new System.Drawing.Size(104, 19);
			this.linkLabel1.TabIndex = 15;
			this.linkLabel1.TabStop = true;
			this.linkLabel1.Text = "Alexander German";
			this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
			// 
			// label4
			// 
			this.label4.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label4.Location = new System.Drawing.Point(568, 20);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(128, 16);
			this.label4.TabIndex = 16;
			this.label4.Text = "agSToredProc 1.0";
			// 
			// label5
			// 
			this.label5.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.label5.Location = new System.Drawing.Point(568, 40);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(224, 40);
			this.label5.TabIndex = 17;
			this.label5.Text = "Searches all the stored procedures in the database and makes the classes out of t" +
				"hose procedures.";
			// 
			// label6
			// 
			this.label6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.label6.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label6.Location = new System.Drawing.Point(775, 156);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(48, 16);
			this.label6.TabIndex = 18;
			this.label6.Text = "May 2004";
			// 
			// btnSave
			// 
			this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.btnSave.Location = new System.Drawing.Point(748, 517);
			this.btnSave.Name = "btnSave";
			this.btnSave.TabIndex = 20;
			this.btnSave.Text = "Save to file";
			this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
			// 
			// lblMessage
			// 
			this.lblMessage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.lblMessage.Location = new System.Drawing.Point(8, 522);
			this.lblMessage.Name = "lblMessage";
			this.lblMessage.Size = new System.Drawing.Size(152, 16);
			this.lblMessage.TabIndex = 21;
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(832, 542);
			this.Controls.Add(this.lblMessage);
			this.Controls.Add(this.btnSave);
			this.Controls.Add(this.label6);
			this.Controls.Add(this.label5);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.linkLabel1);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.tabControl1);
			this.Controls.Add(this.tbClass);
			this.Controls.Add(this.btnCreate);
			this.Name = "Form1";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "agStoredProc";
			this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
			this.tabControl1.ResumeLayout(false);
			this.tabPage1.ResumeLayout(false);
			this.tabPage2.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion



		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		/// <summary>
		/// Check if the connection string exists, if it doesnt,
		/// there's no need to keep calling code
		/// </summary>
		bool CheckIfExists()
		{
			bool Exists = false;
			SqlConnection mycon = new SqlConnection(connection);
			
			try
			{
				mycon.Open();
				if (mycon.State == ConnectionState.Open)
				Exists = true;
			}

			catch(SqlException sqlEx)
			{
				MessageBox.Show("There's been some error: "+sqlEx.Message, "agStoredProc", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception Ex)
			{
				MessageBox.Show("There's been some error: "+Ex.Message, "agStoredProc", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			finally
			{
				mycon.Close();
			}
			return Exists;
		}


		/// <summary>
		/// This is what puts all the other methods together.
		/// </summary>
		void ProcessAll()
		{
			this.connection = this.tbDatabase.Text;

			if (CheckIfExists())
			{
	//			System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
				
				_namespace = (this.tbNamespace.Text == "") ? "agStoredProcNamespace": this.tbNamespace.Text;
				_class = (this.tbClassname.Text == "") ? "agStoredProcClass": this.tbClassname.Text;

				string strHeader = 
					"\n// Class Generated by agStoredProc"+
					"\n// Thanks for your support"+
					"\n// email: agerman77@hotmail.com"+

					"\n\nusing System;"+
					"\nusing System.Data;"+
					"\nusing System.Data.SqlClient;"+
					
					"\n\nnamespace "+_namespace +"{"+
			
					"\n\n\tpublic class "+_class +
					"\n\t\t{"+
					"\n\n\tpublic "+_class +"(){ }";
	
				StringBuilder str = new StringBuilder();
				str.Append(strHeader);

				GetParameters(str);

				this.tbClass.Text = str.ToString();

				//Here we count how many lines the app has generated
				int i = 0;
				foreach(char linefeed in this.tbClass.Text.ToCharArray())
				{
					if (linefeed == '\n')
						i++;
				}
				this.lblMessage.Text = i.ToString()+" lines generated.";
				MessageBox.Show("Class has been generated successfully!", "agStoredProc", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			else
				this.lblMessage.Text = "";
		}

		private void btnCreate_Click(object sender, System.EventArgs e)
		{
			lblMessage.Text = "Generating class...";
			System.Threading.Thread myThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessAll));
			myThread.Start();
		}


		/// <summary>
		/// Counts the amount of stored procedures in the database.
		/// </summary>
		int Count()
		{
			SqlConnection mycon = new SqlConnection(connection);
			SqlCommand myCommand = new SqlCommand("exec sp_stored_procedures", mycon);

			mycon.Open();
			SqlDataReader myReader = myCommand.ExecuteReader();
			int j = 0;
			while (myReader.Read())
			{
				string sprocname = myReader.GetString(2);
				if ((!sprocname.StartsWith("dt_")) && (sprocname.EndsWith("1")))
				{
					j++;	
				}
			}
			myReader.Close();
			mycon.Close();
			return j;
		}


		/// <summary>
		/// Gets the parameters for each stored procedure
		/// </summary>
		void GetParameters(StringBuilder strBuilder)
		{
			string [] commands = GetCommands();
			SqlConnection mycon = new SqlConnection(connection);

			SqlConnection mycon2 = new SqlConnection(connection);
			
			mycon.Open();
			mycon2.Open();
	
			int i = 0;
		
			bool first = true;
			foreach (string str in commands)
			{
				SqlCommand myCommand = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.PARAMETERS WHERE SPECIFIC_NAME = '"+str+"'", mycon);								
				SqlDataReader myReader = myCommand.ExecuteReader();
		
				if (myReader.HasRows)
				{
					string prms = "";
					SqlCommand cmdParams = new SqlCommand("SELECT DATA_TYPE, PARAMETER_NAME FROM INFORMATION_SCHEMA.PARAMETERS WHERE SPECIFIC_NAME = '"+str+"'", mycon2);
					SqlDataReader ParamsReader = cmdParams.ExecuteReader();
					
					int prm = 0;
					if (ParamsReader.HasRows)
					{
						
						while(ParamsReader.Read())
						{
								string prmname = ParamsReader.GetString(0);
								prms += ParamTypeToString(prmname)+" _"+ParamsReader.GetString(1).Remove(0,1).ToLower() +", ";
								prm++;
						}
					}

					prms = prms.Remove(prms.Length -1, 1);

					strBuilder.Append("\n\n\tpublic void "+commands[i]+"("+prms.Remove(prms.Length -1, 1)+")");
					strBuilder.Append("\n\t{");
			
					string sqlcon = (this.tbConnection.Text == "")? "\""+this.connection+"\"" : this.tbConnection.Text;
					strBuilder.Append("\n\t\tSqlConnection sqlCon = new SqlConnection("+sqlcon+");");
		
					strBuilder.Append("\n\t\tSqlCommand myCommand = new SqlCommand(\""+commands[i]+"\", sqlCon);");
					strBuilder.Append("\n\t\tmyCommand.CommandType = CommandType.StoredProcedure;");

					while(myReader.Read())
					{
							string _size = (myReader.IsDBNull(9)) ? "": ", "+myReader.GetInt32(9).ToString();
					
							string param_name_whole = myReader.GetString(7);
							string param_name = param_name_whole.Remove(0,1);
						
						if(first)
							this.lblMessage.Text = "Getting stored procedures...";
						first = false;

							string _direction = (myReader.GetString(4)=="IN")? "Input" : "Output" ;
							strBuilder.Append("\n\n\t\tSqlParameter prm_"+param_name+" = new SqlParameter(\"@"+param_name+"\", "+GetParamType(myReader.GetString(8))+_size+");");
							strBuilder.Append("\n\t\tprm_"+ param_name+".Value = _"+ param_name.ToLower()+";");
							strBuilder.Append("\n\t\tprm_"+ param_name+".Direction = ParameterDirection."+ _direction+";");

							strBuilder.Append("\n\t\tmyCommand.Parameters.Add(prm_"+param_name+");");
					}
					

					ParamsReader.Close();

					strBuilder.Append("\n\n\t\ttry\n\t\t{");
					strBuilder.Append("\n\t\t\tsqlCon.Open();");
					strBuilder.Append("\n\t\t\tmyCommand.ExecuteNonQuery();\n\t\t}");
								
					if (this.cbSqlException.Checked)
					{
						strBuilder.Append("\n\n\t\tcatch(SqlException sqlEx)\n\t\t{");
						if (this.tbSqlException.Text.Trim() != "")
							strBuilder.Append("\n\t\t\tthrow new Exception(\""+this.tbSqlException.Text+" \" + sqlEx.Message);\n\t\t}");
						else
							strBuilder.Append("\n\t\t\tthrow new Exception(sqlEx.Message);\n\t\t}");
					}
					strBuilder.Append("\n\n\t\tcatch(Exception SystemEx)\n\t\t{");

					if (this.tbSystemException.Text.Trim()!= "")
						strBuilder.Append("\n\t\t\tthrow new Exception(\""+this.tbSystemException.Text+" \" + SystemEx.Message);\n\t\t}");
					else
						strBuilder.Append("\n\t\t\tthrow new Exception(SystemEx.Message);\n\t\t}");
			

					strBuilder.Append("\n\n\t\tfinally\n\t\t{");
					strBuilder.Append("\n\t\t\tsqlCon.Close();\n\t\t}");
					strBuilder.Append("\n\t}");
				}

				i++; 
				myReader.Close();

				}
		
			mycon2.Close();	
			mycon.Close();

			if (i == commands.Length)
			{ 
				strBuilder.Append("\n\n\t}");
				strBuilder.Append("\n}");
			}
		}



	/// <summary>
	/// Gets the parameter type for each parameter
	/// This is for the C# generated class.
	/// For example: bigint in SQL Server = SqlDbType.BigInt in .NET
	/// </summary>
		string GetParamType (string _parameter)
		{
			string param = "";

			switch(_parameter)
			{
					
				case "bigint" :
					param = "SqlDbType.BigInt";
					break;

				case "binary" :
					param = "SqlDbType.Binary";
					break;

				case "char" : 
					param = "SqlDbType.Char";
					break;

				case "datetime" :
					param = "SqlDbType.DateTime";
					break;

				case "decimal" :
					param = "SqlDbType.Decimal";
					break;

				case "float" :
					param = "SqlDbType.Float";
					break;

				case "image" :
					param = "SqlDbType.Image";
					break;

				case "int" :
					param = "SqlDbType.Int";
					break;

				case "money":
					param = "SqlDbType.Money";
					break;

				case "nchar" :
					param = "SqlDbType.NChar";
					break;

				case "ntext" :
					param = "SqlDbType.NText";
					break;

				case "nvarchar" :
					param = "SqlDbType.NVarChar";
					break;
					
				case "real" :
					param = "SqlDbType.Real";
					break;

				case "smalldatetime" :
					param = "SqlDbType.SmallDateTime";
					break;

				case "smallint" :
					param = "SqlDbType.SmallInt";
					break;

				case "text" :
					param = "SqlDbType.Text";
					break;

					
				case "timestamp" :
					param = "SqlDbType.Timestamp";
					break;

				case "tinyint" :
					param = "SqlDbType.TinyInt";
					break;

				case "uniqueindentifier" :
					param = "SqlDbType.UniqueIdentifier";
					break;

				case "varbinary" :
					param = "SqlDbType.VarBinary";
					break;
					

				case "varchar" :
					param = "SqlDbType.VarChar";
					break;
					
				default :
					param = "SqlDbType.VarChar";
					break;
			}

			return param;
		}

	/// <summary>
	/// Converts the parameter type from how it is named in SQL Server to the 
	/// the way it is called in .NET
	/// For example: bigint in SQL Server = int in .NET
	/// This is for the parameters in the methods calling the stored procs
	/// </summary>
		string ParamTypeToString(string parameter)
		{
			string param = "";
			
			switch(parameter)
			{
				case "bigint" :
					param = "int";
					break;

				case "char" : 
					param = "char";
					break;
		
				case "datetime" :
					param = "DateTime";
					break;
 
				case "decimal" :
					param = "decimal";
					break;

				case "float" :
					param = "float";
					break;

				case "int" :
					param = "int";
					break;

				case "money":
					param = "double";
					break;

				case "nchar" :
					param = "char";
					break;

				case "ntext" :
					param = "string";
					break;

				case "nvarchar" :
					param = "string";
					break;
					
				case "real" :
					param = "double";
					break;

				case "smalldatetime" :
					param = "DateTime";
					break;

				case "smallint" :
					param = "int";
					break;

				case "text" :
					param = "string";
					break;

				case "timestamp" :
					param = "DateTime";
					break;

				case "tinyint" :
					param = "int";
					break;

				case "varchar" :
					param = "string";
					break;

				default :
					param = "string";
					break;
			}
			return param;
		}


		/// <summary>
		/// Connects to the database and returns a string type array
		/// with the names of the stored procedures.
		/// </summary>
		string [] GetCommands()
		{
			SqlConnection mycon = new SqlConnection(connection);
			SqlCommand myCommand = new SqlCommand("exec sp_stored_procedures", mycon);
			
			string [] arrProc = {};

			mycon.Open();
				SqlDataReader reader = myCommand.ExecuteReader();
				
				arrProc = new string[Count()];	
				int i = 0;
				if (reader.HasRows)
				{
				
					while (reader.Read())
					{
						string sprocname = reader.GetString(2);
					
						if ((!sprocname.StartsWith("dt_")) && (sprocname.EndsWith("1")))
						{
							arrProc[i] = sprocname.Remove(sprocname.Length -2, 2);
							i++;	
						}
					
					}
				}
	
				reader.Close();
			
			return arrProc;
		}


		/// <summary>
		/// System.Exceptions will always be catched.
		/// This is up to the developer to change if desired.
		/// </summary>
		private void cbSystemException_CheckedChanged(object sender, System.EventArgs e)
		{
			this.cbSystemException.Checked = true;
		}


		private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
		{
			System.Diagnostics.Process.Start("mailto:agerman77@hotmail.com?subject=About agStoredProc 1.0");

		}

		/// <summary>
		/// No need for an explanation here. If so, let me know.
		/// </summary>
		private void btnSave_Click(object sender, System.EventArgs e)
		{
			if (tbClass.Text.Trim() != "")
			{
			
				saveFile.DefaultExt = "*.cs";
				saveFile.Filter = "C# Files|*.cs";

				if(saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
					saveFile.FileName.Length > 0) 
				{
					tbClass.SaveFile(saveFile.FileName, RichTextBoxStreamType.PlainText);
				}
			}

		}

	}
}

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Spain Spain
I have been programming for a few years now, like since 1996. Currently working as freelance.

C#.NET MCP. Works with tools such as Delphi, C#.NET, VB.NET, ASP.NET, ADO.NET, XML, java, j2me, Oracle, mySQL, and Sql Server, etc, etc. Open to everything.

Comments and Discussions