2011-10-05 23 views
6

Quando si eseguono script in SQL Server Management Studio, vengono spesso generati messaggi visualizzati nella finestra del messaggio. Ad esempio quando si esegue un backup di un database:Handle C# su SQL Server Output messaggio

10 percento elaborato.

20 percento elaborato.

Etc ...

elaborato 1722608 pagine per il database 'Campione', file 'Sampe' nel file 1.

100 per cento elaborati.

trasformati 1 pagine per 'campione' di database, file 'Sample_Log' su file elaborato 1.

BACKUP DATABASE successo 1722609 pagine in 202.985 secondi (66,299 MB/sec).

Mi piacerebbe essere in grado di visualizzare questi messaggi in un'applicazione C# che sta eseguendo script SQL su un database. Tuttavia, non riesco a capire come ottenere un handle sull'output del messaggio da SQL come viene generato. Qualcuno sa come si fa questo? Non mi importa quale quadro di connessione devo usare. Sono relativamente a mio agio con LINQ, NHibernate, Entity Framework, ADO.Net, Enterprise Library e sono felice di apprenderne di nuovi.

risposta

6

Ecco il codice di esempio che ho provato e funziona per me. http://www.dotnetcurry.com/ShowArticle.aspx?ID=344

Annotare il codice necessario è in realtà questa parte:

cn.Open(); 
cn.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e) 
{          
     txtMessages.Text += "\n" + e.Message;         
}; 

E 'l'e.Message continua a restituire il messaggio al txtMessages (È possibile sostituire come TextBox o l'etichetta).

Si può anche fare riferimento a questo articolo: Backup SQL Server Database with progress

Un esempio del mio codice è il seguente:

//The idea of the following code is to display the progress on a progressbar using the value returning from the SQL Server message. 
//When done, it will show the final message on the textbox. 
String connectionString = "Data Source=server;Integrated Security=SSPI;"; 
SqlConnection sqlConnection = new SqlConnection(connectionString); 

public void DatabaseWork(SqlConnection con) 
{ 
    con.FireInfoMessageEventOnUserErrors = true; 
    //con.InfoMessage += OnInfoMessage; 
    con.Open(); 
    con.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e) 
    { 
     //Use textBox due to textBox has Invoke function. You can also utilize other way. 
     this.textBox.Invoke(
      (MethodInvoker)delegate() 
      { 
       int num1; 
       //Get the message from e.Message index 0 to the length of first ' ' 
       bool res = int.TryParse(e.Message.Substring(0, e.Message.IndexOf(' ')), out num1); 

       //If the substring can convert to integer 
       if (res) 
       { 
        //keep updating progressbar 
        this.progressBar.Value = int.Parse(e.Message.Substring(0, e.Message.IndexOf(' '))); 
       } 
       else 
       { 
        //Check status from message 
        int succ; 
        succ = textBox.Text.IndexOf("successfully"); 
        //or succ = e.Message.IndexOf("successfully"); //get result from e.Message directly 
        if (succ != -1) //If IndexOf find nothing, it will return -1 
        { 
         progressBar.Value = 100; 
         MessageBox.Show("Done!"); 
        } 
        else 
        { 
         progressBar.Value = 0; 
         MessageBox.Show("Error, backup failed!"); 
        } 
       } 
      } 
     ); 
    }; 
    using (var cmd = new SqlCommand(string.Format(
     "Your SQL Script"//, 
     //QuoteIdentifier(databaseName), 
     //QuoteString(Filename)//, 
     //QuoteString(backupDescription), 
     //QuoteString(backupName) 
     ), con)) 
    { 
     //Set timeout = 1200 seconds (equal 20 minutes, you can set smaller value for shoter time out. 
     cmd.CommandTimeout = 1200; 
     cmd.ExecuteNonQuery(); 
    } 
    con.Close(); 
    //con.InfoMessage -= OnInfoMessage; 
    con.FireInfoMessageEventOnUserErrors = false; 
} 

Al fine di ottenere il lavoro ProgressBar, è necessario implementare questo con un backgroundworker, che la tua applicazione non si blocca e ottiene il 100% improvvisamente.