Connections strings to config
I have the opportunity to work on some pretty old code . There were many projects , all that had a sort of connection string to the database. This kind of code were in like > 11 places :
string connectionstring = “Data Source=.\\SqlServer;Initial Catalog=myDB;Integrated Security=SSPI;”;
The task was to modify this in something that could read from a config ( json) file . But more than that, was to verify
1.that is called everywhere – because sometimes it were in methods, other time in a static variable and so on .
2. that the json exists or not ( if not return the default string – but log the fact that are not in the settings)
So – how to monitor that your code is actually hit ? One idea is to make breakpoints. Other is to make a class:
So I came up with this class
public class ConnectionSql { public ConnectionSql( [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { Trace.WriteLine("member name: " + memberName); Trace.WriteLine("source file path: " + sourceFilePath); Trace.WriteLine("source line number: " + sourceLineNumber); } //TODO: if need speed, make this static - or strConnection... public string ConnectionString() { var strConnection = ConfigurationManager.AppSettings["sql"]; if (string.IsNullOrWhiteSpace(strConnection)) { Console.WriteLine("not found connection sql string in settings , going to default"); strConnection = ".\\SqlServer;Initial Catalog=myDB;Integrated Security=SSPI;"; } return strConnection; } }
How we call ?
string connectionstring = new ConnectionSql().ConnectionString();
Because of the attributes https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information we can figure by looking at the trace if the code was hit or not and by which line.