SqlConnection is not catching errors!

  • Thread starter Thread starter Jassim Rahma
  • Start date Start date
J

Jassim Rahma

Guest
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

Continue reading...
 
Back
Top