System.InvalidCastException after adding customize section in app.config - c#

I want to create a simple section without writing any class by myself, I have read other posts and tried building my own section but it throws an exception of System.InvalidCastException when I try to get my section. Could anyone tell me how I can solve it? thanks!
Exception message:
An unhandled exception of type 'System.InvalidCastException' occurred in HttpServer.exe
Additional information: Unable to cast object of type 'System.Configuration.KeyValueInternalCollection' to type 'System.Configuration.AppSettingsSection'.
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="extensions" type="System.Configuration.AppSettingsSection" />
</configSections>
<extensions>
<add key=".gif" value="image/gif"/>
<add key=".png" value="image/png"/>
<add key=".jpg" value="image/jpeg"/>
</extensions>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
C# code:
AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("extensions");
Console.WriteLine(section.Settings[".gif"].Value.ToString());

Change the System.Configuration.AppSettingsSection to System.Configuration.NameValueSectionHandler and get the value by
System.Collections.Specialized.NameValueCollection

Related

Facing issue while running feature, specflow in visual studio, build error

I have created a basic feature file and trying to execute my first program. I have installed all mandatory packages through NuGet.
Error received :
Error The "GenerateFeatureFileCodeBehindTask" task failed unexpectedly.
System.Exception: Error when reading project file. ---> System.Configuration.ConfigurationErrorsException: Unrecognized element 'unitTestProvider'.
at System.Configuration.ConfigurationElement.DeserializeElement(XmlReader reader, Boolean serializeCollectionKey)
at System.Configuration.ConfigurationSection.DeserializeSection(XmlReader reader)
at TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler.CreateFromXml(String xmlContent)
at TechTalk.SpecFlow.Configuration.ConfigurationLoader.Load(SpecFlowConfiguration specFlowConfiguration, ISpecFlowConfigurationHolder specFlowConfigurationHolder)
at TechTalk.SpecFlow.Generator.Configuration.GeneratorConfigurationProvider.LoadConfiguration(SpecFlowConfiguration specFlowConfiguration, SpecFlowConfigurationHolder specFlowConfigurationHolder)
at TechTalk.SpecFlow.Generator.Configuration.GeneratorConfigurationProviderExtensions.LoadConfiguration(IGeneratorConfigurationProvider configurationProvider, SpecFlowConfigurationHolder configurationHolder)
at TechTalk.SpecFlow.Generator.Project.ProjectReader.ReadSpecFlowProject(String projectFilePath, String rootNamespace)
--- End of inner exception stack trace ---
at TechTalk.SpecFlow.Generator.Project.ProjectReader.ReadSpecFlowProject(String projectFilePath, String rootNamespace)
at TechTalk.SpecFlow.Generator.Project.MSBuildProjectReader.LoadSpecFlowProjectFromMsBuild(String projectFilePath, String rootNamespace)
at SpecFlow.Tools.MsBuild.Generation.SpecFlowProjectProvider.GetSpecFlowProject()
at SpecFlow.Tools.MsBuild.Generation.GenerateFeatureFileCodeBehindTaskExecutor.Execute()
at SpecFlow.Tools.MsBuild.Generation.GenerateFeatureFileCodeBehindTask.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() specflowFramework
my app.config looks like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<configSections>
<sectionGroup name="NUnit">
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler" />
</sectionGroup>
<section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
</configSections>
<specFlow>
<language feature="en-US" />
<unitTestProvider name="MSTest" />
</specFlow>
</configuration>
The unit test providers are not configured anymore in the app.config with SpecFlow 3. You have to use the appropriate NuGet package. Doc link: https://docs.specflow.org/projects/specflow/en/latest/Guides/UpgradeSpecFlow2To3.html#changes-to-how-unit-test-providers-are-configured
In your case, you have to add the SpecFlow.NUnit package to your project and adjust your app.config to
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<configSections>
<sectionGroup name="NUnit">
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler" />
</sectionGroup>
<section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
</configSections>
<specFlow>
<language feature="en-US" />
</specFlow>
</configuration>
The list of the correct NuGet package depending on your unit test runner is: https://docs.specflow.org/projects/specflow/en/latest/Installation/Unit-Test-Providers.html
Full disclosure: I am a developer and maintainer of SpecFlow and SpecFlow+

App.config can't find my element

