none
SqlConnection is not catching errors! RRS feed

  • Question

  • Hi,

    I have below code which should connect to my SQL Server and get the ads.

    The code is working perfectly when I am connected to internet

    but when I turn off internet then the app will crash on sql_connection.Open() without going through the catch process

    How can I fix this please?

    Here is the code:

    try
    {
        sql_connection = new SqlConnection("Server=myserver.com; Database=myDB; User Id=MyUser; Password=MyPassword;");
         sql_connection.Open();
    
        sql_command = new SqlCommand("sp_populate_home_page_ads", sql_connection);
        sql_command.CommandType = CommandType.StoredProcedure;
        SqlDataReader sql_reader = sql_command.ExecuteReader();
    
        ObservableCollection<object> trends = new ObservableCollection<object>();
    
        while (sql_reader.Read())
        {
            AdsList data1 = new AdsList()
            {
                ad_id = Convert.ToInt32(sql_reader["ad_id"]),
                ad_guid = Convert.ToString(sql_reader["ad_guid"]),
                ad_category = Convert.ToString(sql_reader["ad_category"]),
                ad_reference = Convert.ToInt32(sql_reader["ad_reference"])
            };
    
            trends.Add(data1);
        }
    
        rotator.ItemsSource = trends;
    }
    catch (HttpRequestException ex)
    {
        Crashes.TrackError(ex, new Dictionary<string, string>
        {
            { "Page", this.Title },
            { "Where", "GetAds" }
        });
    
        rotator.IsVisible = false;
    
        loadingHomePageRotatorNoInternet.IsVisible = false;
    
        RotatorImageNoInternet.IsVisible = true;
        RotatorLabelNoInternet.IsVisible = true;
    
        RotatorNoInternet.IsVisible = true;
    
        return;
    }
    catch (SqlException ex)
    {
        Crashes.TrackError(ex, new Dictionary<string, string>
        {
            { "Page", this.Title },
            { "Where", "GetAds" }
        });
    
        rotator.IsVisible = false;
    
        loadingHomePageRotatorNoInternet.IsVisible = false;
    
        RotatorImageNoInternet.IsVisible = true;
        RotatorLabelNoInternet.IsVisible = true;
    
        RotatorNoInternet.IsVisible = true;
    
        return;
    }
    catch (Exception ex)
    {
        Crashes.TrackError(ex, new Dictionary<string, string>
        {
            { "Page", this.Title },
            { "Where", "GetAds" }
        });
    
        rotator.IsVisible = false;
    
        loadingHomePageRotatorNoInternet.IsVisible = false;
    
        RotatorImageNoInternet.IsVisible = true;
        RotatorLabelNoInternet.IsVisible = true;
    
        RotatorNoInternet.IsVisible = true;
    
        await DisplayAlert("خطأ", "يرجى التأكد من الاتصال بشبكة الإنترنت", "إغلاق");
    
        return;
    }
    finally
    {
        sql_connection.Close();
        sql_connection.Dispose();
    }
    

    Thanks,

    Jassim

    Friday, July 26, 2019 5:39 PM

