Click here to Skip to main content
15,895,192 members
Articles / Programming Languages / JScript .NET

Stored Procedure Invocation Code Generator for VB, C# and JScript.NET

Rate me:
Please Sign up or sign in to vote.
4.92/5 (24 votes)
14 Jun 20038 min read 387.5K   3.4K   133  
Stored Procedure Invocation Code Generator for VB, C# and JScript.NET
//================================================================================
//
//  Copyright (c) objectnation GmbH, 2002
//
//================================================================================
//
//  Author          simon.wilson
//  Creation Date   06.09.2002
//  Creation Time   14:01:46
//  IDE Version     Microsoft Development Environment Enterprise Edition 7.00
//  OS Version      Microsoft Windows NT 5.1.2600.0
//
//================================================================================

#region Copyright � objectnation GmbH, 2002

// This software is provided 'as-is'. While the greatest care has been taken to 
// ensure that the software functions correctly, no guarantee can be made to this effect.
//
// objectnation grants permission to anyone to use this software for any purpose as long as 
// it is in compliance with the following restrictions:
//
// 1.	This software is the intellectual property and copyright of objectnation GmbH. 
//    Under no circumstances may the origin of the software be misrepresented.
//
// 2.	Should this software be used in the development of a commercial product, 
//    then an acknowledgement in that product's documentation is a requirement. 
//    The following text should be used:
//
//    This product contains code generated by objectnation SP/Invoke, 
//    copyright � objectnation GmbH 2002 (http://www.objectnation.com).
//
// 3.	The software may not be redistributed without the express written permission of 
//    the copyright holder, namely objectnation GmbH, Switzerland.

#endregion

using System;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.CodeDom;
using System.CodeDom.Compiler;

namespace objectnation.SPInvoke
{
	class App
	{
		static string _login = null;
		static string _password = null;

		static void OnBeginStep(object source, string message)
		{
			Console.WriteLine(message);
		}

		static SqlConnection OnConnect(string server, string database, string login, string password)
		{
			while(true)
			{
				string connectionString = null;
				SqlConnection connection = null;

				// 1) if the user specified a user-name and password then try them

				if(_login != null || _password != null)
				{
					connectionString = "user id=";

					if(_login != null)
						connectionString += _login;
					else
						connectionString += login;

					connectionString += ";password=";

					if(_password != null)
						connectionString += _password;
					else
						connectionString += password;

					connectionString += ";initial catalog=\"" + database + "\";";
					connectionString += "data source=" + server;

					connection = new SqlConnection(connectionString);
					connection.Open();

					return connection;
				}

				// 2) try using an SSPI connection (i.e. integrated security)

				try
				{
					connectionString = ";initial catalog=\"" + database + "\";";
					connectionString += "data source=" + server + ";Integrated Security=true";

					connection = new SqlConnection(connectionString);
					connection.Open();

					return connection;
				}
				catch(SqlException e)
				{
					if(e.Number != 18456)
					{
						throw e;
					}
				}

				// 3) try using SQL Server authentication using login and password
				//    from file (or defaults)

				connectionString = "user id=" + login;
				connectionString += ";password=" + password;
				connectionString += ";initial catalog=\"" + database + "\";";
				connectionString += "data source=" + server;

				connection = new SqlConnection(connectionString);
				connection.Open();

				return connection;
			}
		}

		static void DisplayHelp()
		{
			Console.WriteLine("/?              Displays this help");
			Console.WriteLine("/u:<login>      SQL Server login. Defaults to integr. auth.");
			Console.WriteLine("/p:<pwd>        SQL Server password. Defaults to blank.");
			Console.WriteLine("/n:<namespace>  Code generation namespace. Required.");
			Console.WriteLine("/o:<filename>   Output file name. Defaults to [input file].[ext].");
			Console.WriteLine("/l:cs|vb|js     Code generation language. Defaults to C#.");
			Console.WriteLine("/s              Silent mode.");
			Console.WriteLine();
			Console.WriteLine("Examples:");
			Console.WriteLine();
			Console.WriteLine("input.xml /n:MyNamespace");
			Console.WriteLine();
			Console.WriteLine("Takes the input file 'input.xml'. Generates C# code in the ");
			Console.WriteLine("namespace 'MyNamespace'. Output is written to 'input.cs'. ");
			Console.WriteLine("Integrated authentication is attempted. If this fails");
			Console.WriteLine("then the login and password from the input file are used. ");
			Console.WriteLine("If these are not specified then 'sa' is used with a blank ");
			Console.WriteLine("password.");
			Console.WriteLine();
			Console.WriteLine("imput.xml /n:MyNamespace /p:Secret");
			Console.WriteLine();
			Console.WriteLine("Takes the input file 'input.xml'. Generates C# code in the ");
			Console.WriteLine("namespace 'MyNamespace'. Output is written to 'input.cs'. ");
			Console.WriteLine("SQL Server authentication is attempted using the ");
			Console.WriteLine("login specified in the input file or 'sa' by default. ");
			Console.WriteLine("The password 'Secret' is used.");
			Console.WriteLine();
			Console.WriteLine("input.xml /o:StoredProcs.vb /n:StoredProcs /l:vb /u:MyLogin /p:Secret");
			Console.WriteLine();
			Console.WriteLine("Takes the input file 'input.xml'. Generates VB code in the ");
			Console.WriteLine("namespace 'StoredProcs'. Output is written to 'StoredProcs.vb'. ");
			Console.WriteLine("SQL Server authentication is attempted using the login 'MyLogin' ");
			Console.WriteLine("with the passord 'Secret'.");
			Console.WriteLine();
		}
		
