I'm new to C#. In the past projects I have worked on, I inherited code where the user already created some default config file system to allow a user to be able to input their own settings outside of the developer environment. Where all they need is the exe and config file which they can edit.
I am writing a simple file copier application and it dawned on me that the two projects I've worked on the users went out of their way to write their own way to use config files. To save time, I looked and saw that Visual Studio gives you a default app.config file to use. So I tried to use it.
My issue:
I have this bit of code:
public static void GetBaseSoureDirSubFolders()
{
BaseSourcePath = ConfigurationManager.AppSettings.Get("BaseSourcePath");
Console.WriteLine($"Base Dir Is: { BaseSourcePath}");
DirectoryInfo dirInfo = new DirectoryInfo(BaseSourcePath);
BaseSubFolders = dirInfo.GetDirectories();
}
When I run the code inside visual studio with my appconfig file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key="BaseSourcePath" value="C:\TDX2KlarfOutputs\"/>
<add key="share" value="\\cdserver.com\share\"/>
<add key="UserCount" value="2"/>
</appSettings>
</configuration>
it does return the value I have inside the file that I wrote in Visual studio.
The problem happens when I take the exe file and the app.config file and put it in the location I want to run this code. When I run the code, it gives me C:\TDX2KlarfOutputs\ instead of the new value I put inside app.config for that BaseSourcePath. It still uses the one I set in Visual studio.
THings I have tried:
I have set it to app.config properties to Build Action =content and CopytoOutputDirector = copy if newer.
I have tried using this in my main() function :
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #".\App.config");
But this doesn't work. I am very new to C# so I'm probably not using the right terminology to describe the issue. The issue is, how can I make my console app, use values set by user on their copy of app.config file outside of Visual studio's values?
I have tried to google this but maybe due to my lack of experience I cannot find a question that answers my issue.
I think you are not using the compiled app.config but instead the uncompiled file.
If your program (.exe) name is copier, it should create a copier.app.config file.
Try to edit that.
Hope my answer helps you
Related
I'm trying place a DB connection string in an app config file for my C# console project in VS Community 2019 so I can access the string from a central location. I had to create an app.config file by adding a new one to my project. When I try to access it using the ConfigurationManager, I get a NullReferenceException 'Object not set to an instance of an object'.
These are my App.config file contents:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="DBConnection"
providerName="System.Data.SqlClient"
connectionString = "Data Source=(localdb)\ProjectsV13; Initial Catalog=DATAMINE; Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" />
</connectionStrings>
<customSettings>
</customSettings>
</configuration>
And for the sake of simplicity, I'm attempting to access via:
using System;
using System.Configuration;
public class Program
{
static void Main(string[] args)
{
var sd = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}
}
While troubleshooting I went into my project's Properties in order to access the Settings Editor, but the menu option isn't present (see pic). I even tried creating a new console application, checked its Properties and the Settings Editor doesn't exist there either. I appreciate any help!
Missing Settings Editor from Visual Studio Community 2019
I had the same issue with the Properties/Settings.Settings.
right click on Settings.Settings
choose "Open with"
Select "Settings Designer"
click "set as default"
https://developercommunity.visualstudio.com/content/problem/962124/propertiessettings-editor-view-missing.html
I test the code with your App.config, and it can get the connection string. Also, I recommend using appSettings instead of customSettings.
As to Settings, it can be found in Visual Studio Enterprise 2019.
It took all day looking through the forums for this one. I'm using .NET Core 3.0 in Visual Studio Community 2019. Basically, my ConfigurationManager was trying to access a config file from ~\bin\debug\netcoreapp3.0\DESCLogicFramework.dll.config. Where this file originated from I have no idea, but I assume it was just created automatically on building my app. Bottom line, I had to overwrite it.
On a side note: I found this out using:
var configfile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
and then exploring the configfile object in the debugger, and finding a property called "Filepath".
The steps I took to correct it were:
Rename my app.config file to be 'assemblyname'.exe.config, for example mine ended up being "DESCLogicFramework.exe.config"
Place this config file in my root project directory.
Change the config file Build Action Property to "Application definition" and its "Copy to Output Directory" Property to "Copy if newer". Both these can be accessed by right clicking on your config file and selecting "Properties". It will bring up the Properties window.
Opening up the project's .csproj file, and adding the following lines of xml right before the closing ProjectTag, you tell the build to copy your .config file to the build location and give it the .dll.config extension.
<!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="DescLogicFramework.exe.config" DestinationFiles="$(OutDir)\DescLogicFramework.dll.config" />
</Target>
<!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
Afterwards, I made sure the project was "using System.Configuration" and accessed the file contents with
var conn = ConfigurationManager.ConnectionStrings["DBconnection"];
Edit:
I am still not seeing the Settings Editor in my Project Properties, but I was able to solve the issue I was having without it.
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 am totally stunned as why one of my unit tests is failing. It is a simple test to see if the correct connectionstring is returned. My App.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation defaultLanguage="c#" debug="true" />
</system.web>
<connectionStrings>
<add name="DbConnectionString" connectionString="Test_HighOnCoding_Db" />
</connectionStrings>
</configuration>
And here is my simple unit test which always throws null exception:
[TestFixture]
public class when_retrieving_database_name_from_config
{
[Test]
public void should_get_the_correct_database_name()
{
var dbName = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
// dbName is always null
Assert.AreEqual("Test_HighOnCoding_Db",dbName);
}
}
My original answer does not apply per your comment below.
One thing I'll suggest checking, then; Is your app.config file being moved into the directory with your program, and being renamed to the same as the program, with .config added?
So, program.exe has program.exe.config as the config file?`
It looks like you have a Web application here; if so, your configuration file should be web.config rather than app.config. Then, you should be using the WebConfigurationManager from the System.Web.Configuration namespace.
It is a simple fix - put the app.config in your test project.
Because you are running from a test, the app.config needs to be in your test project, and NOT with your actual program project.
When executing your test, the context of the running application is from your test assembly, so ConfigurationManager.ConnectionStrings will be looking ONLY in your test project bin folder for YourTestAssembly.dll.config (which is auto generated from your app.config in you test project folder).
if your testdll is MyTests.dll your app.config in that sub-projet will become MyTests.dll.config. Unfortunately nunit wants "MyTests.config" (without the ".dll.")
to solve this issue
create a nunit-project for "MyTests"
open nunit-gui
create a new nunit project "MyTests.nunit" in the bin folder
add MyTests.dll to MyTests.nunit
save the nunit project.
exit nunit
add "MyTests.nunit" to your solution
copy "MyTests.nunit" to the project source. make shure that settings are
buildaction = none
copy to Ouptut Dir = always
create a configfile "MyTests.config" for "MyTests.nunit"
under project settings/build events/PostBildEventCommandLine add
copy $(ProjectDir)\app.config $(TargetDir)\$(TargetName).config
now you can run your unittest by opening "MyTests.nunit"
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