Can't read app.config appSettings from unit test in JetBrains Rider - c#

I am using ConfigurationManager.AppSettings["someKey"] to retrieve values from app.config appSettings
<appSettings>
<add key="someKey" value="value" />
...
However, when I use this in my unit tests, the ConfigurationManager.AppSettings collection is empty.
This happens only when I run the tests from JetBrains Rider IDE!
Running them from Visual Studio (even with ReSharper runner) works perfectly fine and values are loaded.
It is a .Net 5 project using XUnit framework.
What is going on with Rider here?

First make sure the app.config is in the correct format. since you want to reference ConfigurationManager.AppSettings["someKey"]
the app.config should be structed this way
<configuration>
<appSettings>
<add key="someKey" value="value" />
</appSettings>
</configuration>
copy the app.config to the project-folder\bin\Debug\net5.0 and rename in a way that is understood by the IDE which can be achieved through adding the following lines in project file
<Target Name="CopyCustomContent" AfterTargets="AfterBuild" >
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)/ReSharperTestRunner.dll.config" />
<Target/>
Hope this helps!!

Related

dotnet publish single file using VisualStudio

I'm trying to publish a single file for a c# wpf application ( net core 6 ), without success: the pdb files are always added to the output folder. It needs to be done using VS for ... reasons.
1- Created the publish profile
2.1- Added the following line to the cs proj i'm trying to build
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
2.2- Added the following lines to all the projects in the solution
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
3- The solution also has a global NuGet.config file, and my feeling is that the issue is here: if i use the "RestorePackages" condition, no error is found but the pdbs are generated. If I don't use the condition, i get a build error. If I remove the "PackageRestore", everything is ok but it affects the debug mode, which is mandatory to have automatic restore.
<RestorePackages Condition="$(RestorePackages) == '' AND '$(Configuration)' == 'Release'">false</RestorePackages>
<packageRestore>
<add key="enabled" value="True" />
<add key="automatic" value="True" />
</packageRestore>
<packageSources>
<clear />
<add key="mySource" />
</packageSources>
??
What am i missing? Thanks

ConfigurationManager.AppSettings is always empty

Threads I searched
ConfigurationManager.AppSettings count 0
Reading settings from app.config or web.config in .NET
ConfigurationManager.AppSettings is empty?
WPF configurationmanager.appsettings collection is empty
My application is a .NET Core 3.1 app so I added the library System.Configuration.ConfigurationManager via NuGet to my project. My root folder contains a Web.Config with the following contents
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" />
<httpRuntime />
</system.web>
<appSettings>
<!-- Folder of LogParser job-configurations -->
<add key="JobFolder" value="App_Data/jobs"/>
<!-- Background task execution interval in seconds -->
<add key="Interval" value="5"/>
<!-- Message offset in seconds. Reads older messages to circumvent log4net timestamp bug -->
<add key="Offset" value="7200"/>
<!-- Caching duration for hash MemoryCache in seconds. Default is 604800 (7 days) -->
<add key="Caching" value="604800"/>
</appSettings>
</configuration>
However, when I access ConfigurationManager.AppSettings[key] it's always empty. Also, Configurationmanager.AppSettings.AllKeys is empty and the count is 0, as if it's not being parsed.
Any ideas?
I'd like to add for anyone who comes here doesn't have the option to use the appsettings.json....
For me this problem manifest itself inside a UnitTest project. ConfigurationManager expects a file named ASSEMBLYNAME.dll.config, but the Unit Tests in .net core run under the name "testhost" so it looks for testhost.dll.config. Therefore you need to rename the generated config file to match what ConfigurationManager is looking for.
In your csproj file, add a build step like such...
<Target Name="CopyAppConfig" AfterTargets="Build" DependsOnTargets="Build">
<CreateItem Include="$(OutputPath)$(AssemblyName).dll.config">
<Output TaskParameter="Include" ItemName="FilesToCopy"/>
</CreateItem>
<Copy SourceFiles="#(FilesToCopy)" DestinationFiles="$(OutputPath)testhost.dll.config" />
</Target>
Solution came from
https://github.com/microsoft/testfx/issues/348
Okay, https://stackoverflow.com/users/392957/tony-abrams pointed me in the right direction.
So basically, I need an appsettings.json file (even if the Internet told me otherwise) and I defined it like this
{
"JobFolder": "App_Data/jobs",
"Interval": 5,
"Offset": 7200,
"Caching": 604800
}
Then, in the class where I need this I added a new constructor argument IConfiguration configuration which is already registered in the DI container, so no further action needed there.
Then, when I want to access the value, I can simply do _configuration.GetValue<string>("JobFolder") and have the value.
Thank you.
I ran into this issue when migrating asp app from .net 4.x to .net core 3.1. To preserve functionality relying on ConfigurationManager I also installed nuget package System.Configuration.ConfigurationManager, but both ConnectionStrings and AppSettings were empty.
At the moment I cannot use appsettings.json, so I had to move my settings from web.config to app.config. It seems like
.net core version of ConfigurationManager works only with app.config.

C# Configuration Manager when executing Unit Test is referencing machine.config rather than app.config

I have read many other post about fixing the issue for NullReferenceException when calling ConfigurationManager.ConnectionStrings as well as what to do when Unit Test is using machine.config rather than app.config but none have worked for me. Below is a list of approaches that I've tried and have been unsuccessful with so far.
Add Existing Item to unit test and reference the app.config for the project you are testing against
Copy the app.config from the targeted project and paste it in the unit test project
Ensure the bin folder of the unit test project is copying the appropriate config file
Set the properties for the unit test to copy to output as always
Below is a copy of my current config within the Unit Test project:
<configuration>
<appSettings>
<add key="Environment" value="Development" />
</appSettings>
<connectionStrings>
<add name="Connection.Development" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\***;Initial Catalog=***;Persist Security Info=True;Integrated Security=True;Pooling=False" />
</connectionStrings>
</configuration>
I am expecting the following line of code to return Connection.Development connection string but instead I get the LocalSqlServer connection string from the machine.config consistently
string connectionString = ConfigurationManager.ConnectionStrings["Connection.Development"].ConnectionString;
I am using VS2017, running .Net Core 2.0, and trying to connect to local MS SQL Db within the application. If someone could tell me how they fixed this problem for their issue it would be greatly appreciated. If you know why, please pass that information along as well.

VS2015 NuGet private package repo source not updating

I have an issue in VS2015 where adding a NuGet source is not working.
The picture below shows the source. The URL and package name is correct and working (I can successfully push packages to the repo).
The problem is when I add it, check the checkbox, and select "Update" and "Save", it does not activate the source. When I go back into the dialog, the checkbox is unchecked. It remains unchecked no matter what I do.
I think this is a GUI issue, the problem seems to be it simply is not enabling it. Is there a config option in a project file I can manually this package source?
(Note that "NAME" and "http://myrepo.com" are not the real source name and url, but I have verified they are correct by pushing to it successfully.
Edit:
I checked the NuGet.config file and there is indeed an entry in the file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageRestore>
<add key="enabled" value="True" />
<add key="automatic" value="True" />
</packageRestore>
<packageSources>
<add key="nuget.org" value="https://www.nuget.org/api/v2/" />
<add key="NAME" value="http://myrepo.com" />
</packageSources>
<disabledPackageSources />
<activePackageSource>
<add key="All" value="(Aggregate source)" />
</activePackageSource>
</configuration>
I had been running VS as administrator due to using a local IIS instance which requires administrator privileges, magicandre1981 pointed out that NuGet.config needs write permissions, so I gave full access to the folder to normal users (I believe the NuGet.config file was generated under the administrator context therefore lacking normal user permissions).
This by itself did not solve the issue, but doing a Nuget Package Restoreafterwards, caused the NuGet feed to display again.

C# - Use configuration file in Debug mode

I discovered few days ago that we can use Configuration files in .NET and trying to use it in my applications.
First of all, configure correctly the use of configuration file is really borring :
Configuration file should have the same name as the application (understandable)
Then think to add the System.Configuration reference (understandable too)
When file is added, go in it's properties and change it to copy the file in output directory (less understandable).
Configuration file isn't taken into account in debug mode (because of *.vhosts.exe)
It takes me time to understand why this file wasn't taken into account...
So question is pretty simple, how can I fix this and use configuration files in Debug Mode ?
I would use it in order to configure my trace switches.
Here is my App.config file :
<configuration>
<appSettings>
<add key="A" value="B"/>
</appSettings>
<system.diagnostics>
<switches>
<add name="myFirstSwitch" value="1" />
<add name="MySecondSwitch" value="Error" />
</switches>
</system.diagnostics>
</configuration>
Thanks.
I think you created your config file the wrong way, the right way is:
On the Project menu, click Add New Item. The Add New Item dialog box
appears.
Select the Application Configuration
File template and then click Add. A
file named App.config is added
to your project.
This config file is automatically copied to the build folder when you build the project and works in both Debug and Release mode.

Categories