		[STAThread]
		static void Main(string[] args)
		{
			try
			{
				Console.WriteLine();

				Console.WriteLine("objectnation SP/Invoke Command-Line Code Generator v" + 
					Assembly.GetExecutingAssembly().GetName().Version);

				Console.WriteLine("Copyright (c) objectnation GmbH 2002");
				Console.WriteLine();

				if(args.Length < 1)
				{
					Console.WriteLine("objectnation SP/Invoke stored procedure invokation code generator.");
					Console.WriteLine();
					Console.WriteLine("Specify /? for additional information");

					return;
				}

				if(args[0] == "/?" || args[0] == "-?")
				{
					DisplayHelp();
					return;
				}

				bool silent = false;
				string nameSpace = null;
				CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
				string outputFileName = null;
				string inputFileName = args[0];

				for(int i = 1; i < args.Length; i++)
				{
					if(args[i].Length < 2)
						throw new ApplicationException("Unrecognised argument: " + args[i]);

					if(args[i][0] != '/' && args[i][0] != '-')
						throw new ApplicationException("Unrecognised argument: " + args[i]);

					switch(args[i][1])
					{
						case 'p':
						case 'P':
							if(args[i].Length < 3 || args[i][2] != ':')
								throw new ApplicationException("Invalid argument syntax: " + args[i]);

							_password = args[i].Substring(3);
							break;

						case 'u':
						case 'U':
							if(args[i].Length < 3 || args[i][2] != ':')
								throw new ApplicationException("Invalid argument syntax: " + args[i]);

							_login = args[i].Substring(3);
							break;

						case 's':
						case 'S':
							silent = true;
							break;

						case 'n':
						case 'N':
							if(args[i].Length < 3 || args[i][2] != ':')
								throw new ApplicationException("Invalid argument syntax: " + args[i]);

							nameSpace = args[i].Substring(3);
							break;

						case 'o':
						case 'O':
							if(args[i].Length < 3 || args[i][2] != ':')
								throw new ApplicationException("Invalid argument syntax: " + args[i]);

							outputFileName = args[i].Substring(3);
							break;

						case 'l':
						case 'L':
							if(args[i].Length < 3 || args[i][2] != ':')
								throw new ApplicationException("Invalid argument syntax: " + args[i]);

							string language = args[i].Substring(3).ToLower();

							if(language == "cs")
								break;
							else if(language == "vb")
								provider = new Microsoft.VisualBasic.VBCodeProvider();
							else if(language == "js")
								provider = new Microsoft.JScript.JScriptCodeProvider();
							else
								throw new ApplicationException("Unsupported language: " + args[i].Substring(3));

							break;

						case '?':
							DisplayHelp();
							return;

						default:
							throw new ArgumentException("Unrecognised argument: " + args[i]);
					}
				}

				if(nameSpace == null)
					throw new ApplicationException("Code generation namespace must be specified");

				if(outputFileName == null)
				{
					outputFileName = inputFileName.Substring(0, inputFileName.LastIndexOf('.') + 1);
					outputFileName += provider.FileExtension;
				}

				Document doc = Document.Parse(args[0]);
				CompileUnitAssembler assembler = new CompileUnitAssembler(provider, nameSpace);

				assembler.Connect += new ConnectionHandler(OnConnect);
			
				if(!silent)
					assembler.BeginStep += new ProgressHandler(OnBeginStep);

				CodeCompileUnit compileUnit = assembler.Generate(doc);

				StreamWriter writer = new StreamWriter(outputFileName);

				CodeGeneratorOptions options = new CodeGeneratorOptions();
				options.BlankLinesBetweenMembers = false;

				ICodeGenerator generator = assembler.Provider.CreateGenerator();

				generator.GenerateCodeFromCompileUnit(compileUnit, writer, options);

				writer.Flush();
				writer.Close();
		
				Console.WriteLine();
				Console.WriteLine("Code generation complete.");
			}
			catch(Exception e)
			{
				Console.WriteLine();
				Console.WriteLine(e.Message);
			}
		}
	}
}

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
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions