Click here to Skip to main content
Email Password   helpLost your password?

What is this?

DBHelper is a small tool that will generate either a source file or a compiled assembly for selected stored procedures on your SQL server. It uses the CodeDom namespace to output the code. Currently it supports C# and VB.NET code generation (and other language support is likely in the future), but the generated assembly is usable from any .NET language. Also included in version 1.5 is the ability to compile a complete assembly that includes a typed DataSet based on your SQL stored procedures output.

Basically, this is an all-in-one tool for wrapping a SQL database. Great for existing databases, and for rapidly changing databases. E.g. changes gets made to stored procedure's parameters or the output of stored procedures. No problem for DBHelper, just a few clicks and you a have all the methods remapped/DataSet regenerated. All you have to do it adjust your corresponding .NET methods.

NOTE: DBNulls are still not supported. I'm still looking for a way. The alternative is to still generate the source file and the XSD file, and change all the method parameters from their strong type to System.Object. That's all! Hopefully there wont be too many!

New information (version 1.5+)

As of version 1.4, the package comes as a tool rather than a library. Please select the SQL provider (no others will work and I have NO plans to support it). If you tick Create, it will create a corresponding method, and CreateStrong will generate an XSD for strongly typed DataSet/Tables.

Also note VS.NET is NO longer required for typed DataSet generation and compilation (overlooked a static method).

Version 1.6 includes plenty code optimization. Also, typed datasets now get created based on return values. The is no more option to select which ones you want. I have tested it successfully on the MASTER database.

Why?

Some people might ask "Why?". The answer is sweet. Take the following for example:

Every time you even want to execute a simple stored procedure you need something like the following:

SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "ChangeEmail";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id", SqlDbType.BigInt).Value = id_param;
cmd.Parameters.Add("@oldemail", SqlDbType.VarChar).Value = oldemail_param;
cmd.Parameters.Add("@newemail", SqlDbType.VarChar).Value = newemail_param;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();

Now that's only 3 parameters, how about some nasty UPDATE procedures with 10+ parameters? That can be a real time waster, especially doing all the type mapping by hand. On the other hand you could always go for DataSets, and let VS.NET do the work. My personal liking is to use DataSets only for SELECT queries and I usually do all the other statements via SqlCommand's as above. The library will generate all the required parameters and present you with a strongly typed wrapper method for the stored procedure.

UPDATE: I have now updated the library to return a DataTable of the output. For example:

public static DataTable ChangeEmail(SqlConnection connection
    DataTable table, long id_param, 
    string oldemail_param, string newemail_param)

The code from the former example is automatically inserted into a class of choice. Now that looks a lot better, and will probably save you countless hours.

How does it work?

These methods are a bit redundant as of version 1.4 as it run as a tool rather than a library. Firstly your database will be queried for stored procedures. After that we get the name and type of the parameters for each procedure. With the help of CodeDom we create a new class to output to a source file or an assembly.

Constructor

Properties

Methods

Notes

I use a very, very simple mapping from SqlDbType to Type and DBNull values are not supported either in this release.

For the test app to work you will need to change the SqlConnection to your linking.

Free plug

Kristopher Johnson - Typed Collection Class Generator for creating all the collections and dictionaries in DBHelper (although the CodeDom code was not looked at).

Conclusion

This was really my first successful use of CodeDom and it seems really powerful, especially if you use it correctly as output to any language should be possible. As usual, bugs, problems, praise, suggestions, gifts can be added below.

UPDATE: I have created support for VB.NET code as well.

Cheers :)

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Questiondatabase Entry (SQL 2000)
Sapan Jaiswal
10:13 6 Mar '08  
How to store check box(more than one values at a time) to SQL Server 2000 using VB.NET

sapan jaiswal

GeneralHow to use dataset in Sql Server to retrive the data
Janvi
20:50 3 Mar '08  
Hi,
I want to use dataset in my application to retrive data from database which is in sql server. i m writing query in store procedure. so plz send me the code.Confused
GeneralVS.Net 2005 issues & Sample implementation
jcnovoa
11:53 20 Dec '05  
I must say that just working with your code has been an eye opening experience regarding the possibilities of strongly tying business rules(GUI) to auto generated Data Access Layers providing a way to force re-compilation of code every time a stored procedure gets changed in the database:
Thank you. Laugh

Just a couple of things when using the source code in VS.Net 2005
1) Need to add "System.Xml.dll" as a param to SP.cs: param.ReferencedAssemblies.Add("System.Xml.dll");
2) Warning in Form1.cs of SPTestAp [Obsolete("TypedDataSetGenerator class will be removed in a future release. Please use System.Data.Design.TypedDataSetGenerator in System.Design.dll.")]
When trying to refactor it with the new dll (System.Design.dll), I loose my access to my SPs public functions, so not sure what we will do when this is deprecated for the next version. Works for now on VS.Net 2005
3) changed method.Attributes = MemberAttributes.Public | MemberAttributes.Public;// | MemberAttributes.Static;
In SP.cs to make sure I could get to everything I need from the DAO.(good while debugging the implementation)
4) Sample implementation of a SP*.dll (the name of my SP is usp_PAY_EMPLOYEES_Form_Select)

