ConfigurationManager.RefreshSection("appSettings") not updating config file - c#

I am pulling my hair out with this one, having changed my app.settings url it is not reading from disk, therfore crashing my application because it is using a cached version. I have read lots of examples where it is working for people yet cant work out why this does not work
private void button1_Click(object sender, EventArgs e)
{
changeSettings();
ConfigurationManager.RefreshSection("appSettings");
this.Close();
}
public void changeSettings()
{
Configuration config =
ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
settings.Clear();
//MessageBox.Show(settings["client_postCodeRef_Service"].Value);
try
{
//settings["client_postCodeRef_Service"].Value = textBox1.Text;
//ser.Url = settings["client_postCodeRef_Service"].Value;
settings.Add("client_postCodeRef_Service", textBox1.Text);
AppSettingsSection sect = (AppSettingsSection)config.GetSection("appSettings");
ser.Url = sect.Settings["client_postCodeRef_Service"].Value;
config.Save(ConfigurationSaveMode.Modified);
MessageBox.Show(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
MessageBox.Show(settings["client_postCodeRef_Service"].Value);
}
catch (ConfigurationErrorsException e)
{
MessageBox.Show("[Exception error: {0}]",
e.ToString());
}
} // end change settings
here is my exe.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Client.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="client.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
<add key="client_postCodeRef_Service" value="http://127.0.0.1/directory/directory/webService.asmx"/>
</appSettings>
<system.serviceModel>
<bindings />
<client />
</system.serviceModel>
</configuration>

Related

System.InvalidOperationException : No connection string named 'db_modelContainer' could be found in the application config file

I wanted to test a method that creates an account.
public users CreateAccount(string _username, double _weight, string _password)
{
using (var db = new db_modelContainer())
{
Daily_summary summary = new Daily_summary { weight = _weight};
Users_dishes_gallery user_dishes = new Users_dishes_gallery { };
var x = db.usersSet;
foreach (var i in x)
{
if (_username == i.name)
{
throw new CreateAccountFailException("Username is already occupied!");
}
}
users newuser = new users { name = _username, weight = _weight, password = _password};
db.usersSet.Add(newuser);
db.SaveChanges();
return newuser;
}
}
I have another xUnit project where I wanted to write those tests. I prepared my first file:
[Fact]
//[AutoRollback]
public void CreateAccount_GivenNotOccupiedUsername_CreateSucceed()
{
string expectedLogin = "test";
string expectedPassword = "test";
double expectedWeight = 30;
Users user = new Users();
users createduser = user.CreateAccount(expectedLogin, expectedWeight,expectedPassword);
// Assert
Assert.Equal(expectedLogin, createduser.name);
Assert.Equal(expectedPassword, createduser.password);
Assert.Equal(expectedWeight, createduser.weight);
}
But I'm still getting that error.
error from vs
System.InvalidOperationException : No connection string named 'db_modelContainer' could be found in the application config file.
I tried many ways. Main project with edmx inside is my start project. I also added a link to App. config from my main project so my test project has access to the connection string but it didn't help me.
link to app.config
Below is my App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<connectionStrings>
<add name="db_modelContainer" connectionString="metadata=res://*/Database.db_model.csdl|res://*/Database.db_model.ssdl|res://*/Database.db_model.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SQLEXPRESS;initial catalog=Dietaverse_database;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<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>
</configuration>
Where is your App.Config file? If it's not hosted in the same project as your Unit Test then it probably isn't being loaded into the program. Try making a copy of your App.Config file and adding it to your Unit Test project and setting the property to "Copy Always"

How can I get custom action data of a setup project in C#?

I create a windows service and a setup project for my service.
In my windows service I can get my customer action data thinks to this :
Context.Parameters["dbname"]
But I want to access to the value of my customer action data in my service to use it in my project.
Someone have any idea how to do it in c# ?
UPDATE
In my ProjectInstaller :
public ProjectInstaller()
{
InitializeComponent();
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
string dbName = Context.Parameters["dbname"];
AppHelper.Save(dbName+" "+ Context.Parameters["targetdir"].ToString());
string xml = Context.Parameters["targetdir"].ToString() + "App.config";
XmlDocument document = new XmlDocument();
document.Load(xml);
XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
foreach (XPathNavigator nav in navigator.Select(#"/configuration.appSettings/add[#key='dbName']"))
{
nav.SetValue(dbName);
}
document.Save(xml);
}
the app.config of my windows service :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="dbName" value="totodb"/>
</appSettings>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
When I try to install my project I have an error which say that my app.config doesn't exist.
This is working for me. You will need to replace ConsoleApp2 with your output filename.
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
string dbName = Context.Parameters["dbname"].ToString();
string xml = Context.Parameters["name"].ToString() + "ConsoleApp2.exe.config";
XmlDocument document = new XmlDocument();
document.Load(xml);
XmlNode dbNameNode = document.SelectSingleNode("//configuration/appSettings/add[#key='dbName']");
dbNameNode.Attributes["value"].Value = dbName;
document.Save(xml);
}
and my custom action data is:
/name="[TARGETDIR]\" /dbname=[EDITA1]
You can add MessageBox and things in to aid debugging.

How to create a custom app.config with just one extra entry

I want my app.config file to be something like
<configSections>
<section name ="RegCompany" type =""/>
</configSections>
<RegCompany>
<Company name="Tata Motors" code="Tata"/>
<SomethingElse url="someuri"/>
</RegCompany>
Any idea how to do this? I want to get the values defined here through my code.
For simple values like this, there is an easier solution than the one in the duplicate questions.
Config:
<configSections>
<section name="RegCompany" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<RegCompany>
<add key="CompanyName" value="Tata Motors" />
<add key="CompanyCode" value="Tata" />
<add key="CompanyUrl" value="example.com" />
</RegCompany>
Code:
var section = ConfigurationManager.GetSection("RegCompany") as NameValueCollection;
if (section == null) {
throw new InvalidOperationException("Unknown company");
}
var company = section["CompanyName"];
var code = section["CompanyCode"];
var url = section["CompanyUrl"];

Formatter not set in custom trace listener for EnterpriseLibrary logging

I have created a custom trace listener for the EnterpriseLibrary logging block, but the Formatter property is always null.
This is the code:
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using System;
using System.Diagnostics;
namespace test {
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class TestTraceListener : CustomTraceListener {
public override void Write(string message) {
Console.Write(message);
}
public override void WriteLine(string message) {
Console.WriteLine(message);
}
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) {
LogEntry entry = data as LogEntry;
if (entry != null) {
if (Formatter != null) {
string formatted = Formatter.Format(entry);
WriteLine(formatted);
} else {
WriteLine(entry.Message);
}
} else {
base.TraceData(eventCache, source, eventType, id, data);
}
}
}
class Program {
static void Main(string[] args) {
Logger.SetLogWriter(new LogWriterFactory().Create());
LogEntry entry = new LogEntry("This is a test", "General", 0, 0, TraceEventType.Information, null, null);
Logger.Write(entry);
}
}
}
And this is the configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="loggingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="true" />
</configSections>
<loggingConfiguration name="logging" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Console Trace Listener"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.SystemDiagnosticsTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
formatter="Simple Formatter"
type="test.TestTraceListener, test"
traceOutputOptions="DateTime, Timestamp, ThreadId" />
</listeners>
<formatters>
<add name="Simple Formatter"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="{timestamp(local:dd/MM/yy HH:mm:ss.fff)} [{severity}]: {message}" />
</formatters>
<categorySources>
<add switchValue="Information" name="General">
<listeners>
<add name="Console Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="Warning" name="Logging Errors & Warnings" />
</specialSources>
</loggingConfiguration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>
If I understood correctly, my listener should have the "Simple Formatter" formatter that I declared in the configuration file in its Formatter property, but this is not the case.
What am I missing?
I solved the problem with the Enterprise Library Configuration Tool (I could make it work for VS 2015 following the instructions here: Does Enterprise Library 6 work with Visual Studio 2013 and/or 2015?).
The problem was a wrong value of the listenerDataType attribute, the XML declaration of the listener should have been the following:
<add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
type="test.TestTraceListener, test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
name="Console Trace Listener"
formatter="Simple Formatter" />

An error occurred creating the configuration section handler

I have a dot.NET 4.0 web application with a custom section defined:
<configuration>
<configSections>
<section name="registrations" type="System.Configuration.IgnoreSectionHandler, System.Configuration, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="true" restartOnExternalChanges="true" allowLocation="true"/>
....
at the end of the web.config file I have the respective section:
....
<registrations>
.....
</registrations>
</configuration>
Every time I call System.Configuration.ConfigurationManager.GetSection("registrations"); I get the following exception:
An error occurred creating the configuration section handler for registrations: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047) (C:\...\web.config line 13)
I'm also using Unity but don't know if that's in any way related to the error.
Have you faced this error before? How can I fix it? Do I need to replace the IgnoreSectionHandler with something else?
Given this app.config:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="registrations" type="MyApp.MyConfigurationSection, MyApp" />
</configSections>
<registrations myValue="Hello World" />
</configuration>
Then try using this:
namespace MyApp
{
class Program
{
static void Main(string[] args) {
var config = ConfigurationManager.GetSection(MyConfigurationSection.SectionName) as MyConfigurationSection ?? new MyConfigurationSection();
Console.WriteLine(config.MyValue);
Console.ReadLine();
}
}
public class MyConfigurationSection : ConfigurationSection
{
public const String SectionName = "registrations";
[ConfigurationProperty("myValue")]
public String MyValue {
get { return (String)this["myValue"]; }
set { this["myValue"] = value; }
}
}
}
You are missing the Namespace in the type attribute of your section in App.Config. Infact you dont need the full assembly info in there either. only the namespace is enough
Updated 1
yourcustomconfigclass config =(yourcustomconfigclass)System.Configuration.ConfigurationManager.GetSection(
"registrations");
and in config file only write
<section name="registrations" type="System.Configuration.IgnoreSectionHandler" requirePermission="true" restartOnExternalChanges="true" allowLocation="true"/>

Categories

Resources