如何从C#WinForms应用程序判断SQL Server自动升级是否成功

时间:2013-06-26 17:03:53

标签: c# .net sql-server winforms silent-installer

我正在通过用于升级我们的应用程序的WinForms应用程序自动将SQL Server 2005 Express升级到SQL Server 2008R2 Express。该应用程序部署在大约800多个位置,因此我们不需要任何手动步骤。

我已经编写了以下代码来执行升级。我需要知道,确定SQL Server安装程序是否成功完成的最佳做法是什么?我应该只为流程寻找退出代码0吗?这够好吗?即,如果升级出现问题并且已经回滚,它仍然可以退出代码为0(我会测试它,但不知道模拟故障的最佳方法)?

有没有其他方法可以确定我的C#应用​​程序中的升级是否成功,所以如果SQL Server安装程序遇到任何错误,我可以正确处理它吗?

try
{

    //First, find the version of the currently installed SQL Server Instance
    string sqlString = "SELECT SUBSTRING(CONVERT(VARCHAR, SERVERPROPERTY('productversion')), 0, 5)";
    string sqlInstanceVersion = string.Empty;                

    using (DbCommand cmd = _database.GetSqlStringCommand(sqlString))
    {
        sqlInstanceVersion = cmd.ExecuteScalar().ToString();
    }

    if (sqlInstanceVersion.Equals(String.Empty))
    {
        //TODO throw an exception or do something else
    }

    //11.00 = SQL2012, 10.50 = SQL2008R2, 10.00 = SQL2008, 9.00 = SQL2005, 8.00 = SQL2000
    switch (sqlInstanceVersion)
    {
        case "11.00":
        case "10.50":
        case "10.00":
            //Log that the version is already up to date and return
            return;
        case "9.00":
        case "8.00":
            //We are on SQL 2000 or 2005, so continue with upgrade to 2008R2
            break;
        default:
            //TODO throw an exception for unsupported SQL Server version
            break;
    }

    string upgradeArgumentString = "/Q /ACTION=upgrade /INSTANCENAME={0} /ENU /IACCEPTSQLSERVERLICENSETERMS";
    string instanceName = "YourInstanceNameHere";
    string installerFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\SQLEXPR_x86_ENU.exe"; 

    if (!File.Exists(installerFilePath))
    {
        throw new FileNotFoundException(string.Format("Unable to find installer file: {0}", installerFilePath));
    }

    Process process = new Process
    {
        StartInfo = { FileName = installerFilePath, Arguments = String.Format(upgradeArgumentString, instanceName), UseShellExecute = false }
    };

    process.Start();

    if (process.WaitForExit(SQLSERVER_UPGRADE_TIMEOUT))
    {
        //Do something here when the process completes within timeout.
        //What should I do here to determine if the SQL Server Installer completed successfully?  Look at just the exit code?
    }
    else
    {
        //The process exceeded timeout.  Do something about it; like throw exception, or whatever
    }
}
catch(Exception ex)
{
    //Handle your exceptions here
}

1 个答案:

答案 0 :(得分:2)

查看完整版本字符串,坚持它的前5个字符。成功升级将更改版本字符串。

相关问题