System.Data.SqlClient.SqlConnection myConn = new System.Data.SqlClient.SqlConnection("server=JC;uid=sa;pwd=;database=DEV");
DataTable myDataTable = new DataTable();
int myEmpCount = 0;
DEV.DEV myDev = new DEV.DEV();
DEV.SP mySP = new DEV.SP();
//use a strongly typed data table to pass to the procedure
myEmpCount = mySP.usp_PAY_EMPLOYEES_Form_Select(myConn, myDev.usp_PAY_EMPLOYEES_Form_Select, 65);
this.dataGridView2.DataSource = myDev.usp_PAY_EMPLOYEES_Form_Select;
//use a strongly typed datarow to get to the columns within the strongly typed DataTable

foreach (DEV.DEV.usp_PAY_EMPLOYEES_Form_SelectRow myRowCol in myDev.usp_PAY_EMPLOYEES_Form_Select.Rows)
{
this.textBox1.Text = myRowCol.FirstName.ToString();
}

J.C.
GeneralSP returning multiple result sets
GoTech
5:44 6 Dec '05  
I have SPs that returns multiple result sets...
rader= com.ExecuteReader(schemaOnly) returns only schema for 1st result set ---is there any way to return the all the resultset schemas?

gotech
GeneralA simple utility
chris Liang
10:06 30 Aug '05  
A while ago, I searched the internet for a code generator of stored procedures with simple feactures:

  • No further modification to the generated code
  • Synchronizing with procedure changes
  • Directly interacting with data provider methods
  • Flexible for effecient use of ADO.Net functionality
  • Static data binding

There are a lot of such kind but I had no success.

Now, I have created one and if you are interested, take a look at
http://www.povb.com/posharp/[^]


chris Liang


GeneralRe: A simple utility - a free one!
Thomas Schittli
4:10 28 Sep '05  
... or just use one of the many free tools like MyGeneration:
www.mygenerationsoftware.com

Kind regards,
thomas

People who wait until the eleventh hour to call on Jesus die at 10:30.

-- modified at 9:45 Wednesday 28th September, 2005
GeneralBlows up in my eye when I run the demo!
Cyberhacker
7:38 29 Jun '05  
The download drops 3 files in a folder.
When I run the EXE it blows up in my eye.

Anyone have any info on how to get this working?

Generalhow to use this ??
webber123456
9:42 28 Jun '05  
demo has 3 files:

DBHelper.dll
Interop.MSDASC.dll
SPTestApp.exe

but the exe file throws an error when opened:

"An exception 'systemIO.FileNotFoundException' has occurred in SPTestApp.exe "

Can any one help me with what is required to run this application ?

thanks
GeneralSQL Errors are not reported,
mostafaa
11:38 10 Feb '05  
Hi,
   there is an exception that is simply ignored causing SQL errors not to be reported.   This leads to "Unable to ..." error.   It took me 4 hours to find the problem until I had to debug through the source code.

