In an MVC web application I want to override connection strings based on the development machine I'm using. I can use Web.config transformations, but I also need to override connection strings in various non-web config files. I can use the SlowCheetah extension, but then I will end up creating the same transformation for every project that accesses the database. This is a hassle to maintain when the project becomes bigger and has more developers.
What I would like to do is modify the way Entity Framework or ASP.NET look for connection strings, adding a class of my own that looks for connection strings, and only implement the transformation logic once. I would hopefully use Ninject to inject it only when relevant.
Is there such an "IConnectionStringProvider" interface I can implement and register, and automagically have ASP.NET and EF use it?
EDIT. I have found this, but it seems real nasty. If there's no cleaner way, I'll just use multiple identical configuration translations, and maybe let the source control system duplicate them properly.
You can tell Entity Framework to use a different connection string - it doesn't have to use the default one in web.config.
Here is an example: http://www.codeproject.com/Tips/234677/Set-the-connection-string-for-Entity-Framework-at
Here is another: http://msdn.microsoft.com/en-us/library/bb738533.aspx
It's up to you how you architect the rest of it.
Personally I use an app setting in web.config to tell my code which connection string to use for a particular part of the system, e.g.
var connectionStringNameForMyFeature = ConfigurationManager.AppSettings["connectionStringNameForMyFeature"];
myFeature.ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName];
Related
I'm in the process of moving the UI side of an application to the new ASP.NET Core MVC structure. Unfortunately, I still need to reference a data layer which is built in the prior-generation ASP.NET framework. This data .dll has the appropriate connection strings to various databases all being managed by ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString which required me to mimic in the UI layer in order to actually get at the data.
Now, with ASP.NET Core MVC, the web.config for configuration has been replaced with the appsettings.json file.
That paradigm shift breaks all my access to data since I can no longer replicate the connection string in the UI application.
Is there an appropriate solution that can make this data layer .dll more self-contained and rely on its own, internally defined connection string(s), while still exposing the Methods to the "containing" application - in this case, the UI layer?
Actually you do have reference to your connection string from the new .json file. You will do something like:
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection();
var config = builder.Build();
config["somekey"] = "somevalue";
// do some other work
var setting = config["somekey"]; // also returns "somevalue"
here is a link: docs.asp.net
I have resolved my issue with a work-around, and it will do for now. Ultimately, I'd like to find a better option, but I'm moving forward which makes my boss happy.
I ended up changing my method signatures to accept a string value representing the connection string that's no longer in the calling project because of the conversion to Core MVC.
In the called .dll, the code now looks to see if there is a value to the passed parameter, and, if so, uses the passed value to initialize the SqlConnection. If no parameter is provided, it will look to the config section in web.config using the ConfigurationManager capabilities.
This will allow the existing project to use the code, as well as the new Core MVC project. It's a bit kludgy, but functional.
I have a class where I retrieve certain settings from a database (usernames and passwords). This database is sitting on a network, and it means that if the passwords are changed, I can simply change it in the database, and all the applications that use this class will still work.
I am fully aware of the pros and cons of storing usernames and passwords in a database and in a separate location. I don't want to discuss those, please.
The class has a hard-coded static string that is the path to the database. It is a fully qualified network name (not just the drive letter). I did this because we had an issue where our network DNS got screwed up, and drive letter mappings stopped working, and some people have different drive mappings anyway.
We recently had our server moved, so I now need to go through and change these hard-coded strings.
I was thinking that I should store the path in a settings / configuration file instead. I considered "application.settings", but it is not an application setting; its specific to the class. Is there a preferred way of doing this in the existing .Net framework (this is a C# issue)?
I could simply have a small text or XML file that sits in the application directory, which is probably fine... is there an existing framework namespace or open-source code snippet that someone knows of that I can use?
I think, if you want class specific configuration, you should try to have those class instances, configuration driven. Another way of thinking but; Defining a something in a configuration file, will create an instance of the defined classname.
For example: Create a section, and call it, <Modules> and create items in like: <module type="<namespace>.DBConvertor" param="username=root;passwd=whatever"> This type will be created at startup (you need some coding here). And it's even possible to create more than one instance simultaneously with it's specific configurations.
This kind of configuration is already implemented:
You might take a look at this: "How to: Create Custom Configuration Sections Using ConfigurationSection" https://msdn.microsoft.com/en-us/library/2tw134k3.aspx
And creating instances from typenames, use the Activator class.
Besides that, there are many module/plugin libraries, (like Managed Extensibility Framework (MEF) https://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx but could be a little over the top in this case).
We are using Ideablade Devforce Classic 3.8.5.
I would like to use a separate file (not ibconfig) to define all connection strings, and then read those strings and set Ideablade to use them when connecting to the DB.
The connection strings may be for Oracle/SQL Server/Access.
Can I dynamically build and use these separate connection strings on startup of my app? Or do I always need to have them defined in ibconfig? Thanks.
DevForce will look for connection strings (rdbKeys) in a config file - either a .ibconfig or app.config file - and via an implementation of the IDataSourceKeyResolver. The resolver allows you to resolve connection strings at runtime, so is probably what you're looking for. You can find more information on how to use it both in the Developers Guide, and in a Learning Unit called "Custom DataSourceKeyResolver" under the "300 Advanced" folder. Learning units are optionally installed with the product.
Do you see any benefit in injecting the database connnection string from the Global.asax.cs
class in ASP.NET MVC compared to the method in reading the connection string from a BaseDataProvider class accessing the app.config file?
I'd prefer to inject any objects needed using constructor injection (whenever possible).
One small advantage I see is transparency regarding a class's dependencies.
For example, if you try to instantiate a class in a test harness (while doing integration testing):
in the first case (constructor injection) you immediately see that it needs a connection string and provide one
in the second case you instantiate the class (perhaps using a default constructor) and after some trial & error discover that it depends on the ConnectionString property being set
Update:
Another advantage of the constructor injection approach is that it decouples the class itself from the mechanism of getting the connection string from the app.config.
This could enable in the future scenarios that you don't even think about right now.
For example, in a project I currently work on I have a component that has db access and I have reused it in several contexts. In some of them it uses a standard connection string coming from the config file, while in others I have another component that decides which connection string to use based on some conditions.
If you go for the second approach, you'll need to change the code in order to support such a functionality.
I usually take a hybrid approach such that my BaseDataProvider class has an empty constructor which defaults to whatever is stored in the config, but is overriden to accept a connString for cases where I need a connection other than the default.
Then my Global.asax class contains the necessary logic to determine what connection string they might need in a given situation. For example, say you have your web application deployed internationally on servers all over the world, you'd want to connect to the nearest available db server to avoid latency issues. So on user login, I would figure out where my user was and then set them up with the appropriate connection
So normally I just put my sql connection string in my asp.net web.config and reference it whenever I need to open a database connection, however this leaves me with referencing it all over my project. This also exposes my sql connection username and password in my web.config if it isn't encoded.
What are you best practices as far as keeping the connection methods in a class or class library? I saw a php tutorial that did this really well (but I can't find it again) and allowed for re-usability.
I would always keep the connection string in the web.config since the servers/database connections can always change, even if it's not common.
To make it more comfortable to view in code you can always add something like this :
String m_Connection = ConfigurationManager.AppSettings["MyConnectionString"];
and then just reference m_Connection everywhere.
I would also always encrypt the connection string using an EncryptionProvider.
Great MSDN article : How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI
I agree with #gillyb. In most cases the web.config is the place for the connection string(s). The other common alternative is a spring.Net config file if you make heavy use of dependedncy injection. The end result is the same except that the site will not rebuild if you change the Spring.config file, whereas it will if you change web.config.