I have an MVC project and am trying to store my API keys in a separate config file which I will ignore when pushing the code to Git. According to MSDN I should be able to store them in an App.config like like so
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="APIKey" value="APIKeyValue" />
</appSettings>
</configuration>
I should then be able to read from the file by creating a method in a model
public class KeyTest
{
public string KeyTestCall()
{
string testkey = ConfigurationManager.AppSettings.Get("APIKey");
return testkey;
}
}
and then invoke the method in my controller to assign the value from my App.config file (just so I know I'm getting the value).
public void Testing()
{
KeyTest k = new KeyTest();
ViewBag.x = k;
}
At no point will the code break for a breakpoint, the build will succeed and I can't tell if I'm getting the value or not. Any help is much appreciated. Thanks!
For a web application such as an MVC app, it's a Web.config file, not an App.config
In addition to above (re: web.config vs app.config) if you want to remove "secrets" from source control, this is one way to do it:
In web.config
<?xml version="1.0" encoding="utf-8"?>
<cofiguration>
....
<appSettings file="AppKeys.config">
<add key="SomeOtherSettingThatHasNoSecrets" value="foo" />
...
Then in a separte AppKeys.config file (you can name this whatever.config, sample as named in the above), that you don't add to Git/source control:
<appSettings>
<add key="SomeSecretKey" value="the secret" />
...
Note that AppKeys.config doesn't have an XML declaration.
Hth.
Related
In appSettings section of Web.config a file attribute is used referencing a custom config file. The goal is to have possibility to modify some app-settings in the custom config without causing the application to be restarted.
Web.config
<appSettings file="CustomAppSettings.config">
<add key="key1" value="val2" />
</appSettings>
CustomAppSettings.config
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="customKey1" value="custVal2"/>
</appSettings>
The following code does not work. It saves the value to Web.config but expected is to save it to the CustomAppSettings.config because so it will not restart the application (Source).
var configuration = WebConfigurationManager.OpenWebConfiguration("~/");
configuration.AppSettings.Settings[key].Value = value.ToString();
configuration.Save();
This does not work as well.
var configuration = WebConfigurationManager.OpenWebConfiguration("~/CustomAppSettings.config");
What am I doing wrong? Could someone point me to the right direction?
use configSource instead of file.
<appSettings configSource="CustomAppSettings.config" />
use ConfigurationSaveMode.Minimal on saving.
var configuration = WebConfigurationManager.OpenWebConfiguration("~/");
configuration.AppSettings.Settings[key].Value = value.ToString();
configuration.Save(ConfigurationSaveMode.Minimal);
I have about 10 methods in my class. In every method I use ConfigurationManager.AppSettings to get value form App.config file
like
_applicationPort = int.Parse(ConfigurationManager.AppSettings["ApplicationPort"]
My problem is that I want to make this code get AppSettings from another app.config file like AnotherPoject.exe.config.
You can also set the app.config to read another file. Something like this:
<?xml version="1.0"?>
<configuration>
<appSettings file="my\custom\file\path\external.config"/>
</configuration>
and the external.config will have the appSettings section:
<appSettings>
<add key="myKey" value="myValue" />
</appSettings>
refer to this msdn for additional info.
You could do something like this
var fileConfig = ConfigurationManager.OpenExeConfiguration("<filePath>");
int port = int.Parse(fileConfig.AppSettings["PortNumber"].ToString());
You can accomplish this by using ConfigurationManager.OpenExeConfiguration. This will allow you to open another configuration file easily.
MSDN article about OpenExeConfiguration.
I have a Web project which calls a library project (DataAccess) to retrieve some data from the database. I added an App.config file (Add -> New Item -> Application Configuration File) to the DataAccess project and added a connectionString section like this:
<configuration>
<connectionStrings>
<add name="local"
connectionString="Data Source=.\sql2008;Initial Catalog=myDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
In the DataAccess project, I have the BuildConnection method:
internal static SqlConnection BuildConnection()
{
string connectionString = ConfigurationManager.ConnectionStrings["local"].ToString();
return new SqlConnection(connectionString);
}
When I call the method from the Web project, it throws a null exception complaining that the "local" connection string doesn't exist. After debugging it for a while I added the same connection string to the Web.config of the Web project, and now it works fine. The problem though is that I want to isolate the DataAccess project from the Web project, in other words, I want the DataAccess project to use its own app.config file no matter who calls it. Is this even possible? Any help would be appreciated.
at runtime, there is just one config file. so the config file of the active project is only
considered. also, you cannot have a class library project as an active/startup project i.e.
say you have 4 Projects in your solution, and each of them has a config file, then when you run the application, only the active project's(the one which is your startup project) config file is recognized.
Now what can you do?
if you just want to isolate the sections of the config file, then you can have config file in each of your Projects, which in turn, are referenced in the main projects config i.e.
Web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="YourSettings.config">
<add key="KeyToOverride" value="Original" />
<add key="KeyToNotOverride" value="Standard" />
</appSettings>
<system.web>
<!-- standard web settings go here -->
</system.web>
YourSettings.config:
<appSettings>
<add key="KeyToOverride" value="Overridden" />
<add key="KeyToBeAdded" value="EntirelyNew" />
</appSettings>
read more about it here
if you want to have separate config files for your active project itself, than that's whole different story altogether.
its kind of ugly tweak, but read about it here
An app.config is used when you use in an Application. For a library project using a app config file not helps. Even you put it reference library the code will be in web server.
So this type isolation has no sense for any security issue.
But approach of putting things to the right place you are right, the problem is when you reference a dll it doesn't include the dll project's config.
If you want more :) Just read app.config in your lib project and using a code generator create a connection string object such as public static string ConnectionString = $GeneratedCode$;
Yes, it's possible.
Your app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="foo" value="bar"/>
</appSettings>
</configuration>
Your DataAccess layer:
namespace MyApp.DataAccess
{
public class DB
{
public string cfg;
public DB()
{
var asmName = System.Reflection.Assembly.GetAssembly(this.GetType()).GetName().Name;
var asmPath = System.Web.HttpContext.Current.Server.MapPath(#"bin\" + asmName + ".dll");
var cm = ConfigurationManager.OpenExeConfiguration(asmPath);
this.cfg = cm.AppSettings.Settings["foo"].Value;
}
}
}
Here's how to use it:
namespace MyApp.WebApp
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var db = new MyApp.DataAccess.DB();
Response.Write(db.cfg);
}
}
}
When you compile data access project, it'll generate a MyApp.DataAccess.dll.config out of your app.config content. Add MyApp.DataAccess.dll.config and MyApp.DataAccess.dll to your web app project and make sure to mark Copy To Output Directory to Copy if newer for MyApp.DataAccess.dll.config.
Is it possible to add an custom configuration element at runtime.
Here is my app.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="NodeList"
type="Configuration.NodeListSection, NodeListConfiguration"
requirePermission="false" />
</configSections>
<NodeList>
<nodes>
<add name="Dev1" isdefault="false" description ="Dev server" />
<add name="QA1" isdefault="true" description="QA server"/>
<add name="Prod1" isdefault="false" description="Production" />
</nodes>
</NodeList>
</configuration>
Can we add more nodes at runtime using C# code.
This doesn't appear to be from a built-in configuration section. You will find that "NodesList" is an section/element that is custom written. To determine where in your codebase it is coming from look for "NodesList" at the top of your config file in the configSections element. That will point you at the class to look into.
After that, you need the class to support write operations properly.
To learn a lot more about customising configuration files there is a great series at CodeProject on the topic. In particular, the section on Saving Configuration Changes should be helpful to you.
Edit (after more info added to question):
Try something like (of course it all depends on what's in NodeListSection codebase):
using Configuration;
var nodeListSection = ConfigurationManager.GetSection("NodeList") as Configuration.NodeListSection;
var newNode = new NodeElement() { Name = "xyz", IsDefault = false, Description = "New Guy" };
nodeListSection.Nodes.Add(newNode);
Configuration.Save(ConfigurationSaveMode.Modified);
The file you have posted does not look like a normal .NET config file, but a custom XML file.
In either case - .config files are just XML files - you can open, manipulate and save them using any of the XML libraries within the BCL, such as XDocument.
However, if you want to make changes to configuration during runtime, you will need to decide whether the application should apply these changes at runtime as well and code for this, as normally a configuration file will only be read at startup.
private void AddNewKey_Config(string key, string value, string fileName)
{
var configFile = ConfigurationManager.OpenExeConfiguration(fileName);
configFile.AppSettings.Settings.Add(key, value);
configFile.Save();
}
Inside my web.config file I've got code like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
<section name="UninstallSurveySettings" type="dashboard.UninstallSurveyConfig" />
</configSections>
...
<UninstallSurveySettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</UninstallSurveySettings>
...
</configuration>
I need to be able to access this field from my custom control. The control can be dropped into any website and needs to check that site's web.config for the fileLocation value in UninstallSurveySetting.
I've tried a couple different approaches with no luck. Any help on this would be greatly appreciated.
Much easier to use AppSettings.
Web.config:
<configuration>
<appSettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</appSettings>
</configuration>
Code:
string location = System.Configuration.ConfigurationManager.AppSettings["fileLocation"];
If your section will become more complex, then:
var section = (NameValueFileSectionHandler)ConfigurationManager.GetSection("UninstallSurveySettings");
if (section != null)
{
// access section members
}
P.S.
Maybe you want to use ConfigurationSection class instead of handler.
In ASP.NET MVC 3 the tag cannot be a direct child of (it results in a configuration error).
How about adding your key to the section. Then you can easily access it via the ConfigurationManager.AppSettings collection.
using System.Configuration.ConfigurationManager and you will be able to get what you want from the web.config
I was able to solve this by creating a configuration class for it and placing this code in the web.config:
<section name="UninstallSurveyConfig" type="dashboard.UninstallSurveyConfig" />
..
<UninstallSurveyConfig dirFileLocation="C:\inetpub\wwwroot\build\output" webFileLocation="~/output" />