I have a simple app.config file that doesn't quite pass the IDEs checker.
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="XmlRoot" type="System.String"/>
</configSections>
<connectionStrings>
<omitted/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<XmlRoot>
<add key="relativepath" value=""/>
</XmlRoot>
</configuration>
I added the <section name="XmlRoot" type="System.String" /> part to the config and then I tried to define the name and key here: <add key="relativepath" value=""/>. But for some reason the IDE gives me the following Messages:
I rarely use the app.config file so it could just be a noob mistake. How do I make it recognize my tags?
If it's just a simple string, you can use AppSettings to accomplish this.
<configuration>
<appSettings>
<add key="relativepath" value="mypath" />
</appSettings>
</configuration>
Access it from C# like this:
string path = ConfigurationManager.AppSettings["relativepath"]);
Try changing your type to System.Configuration.NameValueSectionHandler
this is how I define my sections:
<configSections>
<sectionGroup name="MySettings">
<section name="serverConfiguration" type="System.Configuration.NameValueSectionHandler"></section>
<section name="sqlSettings" type="System.Configuration.NameValueSectionHandler"></section>
</sectionGroup>
</configSections>
...
<MySettings>
<sqlSettings>
<add key="sqlTransactionTimeOut" value="0" />
</sqlSettings>
<serverConfiguration>
<add key="resolveDnsAsync" value="true" />
</serverConfiguration>
</MySettings>
Probably you need to use the section appSettings
<configuration>
<appSettings>
<!-- and Here you define the key and the value like you do-->
<add key="relativepath" value="path"/>
</appSettings>
</configuration>
then in your code write something like this to read it.
String path = ConfigurationManager.AppSettings["relativepath"].ToString();
hope it works for you.
:)

Error: Configuration element is not declared

?xml version="1.0" encoding="utf-8" ?>
****<configuration>****
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
The above is one part of encoding in my program, which gives a error. Error is in the second line, which shows me something like a blue lined,
configuration element is not declared
For what reason it happens like this?
Error due to the missing '<' at start element
Change it to :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
It gives an error on the second line? That's certainly odd, considering the missing '<' at the start of the first line. But the asterisks around the second line also clearly don't belong there.
How did you get this file? Where does it come from?
And have you tried this?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Because that's what it probably should be.
It gives error because you are missing '<' at start of the file

Windows Service An exception occurred during a WebClient request

I receive the following error from a Windows Service application
System.Net.WebException = {"An exception occurred during a WebClient request."}
-2146233079
InnerException = {"Configuration system failed to initialize"}
The same code on a Console application works fine.
The Service file has not setup Security on "Local Service" (in my test environment)
Could you point me out what could cause the error and how to solve it?
Try
Using client As New Net.WebClient
Dim reqparm As New Specialized.NameValueCollection
reqparm.Add("DeviceId", deviceId)
reqparm.Add("StatusCode", statusCode)
reqparm.Add("Type", "printer")
reqparm.Add("Message", msg)
Dim responsebytes = client.UploadValues("http://xxx.xxx.com/api/notification", "POST", reqparm)
Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using
Catch ex As Exception
'do nothing
End Try
my App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<configSections>
<section name="app" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<app>
<add key="version" value="0.0.1"/>
</app>
</configuration>
The problem was in the App.config file. This the correct version, only one instance of <configSections> and should be the first element after <configuration>.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="app" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<app>
<add key="version" value="0.0.1"/>
</app>
</configuration>

c# Application Configuration File: AppSettings Reads Empty?

This is my first time using an XML config file. In the solution explorer I right click, add, new item, application config. file.
I then edited the file to read...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Key1" value="1000" />
</appSettings>
</configuration>
...and tried to access it with...
Int32.Parse(ConfigurationManager.AppSettings.Get("Key1"));
...but it says that the parameter is null. I looked at just ConfigurationManager.AppSettings and it's AllKeys property has dimension 0.
What am I doing wrong?
Thanks!
Right-click on your project, choose Properties>Settings tab and edit your settings there because the config file is not the only place these values are stored at.
In your code use Settings.Default.MySetting to access the settings.
You'll need to add using MyProjectName.Properties; to your using statements in order to access the settings this way or you'll have to fully qualify it as MyProjectName.Properties.Settings.Default.MySetting...
I know this is super old but I just encountered this opening an old project. A reference to System.Configuration was missing.
To ensure get information from App.config using ConfigurationManager.AppSettings["<Key name>"]; be sure to set your values inside <appSettings> section.
Example:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key ="IntervalSeconds" value ="60000"/>
<add key ="OutputPathLog" value ="\\myserver\hackingtrack\Projects\Log\"/>
<!--Jorgesys si Elenasys sunt puisori-->
<add key="InputFeeds1" value="https://cld.blahbla.com//portadaKick.json" />
<add key="InputFeeds2" value="https://cld.blahbla.com//portadaKick.json" />
<add key="InputFeeds3" value="https://cld.blahbla.com//portadaKick.json" />
</appSettings>
</configuration>
Retrieving values:
string intervalSeconds = ConfigurationManager.AppSettings["IntervalSeconds"];
string inputFeeds1 = ConfigurationManager.AppSettings["InputFeeds1"]; ;
string inputFeeds2 = ConfigurationManager.AppSettings["InputFeeds2"];
string inputFeeds3 = ConfigurationManager.AppSettings["InputFeeds3"];

Categories