I have a web application in C# with .NET Framework 4.0 and I'm trying to find a way to define a variable in Web.Config that can be referenced elsewhere within the Web.Config.
I want something like this.
<?xml version="1.0" encoding="utf-8"?>
<LocalWebConfigVars>
<add key="Var1" value="ServerName1"/>
<add key="Var2" value="DatabaseName1"/>
</LocalWebConfigVars>
<configuration>
<connectionStrings>
<add name="AppConnectionString" connectionString="DATA SOURCE=#Var2 ServerName=#Var1"/>
<add name="OtherStuff" value="#Var1"/>
etc...
Currently I have to keep 3 or 4 hard-coded values (some embedded others just the value) updated to the same thing and would like to make it easier to keep in sync.
Is this possible?
Thanks.
Edit:
Just some background. The reason this is becoming problematic is that we define the apps database instance (among other instance specific setting) in the web.config. We have multiple database instances in our test and production environments and if I need to switch to a different one them while testing something and miss one of the hand full of references I get some strange results. I'm trying to avoid this by defining it once and referencing it everywhere else.
Would not doing a simply .config transformation for each of your environments work, by setting up a project configuration & transform, you would be able to swap from environment to environment by the use of solutions configuration dropdown.
See this link
for more info on transforms on .config files
Related
Hello I have build a small app to demo a concept in C# in which I added the application config file etc added System.Configuration dll to the reference and accessed the settings:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="username" value="myknownusername"/>
</appSettings>
</configuration>
No news It worked flawlessly with the code:
private String username = ConfigurationManager.AppSettings["username"];
Now I have been asked to do the port the app to VB.NET and to my biggest surprise. It's been a while that I opened visual studio in VB.NET project. I was surprised to see an already white dashed App.config file so I added my AppSettings section and after 3 hours I still can't get the value of the username using the same ConfigurationManager
Dim username as String = ConfigurationManager.AppSettings("username")
I have included another application configuration app1.config which by the way has generated entries already. I could not get anything with the app1.config either.It also returns Nothing
</sharedListeners>
</system.diagnostics>
</configuration>
I am really perplexed as how a simple reading of configuration file could be this challenging in VB.NET unless I am using the wrong method which I always use in C#.
Kindly point me to whatever I am not doing right.
EDIT
As you can see in the picture below, I have all it needs to work properly.I as expecting to read the setting key from either App.config or app1.config. When I run like shown below the MessageBox is empty
I found the culprit, I needed to right click the generated App.config and choose Include In Project. that's it. it's weird because I never do that in a C# project.
I am writing a Web API 2.0 project and a test project using Visual Studio 2013.
In the test project, I saved some information in the Settings.settings file (under TestProject->Properties in the Solution Explorer). One of the things saved there is the connection string to a database that is stored locally.
Unfortunately, the connection string will be slightly different on each person's computer when they download the repo. When people push their code to the master repo it overwrites the connection string, affecting everyone else.
What is the best way to make this configurable for each user such that everyone can have their own database path, but pushing to master repo won't affect anyone?
Edit
I don't think this is exactly a duplicate of that other question. Although, yes, my configuration settings are stored in app.config (since they happen to be application settings rather than user settings), following the solution in the other answer will lead me with the same problem. The app.config will contain configSource="otherconfig.config", and when people push that file to the master repo, it will still clobber other people's values. I need something that allows the custom configurations to be source-controlled without affecting the other users of the project.
Visual Studio handles this automatically for WEB projects through Web.config transformations
You'll need to install a separate plugin for use with App.config and non-web projects. http://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859
The plugin basically adds the same functionality to app.config files, and works with the same syntax in the transform files.
Your best approach to this is to use Build Profiles. Have a developer-specific Web.developer.config and with that you get each user to choose their name in Configuration Manager. Then just make the new config, which is technically an XSLT make the changes needed for each team member.
Think of it as Debug vs Release configs, except in your case you'll have many Debug (one for each user). The Build profile you set doesn't get checked into TFS, so you're fine.
This is what a subconfig looks like:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an attribute "name" that has a value of "MyDB".
-->
<connectionStrings>
<add name="RavenDB" connectionString="Url=http://xxx/databases/xxx" xdt:Transform="Replace" xdt:Locator="Match(name)"/>
</connectionStrings>
<appSettings>
<add key="BaseUrl" value="http://xxx" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>
<system.net>
<defaultProxy enabled="true" />
<mailSettings>
<smtp xdt:TrandeliveryMethod="Network" transform="Replace">
<network xdt:Transform="Replace" host="xxx" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
</configuration>
More info on web.config transforms
http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx
The way I handle this problem is by adding a folder into my app that has only assets that don't get included in the build/publish. One of the things I include in that folder is DeveloperName.App.config files for each of my developers. Then I leave the the actual App.config file out of source control. When they check out the project, they copy their personalized DeveloperName.App.config file to the project folder and rename it to App.config.
This isn't perfect, but it gives you at least most of the goals you're looking for: The developers each get their own App.config file they can maintain and keep in source control. And the changes they make to App.config don't clobber each other every check-in.
I'm trying to do a bunch of environment-specific configuration in an asp.net MVC3 web application I'm building. I'm somewhat new to the platform and am running into a bit of an issue with environment specific configuration.
I have 3 configuration files:
Web.config
Web.Debug.config
Web.Release.config
I've placed my connectionString configuration in the Debug/Release files and it works, so I know asp.net recognizes at least some notion of my Debug/Release setup.
I've also added some custom configuration sections in Web.config like this:
<configSections>
<section name="GitHubConfig" type="SmartGigs.Controllers.GitHubConfig" />
<section name="JanRainConfig" type="SmartGigs.Services.JanRainConfig" />
</configSections>
Then I actually define them like this in Web.config:
<GitHubConfig ClientId="c" Secret="s" />
And attempt to load them like this:
var jrConfig = (JanRainConfig)WebConfigurationManager.GetSection("JanRainConfig");
var gitHubConfig = (GitHubConfig) WebConfigurationManager.GetSection("GitHubConfig");
Finally, I add a Debug-specific property into Web.Debug.config:
<JanRainConfig Key="key" TokenUrl="http://localhost:55739/Account/LogOn" />
The problem
If I get the property I defined in Web.config, it works perfectly. If I try to only define a property in Web.config or define it in Web.Debug.config and override it (and add xdt:Transform="Replace"), the property settings are either blank (in the former case) or contain the settings in Web.config (in the latter) - as though my configuration in Web.Debug.config is being ignored.
What is the correct way to accomplish what I'm trying to do?
Web.config transformations are only applied when publishing a project. You are certainly not the first, to get this wrong (me included). I suggest using a debug-configuration in the default web.config and apply only custom logic in the .release.config file.
It is somewhat sad, that the transformed web.config isn't picked up by VS when starting the project directly, but AFAIR the transformation process is a custom MSBuild Task, so one might be able to add execute it during compilation.
I've got 3 connectionstrings in web.config, and I used theirs like this:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeName"].ConnectionString))
Every metgod is called by winforms application.
One of webmethods doesn't work properly because it reads only one connectionString:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
It's not a connectionString from my web.config .
I invoke every method in the same way.
How it's impossible ??
EDITED:
I use facade: This is structure:
WinForms calls WebMethod SaveItem
SaveItem calls method on Facade: SaveItemAndDoDatabaseStuff
SaveItemAndDoDatabaseStuff does database stuff.
We can't see your web structure, but is it possible that your app isn't configured as an application in IIS, therefore is picking up the master web.config? Which would look exactly like that...
Go into IIS and ensure it is an application (it may have a cog icon).
If your WinForms application talks directly to database X (not via the web service), then the connection string for database X should be in app.config (in the WinForms project).
If your Web Service (as I understand, this includes your facade and your database layer), talks to databases X, Y and Z, then the connection strings for X, Y, and Z need to be in web.config (in the Web Services Project).
It's using the default connection string asp.net has (in the machine.config in the .net installation folders).
Do a clear:
<configuration>
<connectionStrings>
<clear/>
... your connection strings here
</connectionStrings>
</configuration>
Btw, when you say you are using "SomeName" in the connection string. It isn't surely any random connection string you used, its the default: "LocalSqlServer".
You should store the connection-strings in the web.config or app.config in whatever project that you are executing.
In your case, you should have the connection-strings in your app.config for your winforms application.
Why not just add a Trace line to print out the configuration file being used just before you ask for the connection string. Simply add the following line:
System.Diagnostics.Trace.WriteLine(
System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
"APP_CONFIG");
Set a breakpoint after this and look at the Output window for a line that starts with "APP_CONFIG:". This will give the full path to the configuration file and allow you to determine where it's being loaded. If you still see a discrepancy between the runtime values and the configuration file then likely something is changing those values at runtime within your application.
This is a late answer, but perhaps worthwhile.
I have a web-service project, and I want to run it in two modes.
One is "local as app" (for testing), and for that, at least in my current system setup, the file where it reads from is
Web.config (which it apparently reads in deug mode INSTEAD of Web.Debug.config, at least for database configuration)
So, one replace the attribute section with and copy in the ones you would use in the "Calling project for hte web service).
So replace
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
with
<appSettings>
<!-- Database Connection -->
<add key="AppDatabase" value="RedactedDatabase"/>
<add key="AppLoginID" value="RedactedLoginID"/>
<add key="AppLoginPwd" value="RedactedPwd"/>
</appSettings>
The above are found in app.config in the "calling project".... To me, this is more elegant anyway.
Now it will work in both modes.
One could use a conditional compile in the C#, but now you just read it in:
C# code:
String whichDatabase = System.Configuration.ConfigurationManager.AppSettings["AppDatabase"];
String appUsedID = System.Configuration.ConfigurationManager.AppSettings["AppLoginID"];
String appUsedPwd = System.Configuration.ConfigurationManager.AppSettings["AppLoginPwd"];
The above works in either mode, without conditional compile directives.
I am putting the setting under the property of one of my C# Class Library project for app setting:
EUCAccountService_ConnectionString
EUCTelcoDB_ConnectionString
In the development, it works nicely. Until I deported to production, I realise that the component that use those thing .. it just hang. I found that under \BIN when it compiled dewaCorp.EUC.TelcoDB.Data.dll.config and open up that file and turn out nothing.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
How to make this works? I thought by compiling it, it turned to some sort config file or something. But it didn't.
I am appreciated your comment.
The properties are not stored in the .config file they are stored in the windows user profiles.
To store setting in the .config file add a config file to the executing assembly (take note is important to use the executing assembly) and store add the settings there for connection strings there is a special note for them.
<ConnectionStrings>
<ConnectionString />
</ConnectionStrings>
You'd better take a look at similar projects, such as log4net, and Enterprise Library.
http://logging.apache.org/log4net/index.html
http://www.codeplex.com/entlib