Reputation: 3575
I have got this method which creates SqlConnection string in class. I read the data from .txt file but the problém is that if there is no data inserted the app doesn't even turn on. I was wondering how can I thrown an exception in messagebox and insert that command right into this class method. I'm not sure if it is possible. Sorry if my answer is too trivial or it's non-sense. I'm not programming for long time.
internal static class DataSource
{
private static string _ConnectionString;
public static string ConnectionString
{
get
{
if (_ConnectionString == null)
_ConnectionString = FunctionToDynamicallyCreateConnectionstring();
return _ConnectionString;
}
}
private static string FunctionToDynamicallyCreateConnectionstring()
{
string path = "C:\\Users\\marek\\Documents\\Visual Studio 2012\\Projects\\tours\\tours\\sql_string.txt";
StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.DataSource = sr.ReadLine();
cb.InitialCatalog = sr.ReadLine();
cb.UserID = sr.ReadLine();
cb.Password = sr.ReadLine();
return cb.ToString();
}
Upvotes: 2
Views: 217
Reputation: 21712
I really discourage “throwing an exception into MessageBox”, especially if that’s all you do. Exceptions are for handling errors, and showing a MessageBox does not handle the error. If there is nothing you can do to handle the error, stop. If you just show a message and continue you will get the same exception again when you try to use the data you didn’t get. What are you going to do then? Show another MessageBox?
What makes you think showing a MessageBox will help anyway? Will the user know how to fix it? What if the code is called from a service or background task and has no UI?
If you know how to fix the file, you should catch the exception, fix the file, and retry.
Edit: OK, if you really really want to show a MessageBox “right into this class method”, try this:
private static string ReadConnectionstringFromFile(string path)
{
try
{
using (var sr = new StreamReader(File.Open(path, FileMode.Open))
{
var cb = new SqlConnectionStringBuilder();
cb.DataSource = sr.ReadLine();
cb.InitialCatalog = sr.ReadLine();
cb.UserID = sr.ReadLine();
cb.Password = sr.ReadLine();
return cb.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), ex.message);
throw new CustomExceptionClassForYourApplication("Trying to get connection string from "
+ path, ex);
}
}
Upvotes: 0
Reputation: 4464
Wrap the access to DataSource.ConnectionString
when your app starts up with a try/catch. Heres some pseudocode:
public void OnAppStart()
{
string connString = null;
try
{
connString = DataSource.ConnectionString;
}
catch (IOException ioe)
{
MessageBox.Show("Hey, the file doesn't exist!");
}
catch (ArgumentNullException ane)
{
MessageBox.Show("Hey, the file is missing information!");
}
//You should be prepared to deal with a null or malformed connString
//from this point forwards
}
Upvotes: 2