I am currently on a solution in ASP.net containing two project. One MVC project and the other is a class library serving as an API.
Currently I have a connection string like this in the web config of my project MVC.
I read it with the following code in my API:
public ConnectionProvider()
{
this.connectionString = ConfigurationManager.ConnectionStrings[Connection.Name].ConnectionString.ToString();
factory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[Connection.Name].ProviderName.ToString());
}
The problem is that I would like to move the connection string in the app.config of my API and by default but every time it starts, it will read in the web.config.
Using a resource file is a bad idea.
Just copy the the connection string from the api and have it in the web.config. By using the resource file there is no way to update that connection string without having to recompile.
The web application will use web.config and the connection string will be accessible from there. If the same api is to be reused in another project, say a desktop application, again just copy the connection string to the config file of the entry point.
As I suggested via comment, I would use a resource file in the class library.
While #Nkosi is not wrong that the connectionstring will be static, it's the easiest way to carry the connectionstring across w/o having an actual API or database call.
However, it's not the entire application that needs to be republished.
If the functionality in the code of the class library does not change, you can simply build the class library and overwrite the .dll of it.
Another valuable solution would be to save the connectionstring in a separate text file which all solutions will use.
Then you can replace that piece of code in all your applications while having 1 centralized point of access which can be replaced w/o building and replacing anything :).
(Posted solution on behalf of the OP).
Thanks to Dieter B!
With a resource file:
And for read it in the API:
public ConnectionProvider()
{
ResourceManager rm = new ResourceManager("Bank.Project.API.resources", GetAssemblyByName("Bank.Project.API"));
this.connectionString = rm.GetString(Connection.Name);
this.factory = DbProviderFactories.GetFactory(rm.GetString(Connection.Factory));
}
Assembly GetAssemblyByName(string name)
{
var Myassembly = AppDomain.CurrentDomain.GetAssemblies().
SingleOrDefault(assembly => assembly.GetName().Name == name);
return Myassembly;
}
Related
I am creating a dll project in C# using Visual Studio 2013 .Net 4.5. The project contains an entity model using EF6. My dll will be called as a plugin to an external application, that belongs to a software suite for some hardware products.
I have visual studio set up so that when I press debug it launches this external application (i will refer to as the gateway) which in turn makes calls to my dll, allowing me to debug.
The issue occurs when my dll tries to make calls to the entity model. I get:
InvalidOperationException -- An unhandled exception of type 'System.InvalidOperationException' occured in ENTITYFRAMEWORK.dll
'No connection string named 'Entity' could be found in the application config file.
Now, my config file has, very clearly, the required connection string which was added by VS when I set up the model. I have read all of the similar threads to this issue, and adding the connection string to the config is not the problem.
The gateway does have knowledge of the real DB instance and is given the connection string for that in a configuration. However, the entity connection string and the instance connection string differ, because of the entity jargon that gets added on by VS and EF.
I am able to create a console app which makes calls to my dll, capable of making the enity calls. I had to give the console app a reference to my dll and entity framework as well as add the connection string to the console apps config file.
This has led me to believe that, any app that makes calls into my dll must have knowledge of EF and the connection string.
Is this the case? If so, it would appear to me that I will be unable to use EF for this project because I will have no way to make the gateway aware of EF.
Thanks for your input!
So what I would do in this case is make a new Context which inherits from your current context and in the constructor pass in the connection string.
Alternatively you can also create a connection string that you can then pass into the constructors overload for your context.
public string GetConnectionString()
{
string connectionString = new EntityConnectionStringBuilder
{
Metadata = "res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new SqlConnectionStringBuilder
{
InitialCatalog = ConfigurationManager.AppSettings["SystemDBName"],
DataSource = ConfigurationManager.AppSettings["SystemDBServerName"],
IntegratedSecurity = false,
UserID = ConfigurationManager.AppSettings["SystemDBUsername"],
Password = ConfigurationManager.AppSettings["SystemDBPassword"],
MultipleActiveResultSets = true,
}.ConnectionString
}.ConnectionString;
return connectionString;
}
Can't you compose the Entity connectionstring based on the sql connection string?
Otherwhise have a look at this question: How to have DLL specific config file?
Basicly you are supplying a config for the dll file. So besides of myapplication.exe.config you can have a myddl.dll.config
Is it possible to include a app.config by the host in C# .net? So i can load a different connection string and other options?
like
if (host == "stackoverflow"){
//inlcude stackoverflow.config
}else{
//include othersite.config
}
It is possible to load a configuration file. You should have a look at ConfigurationManager documentation
But if you want to use different connection strings you could use it by its name like this. See Retrieving Connection Strings at Run Time
I am trying to edit a config file of another application with my Web Service.
Currently I have:
[WebMethod]
public string EditConfig(string path)
{
string cfgPath = Path.Combine(path, "Compressor.exe.config");
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = cfgPath };
var cf = ConfigurationManager.OpenMappedExeConfiguration(configMap,
ConfigurationUserLevel.None);
string hello = cf.AppSettings.Settings["SaveTo"].Value;
return hello;
//cf.AppSettings.Settings["RandomAddedKey"].Value = "Hello World!";
//cf.Save();
}
I have also tried:
var config = ConfigurationManager.OpenExeConfiguration(path);
var hello = config.AppSettings.Settings["SaveTo"].Value;
return hello;
Sadly I haven't had success with any of these, and before resorting to the XML Editor I needed to make sure that this isn't possible or I am doing something wrong?
I have searched through StackOverFlow and the best results returned me an "Object reference not set to an instance of an object." Exception.
I have tried feeding the exe to the path the config and only the directory in several different applications.
In this case I want the Web Service to tell the Compressor what to compress and where to save it, but in the code I am just experimenting to get it working.
I am using .NET Framework 3.5 (Latest for web services).
I have tried editing apps in different kinds of framework versions and the end result was the same.
Thank you in advance.
If I get it right, what you want to do is manipulate a configuration file of another application programmatically. Your problems have nothing to do with doing your manipulation inside a web service application. While I think it is relatively easy to manipulate a configuration file through the very same application, it is not such an easy task to do it from another application. I would suggest two approaches:
Use the .NET API to do it. Here you can find an example of manipulating configuration files remotely.
You could manipulate the specific configuration file, as every other XML file using the respective .NET libraries. Here you can see how to do it.
Hope I helped!
I'm setting up a dll to be used as a third party dll for a different application. I want this dll to have it's own logging so the external application doesn't have to deal with setting up anything (I don't believe they use the same logging as we do). I've read that may not be the best solution but it's the task I've been given. We want to use log4net with this. I've looked at a few of the other questions on here and they mention that it is configurable via code, however, the main issue I'm having is that there is no clear cut entry point into our code to configure log4net. I'm curious if I should just abandon having the dll configure itself and have a method that is called by the secondary application that configures the dll's logging or if there is a better way to go about this. Any input would be much appreciated
You can configure log4net programmatically. Perhaps add this code to the constructor of your DLL.
if (!log4net.LogManager.GetRepository().Configured)
{
// my DLL is referenced by web service applications to log SOAP requests before
// execution is passed to the web method itself, so I load the log4net.config
// file that resides in the web application root folder
var configFileDirectory = (new DirectoryInfo(TraceExtension.AssemblyDirectory)).Parent; // not the bin folder but up one level
var configFile = new FileInfo(configFileDirectory.FullName + "\\log4net.config");
if (!configFile.Exists)
{
throw new FileLoadException(String.Format("The configuration file {0} does not exist", configFile));
}
log4net.Config.XmlConfigurator.Configure(configFile);
}
I deployed my asp.net web app project that has a reference to my DAL class library. How can I change the connection string in my DAL library once deployed? The DAL code was ignoring my web.config connection string and trying to use the app.config value.
I thought I would be able to edit a config file that is associated with the class library, but I can't find one. Temporarily I edited the connection string and re-compiled and re-deployed the library.
Is there an option or way to setup the project files where it changes the values of the connection string based on being compiled in debug mode versus doing a release compile.
What is the recommended way of dealing with connection strings in web apps which reference class libraries?
Clarification:
the DAL library connection strings are also utilized by some datasets and L2S classes (.dbml) and I am not sure how to change those to reference a web.config file that sits outside the library in the web app project.
Currently Using this code to get around my L2S class problem:
public partial class MyDataContext
{
partial void OnCreated()
{
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["PrimaryConnectionString"];
if (cs != null)
{
this.Connection.ConnectionString = cs.ConnectionString;
}
}
}
Generally, I let the top-level project define this, via either web.config or app.config; either by specifying that the application should include a connection-string named "FOO", or (much better) allowing the calling application to pass (one of) the connection key, the connection string, or the connection to the dll.
Then you mainly just edit web.config like normal...
I usually place the string in the web.config file and let a class (possibly a global class used to reference settings in the web.config) reference it, with the following line:
class Globals
{
static string ConnectionString =
ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
}
and use it elsewhere like:
IApartmentRepository apartmentRepository = new
ApartmentRepository(Globals.ConnectionString);
This was also Saif Khan's suggestion in his answer.
As for changing the connection strings based on compile mode, Visual Studio 2010 has support for this, see Web Deployment: Web.Config Transformation from the Visual Web Developer team blog. I do not think Visual Studio 2008 can do this out of the box, however maybe it can be done with some kind of build script.
I don't believe there is a recommended way, but a prefered way. Some store connection strings in the web.config file, while some store in the registry or machine.config, while some go to the extreme and store it remotely...yes I've seen that.
The most common storage I see and use myself is storing in the web.config. In my DAL objects I make a call to the web.config file for the connectionstring
string connStr = ConfigurationManager.ConnectionStrings["myString"].ConnectionString
as for auto changing of the connectionstring based on the app compiled mode, I've never seen that. You might have to put that check in the DAL itself to check if debug mode is turned "on" or "off". That would require 2 connectionstring entries in the web.config file.