6

I have developed a Window Service using SQL Database currently in my DB is full of Record so query execuction taking much time while default command timeout is 30S but I want to increase it to 120S one option is

com.CommandTimeout = 120;

but I have many methods in my Application so I want to set it from APP.config file so it will be applicable for Application level, can anyone please tell me how could I achive this

Thanks

Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70

2 Answers2

6

The easiest way to achieve this is to add a new entry in <appSettings> something like this:

<appSettings>
    <add key="commandTimeout" value="3000" />
</appSettings>

Afterwards, create a CommandFactory class that will populate the value

class CommandFactory
{
    public static int CommandTimeout
    {
        get
        {
            int commandTimeout = 0;
            var configValue = ConfigurationManager.AppSettings["commandTimeout"];
            if(int.TryParse(configValue, out commandTimeout))
               return commandTimeout;
            return 120; 
        }
    }

    public static SqlCommand CreateCommand(SqlConnection connection)
    {
        var command = new SqlCommand()
        {
            Connection = connection,
            CommandTimeout = CommandTimeout
        };
        return command;
    }
}

Now, in your code, instead of just instantiating a new SqlCommand just call the CommandFactory method:

using(var command = CommandFactory.CreateCommand(yourConnection))
{
    //
}
RePierre
  • 9,358
  • 2
  • 20
  • 37
-1

use this in app.config file

<configuration>
  <appSettings>
    <add key="connectioStringName" value="Data Source=source;Initial Catalog=tableName;User Id=databaseName;Password=password;Connection Timeout=3000"/>
  </appSettings>
</configuration>
  • 6
    This will set the `ConnectionTimeout` property of the `SqlConnection` not the command timeout. See MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout(v=vs.110).aspx – RePierre Aug 14 '14 at 07:54