All replies

  • Place a breakpoint on the line prior to the Open method, step through the code, where does it take you ?

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, July 26, 2019 5:52 PM
    Moderator
  • It goes to this line:

    sql_connection = new SqlConnection("Server=MyServer.com; Database=MyDB; User Id=MyUser; Password=MyPassword;");

    then goes to this line:

    sql_connection.Open();

    Never reach this line:

    sql_command = new SqlCommand("sp_populate_home_page_ads", sql_connection);

    and never goes to catch handler


    Friday, July 26, 2019 6:04 PM
  • Where is this code located? Does it happen to be in the Form_Load event of a Windows Forms application?

    There is a known bug where any exceptions thrown in Form_Load under some circumstances are just ignored silently and are not caught by catch blocks. I am not aware of any solution for the bug. The workaround is to move the offending code elsewhere in the application. You could move the connection to some other event that triggers after the form is already loaded, or if you need the connection very early you could open it before loading the form and pass it as an argument to the constructor.

    Sunday, July 28, 2019 12:53 PM
    Moderator
  • it's in OnAppearing()

    protected override async void OnAppearing()
    {
        base.OnAppearing();
    
        if (is_loaded == false)
        {
            GetAds();
        }
    
        is_loaded = true;
    }

    GetAds() is this:

    try
    {
        sql_connection = new SqlConnection("Server=myserver.com; Database=myDB; User Id=MyUser; Password=MyPassword;");
         sql_connection.Open();
    
        sql_command = new SqlCommand("sp_populate_home_page_ads", sql_connection);
        sql_command.CommandType = CommandType.StoredProcedure;
        SqlDataReader sql_reader = sql_command.ExecuteReader();
    
        ObservableCollection<object> trends = new ObservableCollection<object>();
    
        while (sql_reader.Read())
        {
            AdsList data1 = new AdsList()
            {
                ad_id = Convert.ToInt32(sql_reader["ad_id"]),
                ad_guid = Convert.ToString(sql_reader["ad_guid"]),
                ad_category = Convert.ToString(sql_reader["ad_category"]),
                ad_reference = Convert.ToInt32(sql_reader["ad_reference"])
            };
    
            trends.Add(data1);
        }
    
        rotator.ItemsSource = trends;
    }
    catch (HttpRequestException ex)
    {
        Crashes.TrackError(ex, new Dictionary<string, string>
        {
            { "Page", this.Title },
            { "Where", "GetAds" }
        });
    
        rotator.IsVisible = false;
    
        loadingHomePageRotatorNoInternet.IsVisible = false;
    
        RotatorImageNoInternet.IsVisible = true;
        RotatorLabelNoInternet.IsVisible = true;
    
        RotatorNoInternet.IsVisible = true;
    
        return;
    }
    catch (SqlException ex)
    {
        Crashes.TrackError(ex, new Dictionary<string, string>
        {
            { "Page", this.Title },
            { "Where", "GetAds" }
        });
    
        rotator.IsVisible = false;
    
        loadingHomePageRotatorNoInternet.IsVisible = false;
    
        RotatorImageNoInternet.IsVisible = true;
        RotatorLabelNoInternet.IsVisible = true;
    
        RotatorNoInternet.IsVisible = true;
    
        return;
    }
    catch (Exception ex)
    {
        Crashes.TrackError(ex, new Dictionary<string, string>
        {
            { "Page", this.Title },
            { "Where", "GetAds" }
        });
    
        rotator.IsVisible = false;
    
        loadingHomePageRotatorNoInternet.IsVisible = false;
    
        RotatorImageNoInternet.IsVisible = true;
        RotatorLabelNoInternet.IsVisible = true;
    
        RotatorNoInternet.IsVisible = true;
    
        await DisplayAlert("خطأ", "يرجى التأكد من الاتصال بشبكة الإنترنت", "إغلاق");
    
        return;
    }
    finally
    {
        sql_connection.Close();
        sql_connection.Dispose();
    }


    Sunday, July 28, 2019 5:06 PM
  • Where is this code located? Does it happen to be in the Form_Load event of a Windows Forms application?

    There is a known bug where any exceptions thrown in Form_Load under some circumstances are just ignored silently and are not caught by catch blocks. I am not aware of any solution for the bug. The workaround is to move the offending code elsewhere in the application. You could move the connection to some other event that triggers after the form is already loaded, or if you need the connection very early you could open it before loading the form and pass it as an argument to the constructor.

    As I said, this problem happens only when I am not connected to internet which I am expecting to show (No Internet) message but this is not happening

    When user is connected to internet then there is no issue at all

    Sunday, July 28, 2019 5:08 PM
  • Hello,

    Since this is WPF try subscribing to DispatcherUnhandledException.

    https://www.wpf-tutorial.com/wpf-application/handling-exceptions/


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, July 28, 2019 5:14 PM
    Moderator