andrew4582

SQLCmdHelper

Aug 4th, 2010
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.69 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5.  
  6.  namespace  Core.Data {
  7.     public  class  SQLCmdHelper {
  8.          
  9.          #region  Excecute sqlcmd.exe
  10.          string  GetSqlcmdPath() {
  11.              //might be different on other boxes
  12.              return  @"C:\\Program Files\\Microsoft SQL Server\\100\\Tools\\Binn\\SQLCMD.EXE" ;
  13.          }
  14.          /// <summary>
  15.          /// Gets a temp file in C:\\Users\\{USER}\\AppData\\Local\\Temp\\_SQLTEMP directory
  16.          /// </summary>
  17.          /// <param name="filename"></param>
  18.          /// <returns></returns>
  19.          string  GetTempFilePath(string  filename = null ) {
  20.              string  tempDirectory = Path .Combine(Path .GetTempPath(),"_SQLTEMP" );
  21.  
  22.              if (!Directory .Exists(tempDirectory))
  23.                  Directory .CreateDirectory(tempDirectory);
  24.  
  25.              if (filename == null )
  26.                  filename = Path .GetFileName(Path .GetTempFileName());
  27.              return  Path .Combine(tempDirectory,filename);
  28.          }
  29.          bool  ExcecuteSQLScript(string  sqlbatch) {
  30.            
  31.             string  sqlServerInstance = ".\\\\SQLExpress" ;
  32.            
  33.             return ExcecuteSQLScript(sqlbatch,sqlServerInstance);
  34.          }
  35.          /// <summary>
  36.          /// Executes the sql code
  37.          /// </summary>
  38.          /// <param name="sqlbatch"></param>
  39.          /// <returns></returns>
  40.          bool  ExcecuteSQLScript(string  sqlbatch,string sqlServerInstance) {
  41.  
  42.              if (string .IsNullOrWhiteSpace(sqlbatch))
  43.                  throw  new  ArgumentNullException ("sqlbatch" );
  44.  
  45.              
  46.              bool  deleteTempFiles = true ;
  47.  
  48.              string  sqlcmdPath = GetSqlcmdPath();
  49.              string  cmdline = string .Empty;
  50.  
  51.              string  scriptPath = GetTempFilePath("DBSCRIPT.sql" );
  52.              string  outputPath = GetTempFilePath("DBSCRIPT_OUTPUT.sql" );
  53.  
  54.              if (File .Exists(scriptPath))
  55.                  File .Delete(scriptPath);
  56.              if (File .Exists(outputPath))
  57.                  File .Delete(outputPath);
  58.  
  59.              try  {
  60.  
  61.                  //write the dropall text to temp file
  62.                  using (FileStream  file = new  FileStream (scriptPath,FileMode .CreateNew,FileAccess .Write)) {
  63.  
  64.                      file.Write(
  65.                          Encoding .Default.GetBytes(sqlbatch),
  66.                          0,
  67.                          sqlbatch.Length);
  68.  
  69.                      file.Flush();
  70.                      file.Close();
  71.                  }
  72.  
  73.                  cmdline = " -E " ;   // trusted connection
  74.                  cmdline += " -S "  + sqlServerInstance;  // server name/instance
  75.                  cmdline += " -i "  + scriptPath;   //sql script file path
  76.                  cmdline += " -o "  + outputPath;   //output file path
  77.  
  78.                  Status(Environment .NewLine);
  79.                  Status(sqlcmdPath,true );
  80.                  Status(cmdline,true );
  81.                  Status(Environment .NewLine);
  82.                  Status("Running Scripts..." );
  83.  
  84.                  //create process with arguments
  85.                  ProcessStartInfo procInfo = new  ProcessStartInfo(sqlcmdPath);
  86.                  procInfo.UseShellExecute = false ;
  87.                  procInfo.CreateNoWindow = true ;
  88.                  procInfo.Arguments = cmdline;
  89.                  Process sqlproc = Process.Start(procInfo);
  90.  
  91.                  //run sqlproc and wait for 60 seconds
  92.                  if (sqlproc.WaitForExit(60000)) {
  93.                      if (File .Exists(outputPath)) {
  94.                          Status(Environment .NewLine);
  95.                          Status("Completed sqlcmd.exe" );
  96.  
  97.                          Status("Results:" );
  98.  
  99.                          Status(File .ReadAllText(outputPath));
  100.  
  101.                          if (deleteTempFiles) {
  102.                              if (File .Exists(scriptPath))
  103.                                  File .Delete(scriptPath);
  104.  
  105.                              if (File .Exists(outputPath))
  106.                                  File .Delete(outputPath);
  107.                          }
  108.                          return  true ;
  109.                      }
  110.                      else  {
  111.                          Status("No output for returned" );
  112.                          return  false ;
  113.                      }
  114.                  }
  115.                  else  {
  116.                      Status("Scripts timeout" );
  117.                      return  false ;
  118.                  }
  119.              }
  120.              catch (Exception  error) {
  121.                  Status(error.ToString());
  122.                  return  false ;
  123.              }
  124.          }
  125.          #endregion
  126.  
  127.     }
  128.  }
Advertisement
Add Comment
Please, Sign In to add comment