I cant get the results - c#

I'm using this code to get the values from app.config but I get an error. I tried another little application and it turns right.
What am I doing wrong?
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 61; i++ )
{
this.comboBox1.Items.Add(i.ToString("D2"));
this.comboBox2.Items.Add(i.ToString("D2"));
}
string minutos = ConfigurationManager.AppSettings["minutos"];
string segundos = ConfigurationManager.AppSettings["segundos"];
//label3.Text = minutos;
this.comboBox1.SelectedIndex = 30;
this.comboBox2.SelectedIndex = 59;
}
This is the error
https://ibb.co/LSCPsxN "tooltip"

It appears (from this link hidden in the comments) that you've added your settings directly to the <configuration> node, rather than inside an <appSettings> node.
Try modifying your config by adding an appSettings node and then placing your settings inside it, 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="minutos" value="30"/>
<add key="segundos" value="59"/>
</appSettings>
</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"

Configuration.SaveAs writes empty config

Getting some odd behavior from Configuration class. This code
class Program
{
static void Main(string[] args)
{
var configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
var configuration = ConfigurationManager.OpenExeConfiguration(configFile);
var value = configuration.AppSettings.Settings["Supercali"];
if (value != null) Console.WriteLine("Yay, it finally worked!");
else Console.WriteLine("Still broken.");
configuration.SaveAs("ReadConfig.config");
}
}
with this config in AppDomain.CurrentDomain.SetupInformation.ConfigurationFile:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="Supercali" value="Fragalistic"/>
</appSettings>
</configuration>
writes the following to "ReadConfig.config"
<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>
and prints this
Still broken.
Looking at it in debug view, AppDomain.CurrentDomain.SetupInformation.ConfigurationFile has the correct file, but OpenExeConfiguration seems to create a blank config. The appSettings section is empty. I'm pretty sure this is wrong, but maybe I'm missing something?
Try this:
var configFile = Assembly.GetExecutingAssembly().Location;
var configuration = ConfigurationManager.OpenExeConfiguration(configFile);
var value = configuration.AppSettings.Settings["Supercali"];
if (value != null) Console.WriteLine("Yay, it finally worked!");
else Console.WriteLine("Still broken.");
configuration.SaveAs("ReadConfig.config");
The OpenExeConfiguration expects the path to a DLL/EXE, not to the .config file.

Can not read Config File

I have a config file in my project, which I am not able to read in for some reason. Similar code has worked for me in the past. I am not sure what am I doing wrong here. I was wondering if someone would be able to have a look and let me know if I am doing something wrong. Please help...
Here's my code:
KeyValueConfigurationCollection settings;
Configuration config;
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = "myProject.exe.config";
config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
settings = config.AppSettings.Settings;
this.logFilePath = settings["logFilePath"].Value;
this.logFilePath = settings["logFileName"].Value;
Here's my Config File:
<?xml version="1.0"?/>
<configuration>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
</configuration>
Thanks in advance,
Harit
harit, try amending your structure to:
<?xml version="1.0"?/>
<configuration>
<appSettings>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
<appSettings>
</configuration>
Using the ConfigurationManager creates the requirement for this exact structure to be present. it should work as planned with the above change.
The AppSettings Collection is missing from your configuration. You only have the root-level of configured. But you are requesting in your code.
Your configuration should be
<configuration>
<appSettings>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
</appSettings>
</configuration>
Read values from different web.config:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + #"second.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None);
ConfigurationSection mySection = config.GetSection("countoffiles");
if (config.AppSettings.Settings.Count > 0)
{
System.Configuration.KeyValueConfigurationElement customSetting =
config.AppSettings.Settings["countoffiles"];
if (customSetting != null)
{
Response.Write(customSetting.Value);
}
else
{
Console.WriteLine("No countoffiles application string");
}
}

Write to just one XML attribute without affecting the rest

I have the following but its not working for me:
static void SaveVersion(string configFile, string Version)
{
XmlDocument config = new XmlDocument();
config.Load(configFile);
XmlNode appSettings = config.SelectSingleNode("configuration/appSettings");
XmlNodeList appKids = appSettings.ChildNodes;
foreach (XmlNode setting in appKids)
{
if (setting.Attributes["key"].Value == "AgentVersion")
setting.Attributes["value"].Value = Version;
}
config.Save(configFile);
}
The config file i'm loading up on config.Load(configFile) is the following:
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
</startup>
<appSettings>
<add key="AgentVersion" value="2.0.5" />
<add key="ServerHostName" value="" />
<add key="ServerIpAddress" value="127.0.0.1" />
<add key="ServerPort" value="9001" />
</appSettings>
</configuration>
Am I missing something? I figured it would edit just that particular attribute AgentVersion but its not really doing anything.
Are you aware of the ConfigurationManager class? You can use it to manipulate your app.config file without doing anything manually. I don't think you should reinvent the wheel unless you have a good reason to:
static void SaveVersion(string configFile, string version)
{
var myConfig = ConfigurationManager.OpenExeConfiguration(configFile);
myConfig.AppSettings.Settings["AgentVersion"].Value = version;
myConfig.Save();
}
Try this:
static void SaveVersion(string configFile, string Version)
{
var config = new XmlDocument();
config.Load(configFile);
var agentVersionElement = config.DocumentElement.SelectSingleNode("configuration/appSettings/add[#key = 'AgentVersion']") as XmlElement;
if (agentVersionElement != null)
agentVersionElement.SetAttribute("value", version);
config.Save(configFile);
}
Note that I'm doing the SelectSingleNode from the DocumentElement, not from the XmlDocument itself.

Custom InitialDirectory C# using app.config

I have the following in my App.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="save" value="C:\Test"/>
</appSettings>
</configuration>
And the following in my Main.cs
private void tsSaveImage_Click(object sender, EventArgs e)
{
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "TIFF Files (*.tif)|*.tif";
sd.FilterIndex = 1;
sd.InitialDirectory =
}
I would like to know how I can use the value from the key to set the InitialDirectory. The idea being that Once the app is installed I want users to navigate to app.config file and change this just the once.
Is this a good way or are there better methods?
You can set the initail directory from web.config key by
sd .InitialDirectory = ConfigurationManager.AppSettings[key].ToString();
You need to use the ConfigurationManager:
string value = ConfigurationManager.AppSettings[key];
In your case:
value = ConfigurationManager.AppSettings["save"];

Categories

Resources