Before I write this myself, is there a c# method out there floating around that will create the tables, sprocs, and views that get installed by aspnetregsql?
1 Answer
As far as I know there is no API to do this directly - the aspnet_regsql.exe tool just references script files on disk anyhow.
For a head start on how to implement this yourself:
You can manually execute aspnet_regsql.exe via Process.Start.
Or you can run the program from the command line, with command line options to dump out the script. Then edit those scripts to be DB agnostic (or don't - up to you), store those scripts as embedded resources in your application, extract them at runtime, and use a SqlConnection and ExecuteNonQuery to run those scripts against a database.
Here are the command line options for aspnet_regsql.exe:
http://msdn.microsoft.com/en-us/library/ms229862(v=vs.80).aspx
Here's some code I have used to implement the second option:
ExecuteSqlScriptResource("MyDb", "MyAssemblyName.Scripts.aspnet_regsql_add.sql");
// ...
static void ExecuteSqlScriptResource(string connectionName, string resourcePath)
{
using (Stream scriptStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourcePath)
)
{
if (scriptStream == null)
{
WriteLine(string.Format("Failed to open resource {0}", resourcePath));
return;
}
using (
var sqlConnection = new SqlConnection(
ConfigurationManager
.ConnectionStrings[connectionName].ConnectionString
)
)
{
using (var streamReader = new StreamReader(scriptStream))
{
var svrConnection = new ServerConnection(sqlConnection);
var server = new Server(svrConnection);
server.ConnectionContext.ExecuteNonQuery(streamReader.ReadToEnd());
}
}
}
}