1

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 1

6

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());
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

-sqlexportlonly <filename> BAM! ty sir
@andrew: Indeed :) It isn't DB agnostic, if that is a concern for you. I edited that file manually. If you want some slapped together code to execute that script I can give it to you later today. About 10-15 lines.
@andrew: Glad this helped. If the answer solved your problem, please mark it as accepted (the check mark at the top-left of the answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.