I am absolutely at my wits end with this, having tried basically everything. I also do not see any existing stackoverflow threads about doing this.
I have an app.config file for my C# project, and it stores a list of servers which the user can create and add to.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="servers" type="System.Configuration.AppSettingsSection" />
</configSections>
<servers>
<add key="server" value="678,true,true"/>
</servers>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
</startup>
<appSettings>
<add key="nightmode" value="Dark"/>
<add key="theme" value="Red"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="ControlzEx" publicKeyToken="69f1c32f803d307e" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
((NameValueCollection)ConfigurationManager.GetSection("servers")).Add("server", $"{port}," + $"{ (dialogResult1 == MessageDialogResult.Affirmative) },{dialogResult2 == MessageDialogResult.Affirmative}");
When the user goes to add a new key the the "servers" section, it throws the below exception.
System.Configuration.ConfigurationErrorsException: 'The configuration is read only.'
I am bewildered why this is happening
you can try:
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("test", "propertyValue");
config.Save(ConfigurationSaveMode.Modified, true);
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
string test = ConfigurationManager.AppSettings["test"];
This get de appsettings section values.
Ps.: You need Install-Package System.Configuration.ConfigurationManager.
I ended up generating my own XML configuration, since that appears to be the best way to do things.
Related
I have a .NET Framework 4.7.2 library project, inside there's an App.config file like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="NewDocumentMetadata" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<NewDocumentMetadata>
<add key="Type" value="principal"/>
<add key="IsActive" value="true"/>
</NewDocumentMetadata>
<appSettings>
<add key="Entity" value="9"/>
<add key="Flux" value="pdf"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<!-- [...] -->
</assemblyBinding>
</runtime>
</configuration>
As you can see, I have some standard settings, but also a custom section. I have no problems with the settings, but when I retrieve the section, it works, but there I'm stuck, when I try to cast it to NameValueCollection or AppSettingsSection it gives me a null value, I'm stuck with a ConfigurationOption object I am not able to work with.
var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
flux = appConfig.AppSettings.Settings["Flux"].Value; //Works
entity = appConfig.AppSettings.Settings["Entity"].Value; //Works
var metadataSection = appConfig.GetSection("NewDocumentMetadata"); //What do I do with this boy?
I need to retrieve the settings within the NewDocumentMetadata section, how to proceed?
You should try this :
var metadataSection = ConfigurationManager.GetSection("NewDocumentMetadata") as NameValueCollection;
// Get all the value foreach key
foreach(var key in metadataSection.AllKeys)
{
string value = metadataSection.GetValues(key).FirstOrDefault()
}
I just found out that the problem was with this line :
<section name="NewDocumentMetadata" type="System.Configuration.NameValueSectionHandler" />.
I changed the type and went for this :
<section name="NewDocumentMetadata" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Now I just have to do this kind of code to retrieve the values I want :
var metadataSection = (AppSettingsSection)appConfig.GetSection("NewDocumentMetadata");
foreach (var key in metadataSection.Settings.AllKeys)
{
string value = metadataSection.Settings[key].Value;
}
I have created a console app in c# that reads information from App.config. if i add things in appSettings section, i can acces them and it works, but as soon as i add some custom sections i cant read anything from it. I am using ConfigurationManager, and i have the reference for it included.
My app config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
and i am trying to acces those information like this:
string path = ConfigurationManager.AppSettings["path"];
var settings = ConfigurationManager.GetSection("ImageFormatsINeed");
When i didnt have the ImageFormatsINeed section i could get the path from AppSettings and it was working. But as soon as i added my ImageFormatsINeed section, everything stops working.
Now my question is how can i add custom sections in app.config that it will work, or should i just read my ImageInformation from some custom xml file or config file?
You have to use the tag <configSections> at the top in your app.config, for this case you should use the type AppSettingsSection
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ImageFormatsINeed" type="System.Configuration.AppSettingsSection" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
Then in your C# code:
NameValueCollection settings_section = ConfigurationManager.GetSection("ImageFormatsINeed") as NameValueCollection;
Console.WriteLine(settings_section["type1"]);
I've been trying to create an actor system that uses Akka.Remote with akka.net 1.3... However, I can't create an instance of the system due to the following exception:
TypeLoadException: Cannot instantiate transport [Akka.Remote.Transport.DotNetty.DotNettyTransport]. It has no public constructor with [Akka.Actor.ActorSystem] and [Akka.Configuration.Config] parameters
The thing is, my config is copied from the Akka.NET documentation, and I don't know what I have failed to do.. here is the config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="akka" type="Akka.Configuration.Hocon.AkkaConfigurationSection, Akka" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<akka>
<hocon>
<![CDATA[
akka {
stdout-loglevel = INFO
loglevel = INFO
# this config section will be referenced as akka.actor
actor {
provider = remote
debug {
receive = on
autoreceive = on
lifecycle = on
event-stream = on
unhandled = on
}
}
# here we're configuring the Akka.Remote module
remote {
dot-netty.tcp {
transport-class = "Akka.Remote.Transport.DotNetty.DotNettyTransport,Akka.Remote"
#applied-adapters = []
transport-protocol = tcp
port = 9090
hostname = "127.0.0.1"
}
}
}
]]>
</hocon>
</akka>
</configuration>
I would appreciate some feedback on what I am doing wrong. Thank you.
EDIT: here is the stacktrace:
" at Akka.Remote.EndpointManager.get_Listens()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at Akka.Remote.EndpointManager.<>c__DisplayClass48_0.b__0()\r\n at System.Threading.Tasks.Task`1.InnerInvoke()\r\n at System.Threading.Tasks.Task.Execute()"
Looks like you have incorrect transport configuration . instead of specifying transport you should use the default transport by removing
#transport-class = "Akka.Remote.Transport.DotNetty.DotNettyTransport,Akka.Remote"
the base configuration uses Akka.Remote.Transport.DotNetty.TcpTransport,Akka.Remote you don't need to explicitly define it in your configuration , unless there is a reason for that.
I'm trying to use a config file by directing there from App.config.
I have created a folder named Config inside my solution and created a new config file named Environment.config.
My App.Config looks as following:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<appSettings configSource="Config/Environment.config"/>
</configuration>
and the Environment.config looks as the following:
<appSettings>
<add key="URL" value="http://foo.aspx"/>
</appSettings>
I'm getting an error which says:
Result Message:
OneTimeSetUp: System.Configuration.ConfigurationErrorsException : Configuration system failed to initialize
----> System.Configuration.ConfigurationErrorsException : The configSource attribute must be a relative physical path, so the '/' character is not allowed. (D:\tfs\QA - Automation\Projects\ReportAppeal\ReportAppeal\bin\Debug\ReportAppeal.dll.config line 22)
I have tried to switch from "/" to "\" but got a different error.
Result Message:
System.Configuration.ConfigurationErrorsException : Unable to open configSource file 'Config\Environment.config'. (D:\tfs\QA - Automation\Projects\ReportAppeal\ReportAppeal\bin\Debug\ReportAppeal.dll.config line 22)
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
I'll probably need to change the way I'm directing the Environment.config file but I'm not sure how.
As the error says:
The configSource attribute must be a relative physical path
So you will need to change your key to a physical path, not a relative one:
<appSettings configSource="C:\Config\Environment.config"/>
Or just leave it under the root:
<appSettings configSource="Environment.config"/>
I am trying to do a little spike and I cannot get log file generated.
This is my NLog configuration:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.2.4.0" newVersion="3.2.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<nlog throwExceptions="true"
internalLogLevel="Warning"
internalLogFile="Rebus.Tests.Output.NLog.Internal.log"
internalLogToConsole="true"
xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="normalLogfile" type="File" fileName="${basedir}/Rebus.Tests.Output.log" />
<target name="normalConsole" type="Console" detectConsoleAvailable="true" />
</targets>
<rules>
<logger name="NormalLog" minlevel="Trace" writeTo="normalLogfile, normalConsole" />
</rules>
</nlog>
</configuration>
And here is my static Main in the Console Application:
var logger = LogManager.GetLogger("NormalLog");
logger.Error("This is a log error line");
But nothing is logged neither LogFile nor Console.
The application.exe.config is in the bin/Debug runtime folder.
And I am looking for the log file with SearchEverything so it will found in any folder where it is.
Adding some information to this question if I put a breakpoint to inspect logger variable I can see no configuration was read:
Try to change
var logger = LogManager.GetLogger("NormalLog");
to
var logger = LogManager.GetLogger("normalLogfile");
because as far as I know you have to get the logger via target-name and not via rule-name.
//edit
Have you tried to remove the nlog attributes in you app.config? Just to be sure none of them is the problem.