If you just add tracing for SQL exceptions that would be great.   The code that needs to be added is in StoredProcedure.cs (lowest 2 lines of this code):

          public static StoredProcedure Inspect(
               SqlConnection connection,
               string name)
          {
               // get a collection mapping user-defined data types to their
               // base-equivalents.

               StringDictionary typeMap = ReadUserDefinedDataTypes(connection);

               // get parameter and result set metadata

               StoredProcedurePrototype prototype = InspectPrototype(connection, typeMap, name);
               StoredProcedureResultSetColumns resultSet = null;
              
               try { resultSet = InspectResultSet(connection, name, prototype.Parameters); }
               catch(Exception e) {
                    Console.WriteLine();   // added these 2 lines
                    Console.WriteLine(e.Message);
                    resultSet = null; }

GeneralSweeet...
JoshCrosby
6:14 23 Dec '04  
this is some great stuff thanks for sharing this, it looks like this will save me a bunch of time.

is there anyway of providing a sample application using the Generated dlls, xsd, etc... It would help me and others out greatly.

thanks.
GeneralRe: Sweeet...
leppie
6:49 23 Dec '04  
Thanx, but there is another article on CP that betters my efforts, sorry no link, just search for it Smile

top secret
Download xacc-ide 0.0.3 now!
See some screenshots

GeneralRe: Sweeet...
JoshCrosby
14:54 23 Dec '04  
Big Grin Having a tough time finding it, you have around 10 Big Grin Can you give me the title or some keywords Laugh
GeneralCannot Get It To Work With Oracle 9i
Mark Kamoski
7:04 25 May '04  
FYI, I cannot get this to work with Oracle 9i.

Here is what happens.

I run the project, it prompts me for database information, I fill in the database dialog, I press "Test Connection", it says "OK", then the Generator program complains that I must "choose a database too", I go back to the database info dialog, I use the same UID and PWD and I try to list the initial catalog to use and it says "invalid parameter", and I am stuck.

It does the same thing for OLEDB and Oracle provider selection.

(Note that I can connect to this Oracle instance using other programs such as TOAD, MyGeneration, SQL Navigator. When I supply the same credentials, those programs can find the database information just fine.)

Any ideas?

Please advise.

Thank you.

--Mark

GeneralRe: Cannot Get It To Work With Oracle 9i
leppie
10:45 25 May '04  
This strictly for MS SQL, sorry I did thought I mentioned it, but looking over the article again, I noticed I omitted it.

The reason why it wont work is that I use specific system stored procedures from MS SQL to get the information.

Feel free to port it to Oracle if you can, but unfortunately I wont.

top secret xacc-ide 0.0.1
GeneralWill this work for Oracle 9i?
Mark Kamoski
13:41 22 May '04  
L--

Thank you very much for a very nice tool.

Will this work for Oracle 9i?

(If not, can you suggest something?)

Please adivse.

Thank you.

--Mark
GeneralJust came across this
Michael P Butler
1:20 12 Apr '04  
Auto-Generating Wrapper Classes for Stored Procedures, Part 1: Using the AutoSproc Tool[^]

May be of interest to you.

Michael

But you know when the truth is told,
That you can get what you want or you can just get old,
Your're going to kick off before you even get halfway through.
When will you realise... Vienna waits for you?
- "The Stranger," Billy Joel

GeneralHow to invoke wrapped procedures?
Iryx
9:48 29 Sep '03  
I ran the demo and generated the code, the assembly and the xsd file. Now I can call one of the wrapper functions but I'm not sure how to define the table attribute that it takes.

I used the xsd.exe tool to generate a class from the xml shema but that's where I get lost.
What do I do next to make this useful tool work?

Can anybody help? What am I missing?

Iryx
GeneralException running example program
versteijn
6:14 20 Jul '03  
Hello

I tried the example program to connect to a SQL Server 2000 database, but it failed and quit with the following exception error.

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in system.data.dll

Additional information: System error.
GeneralRe: Exception running example program
leppie
7:40 20 Jul '03  
You will have to at least provide a stack trace...

leppie::AllocCPArticle(Generic DFA State Machine for .NET);
GeneralRe: Exception running example program
versteijn
9:52 22 Jul '03  
Here it is

system.data.dll!System.Data.SqlClient.SqlConnection::Open() + 0x395 bytes
> dbhelper.dll!DBHelper.SP.GetSPs() Line 177 C#
dbhelper.dll!DBHelper.SP.Init(System.CodeDom.Compiler.CodeDomProvider cp = {Microsoft.CSharp.CSharpCodeProvider}) Line 151 C#
dbhelper.dll!DBHelper.SP.SP(System.Data.SqlClient.SqlConnection conn = {System.Data.SqlClient.SqlConnection}, System.CodeDom.Compiler.CodeDomProvider cp = {Microsoft.CSharp.CSharpCodeProvider}) Line 142 C#
SPTestApp.exe!SPTestApp.Form1.Connect() Line 662 + 0x26 bytes C#
SPTestApp.exe!SPTestApp.Form1.Form1() Line 82 C#
SPTestApp.exe!SPTestApp.Form1.Main() Line 482 + 0x14 bytes C#

GeneralRe: Exception running example program
leppie
10:10 22 Jul '03  
It appears your connection string is incorrect. I'm not really sure if that SQL GUI thing works correctly. Are you sure you select the SQL providor, not the OleDb providor?

leppie::AllocCPArticle(Generic DFA State Machine for .NET);
GeneralRe: Exception running example program
versteijn
9:10 29 Jul '03  
Yes I'm sure.
GeneralRe: Exception running example program
leppie
10:40 29 Jul '03  
Unless I have more info (perhaps a sample db) im afraid I cant help you. I have never seen that problem. What is your connection string? What is your locale set to?

leppie::AllocCPArticle(Generic DFA State Machine for .NET);
GeneralRe: Exception running example program
Jonathan de Halleux
1:07 29 Aug '03  
I have the same problem.

Jonathan de Halleux.

GeneralRe: Exception running example program
quincykong
23:46 23 May '04  
Hi,

You may try to check "Allow saving password" checkbox under password field ?

Quincy


Last Updated 8 Dec 2002 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010