August 28, 2013

LINQPad Command-Line and Scripting

LINQPad Command-Line and Scripting
Sample usage:
CALL C:\...\LinqPad\lprun.exe "C:\...\Queries\AttachDatabases.linq" DEV
This runs the given linq query. The sample is a "C# Program" and has a "Main" method taking "string[] args" as a paremeter. In this way the "DEV" string at the end of the line is passed as a parameter to the linq program.
Here is the sample linq script:
<Query Kind="Program" />

void Main(string[] args)
{
  string attachFolder = @"C:\Databases\";
  if ((args != null) && (args.Length == 1))
  {
  attachFolder = Path.Combine(attachFolder, args[0]);
  }
  Console.WriteLine("Attaching to databases in \'" + attachFolder + "\'"); 
  Console.WriteLine("");
  var server = @".\";
  var databaseNames = new[] { "XXX", "YYY", "ZZZ", "AAA" };

    using(var connection = new SqlConnection(
   string.Format("Server={0};Database=master;Trusted_Connection=True;", server)))
    {
    connection.Open();
  
    // attach the databases
    foreach(var database in databaseNames)
    {
      var dataFile = Path.Combine(attachFolder, database + "_Data.MDF");
      if (File.Exists(dataFile))
      {
        Console.WriteLine("Attaching {0}", database);
        var attachCommand = connection.CreateCommand();
        attachCommand.CommandText = "sp_attach_db  @dbName, @dataFileName, @logFileName";
        attachCommand.Parameters.AddWithValue("dbName", database);
        attachCommand.Parameters.AddWithValue("dataFileName", dataFile);
        attachCommand.Parameters.AddWithValue("logFileName", 
            Path.Combine(attachFolder, database + "_Log.LDF"));    
        attachCommand.ExecuteNonQuery();
      }
      else
      {
        Console.WriteLine("No data file for {0}", database);
      }
    }
      }
  
    Console.WriteLine("");
    Console.WriteLine("Press any key to continue ...");
    Console.ReadKey(false);
}
If you want the script to hang around a bit so that you can read the error messages then you can add the the following lines to the end
Console.WriteLine("");
Console.WriteLine("Press any key to continue ...");
Console.ReadKey(false);
This keeps the script alive until a key is pressed.

No comments: