Joe C
Joe C

Reputation: 184

C#, How to hande SSH timeout Exception with SharpSSH

I am trying to connect to a remote server to using Sharp SSH. The timeout exception I receive is a network based exception. I want the program to be more robust even if the network has problems, or if the server simply isn't available. The time out occurs at my open command and throws an IO timeout exception.

I am hoping to solve this intermittent problem from my end.

mySqlConnectionString = String.Format(
    "server={0};user={1};database=MTA;port=3306;password={2}", 
    SqlHost, mySqlUser, mySqlPass);

se = new SshExec(Host, User, Pass);
msc = new MySqlConnection(mySqlConnectionString);

// Connect to server and get the list of 
// firmware versions and serial numbers available
se.Connect();

lblConnected.Text = (se.Connected) ? "Connected" : "Not Connected";

msc.Open();         //exception happens here

My question: Is there some way I can tell the C# application to just try the connect command again should it encounter an exception?

Upvotes: 1

Views: 1851

Answers (1)

Andrea
Andrea

Reputation: 12355

Try using a try catch block:

        mySqlConnectionString = String.Format("server={0};user={1};database=MTA;port=3306;password={2}", SqlHost, mySqlUser, mySqlPass);

        se = new SshExec(Host, User, Pass);
        msc = new MySqlConnection(mySqlConnectionString);
        // Connect to server and get the list of firmware versions and serial numbers available
        se.Connect();

        lblConnected.Text = (se.Connected) ? "Connected" : "Not Connected";

        try
        {
            msc.Open();  //exception happens here
        }
        catch (Exception)
        {
            //do stuff, i.e. retry connection
            msc.Open();
        }

to be sure you can use a nested try/catch:

        mySqlConnectionString = String.Format("server={0};user={1};database=MTA;port=3306;password={2}", SqlHost, mySqlUser, mySqlPass);

        se = new SshExec(Host, User, Pass);
        msc = new MySqlConnection(mySqlConnectionString);
        // Connect to server and get the list of firmware versions and serial numbers available
        se.Connect();

        lblConnected.Text = (se.Connected) ? "Connected" : "Not Connected";

        try
        {
            msc.Open();  //exception happens here
        }
        catch (Exception)
        {
            //do stuff, i.e. retry connection
            try
            {
                msc.Open();  //exception happens here
            }
            catch (Exception)
            {
                //do stuff
            }
        }

Upvotes: 2

Related Questions