1

I am writing a C# .NET 4.5-based Windows Forms application.

I'd like to set a flag (Boolean) in one of the classes (probably the main Form's class) that defines whether the app is running in Production of Debug mode. I will use this flag to control various actions of the app, including GUI-based actions as well as which connection string to use.

I don't have a problem with the GUI-based stuff because the flag is defined in the main Form's class, but I'm having a problem with the connection string. There is a separate class for DB access, which basically just defines a constant like this:

namespace MyApp
{
    class DatabaseInterface
    {
        public static string MyConnectionString = "Data Source=server;Initial Catalog=db";
    }
}

I'd like to change the connection string (really just the "server") depending on that production/debug flag. I do NOT want to put an if/then/else in every place where the connection string is used (to toggle between debug and production strings), but would like a single named connection string that can be used throughout the app. I'd also prefer to NOT have to instantiate a DatabaseInterface object (I know I could dynamically change this in the "get" definition of a public property of the DatabaseInterface class).

Is there a way to do this?

jimtut
  • 2,366
  • 2
  • 16
  • 37
  • Rather than tackle this in code, you should look at using the config file. If you're using a web application you can use web config transforms to specify what your debug and release configs look like (see this article http://msdn.microsoft.com/en-us/library/dd465318(v=vs.100).aspx). If not you can create a debug and release version of your app.config and use the build events to choose which one you want to use by copying the correct one to app.config. – Doctor Jones Feb 24 '14 at 09:06
  • Have a look here regarding app.config and transformations: http://stackoverflow.com/questions/3004210/app-config-transformation-for-projects-which-are-not-web-projects-in-visual-stud – Johann Blais Feb 24 '14 at 09:36
  • We can't use an app.config due to not wanting to expose the connection string to users. App.configs are generally plain text, and the methods for encrypting them didn't seem feasible. – jimtut Feb 24 '14 at 09:56

1 Answers1

1

If you want to do this based on a flag and don't want the if everywhere, I'd suggest that you use a simple getter like this :

namespace MyApp
{
    class DatabaseInterface
    {
        public static string getConnectionString()
        {
            return myFlag ? "Data Source=server;Initial Catalog=db" : "AnotherString";
        }
    }  
 }
Luke Marlin
  • 1,398
  • 9
  • 26