user1238321
user1238321

Reputation: 249

Backup database from C#

I have a stored procedure that works fine when I run it when using Windows authentication. If I run it as the standard website user it fails, I guessed it was a permissions thing. So I'm trying to add a script in that allows me to connect to the database from C# and run the backup using Windows auth.

public bool BackUpDataBase()
{
    string connString = _country == Country.England ? _connectionStringSiteDbEngland : _connectionStringSiteDbScotland;

    try
    {
            using (SqlConnection conn = new SqlConnection(connString)) 
            {
                conn.Open();
                SqlCommand cmd  = new SqlCommand("BackupDB", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@BaseLocation", _serverBackupLocation));
                cmd.Parameters.Add(new SqlParameter("@BackupType", _backupType));
                cmd.ExecuteNonQuery();
                return true;
            }
    } 
    catch (Exception e)
    {
        //FAILED :(
        return false;
    }
}

I get a timeout error on cmd.ExecuteNonQuery();. The same connection string allows me to connect the the database to query a table here.

public bool IsScheduled()
{
        string archiveDB = _country == Country.England ? _englandArchiveDBName : _scotlandArchiveDBName;

        using (SqlConnection conn = new SqlConnection(_country == Country.England ? _connectionStringSiteDbEngland : _connectionStringSiteDbScotland)) 
        {
            conn.Open();
            SqlCommand cmd  = new SqlCommand(SQLToCheckSchedule(), conn);
            cmd.CommandType = CommandType.Text;

            int rows = 0;

            using (SqlDataReader rdr = cmd.ExecuteReader()) 
            {
               while (rdr.Read())
               {
                    rows++;
               }
            }  

            conn.Close();

            return rows > 0;
        }
}

Any ideas?

Upvotes: 0

Views: 394

Answers (1)

rikitikitik
rikitikitik

Reputation: 2450

Your database backup process simply takes too long compared to a regular table query. You can set the command timeout via the SqlCommand.CommandTimeout property

cmd.CommandTimeout = 1000; //This is in seconds
cmd.ExecuteNonQuery();

The default is 30 seconds. You can also set it to 0 so that it would wait indefinitely. However, this is a bit dangerous as this may lock your site/app. You may want to set your backup processes somewhere else instead, such as a scheduled task.

Upvotes: 3

Related Questions