problem with windows forms application settings - c#

I have used Visual Studio to generate a class for application settings in a windows forms application. The application settings aren't populated with values when debugging. Why are there no values?
Here is the generated code:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Unidata_Client.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("blah")]
public string UnidataUsername {
get {
return ((string)(this["UnidataUsername"]));
}
set {
this["UnidataUsername"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("blah")]
public string UnidataPassword {
get {
return ((string)(this["UnidataPassword"]));
}
set {
this["UnidataPassword"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("blah")]
public string UnidataHost {
get {
return ((string)(this["UnidataHost"]));
}
set {
this["UnidataHost"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("123")]
public string UnidataPort {
get {
return ((string)(this["UnidataPort"]));
}
set {
this["UnidataPort"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("blah")]
public string UnidataAccount {
get {
return ((string)(this["UnidataAccount"]));
}
set {
this["UnidataAccount"] = value;
}
}
}
}
Here is the app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Unidata_Client.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<Unidata_Client.Properties.Settings>
<setting name="UnidataUsername" serializeAs="String">
<value>blah</value>
</setting>
<setting name="UnidataPassword" serializeAs="String">
<value>blah </value>
</setting>
<setting name="UnidataHost" serializeAs="String">
<value>blah</value>
</setting>
<setting name="UnidataPort" serializeAs="String">
<value>123</value>
</setting>
<setting name="UnidataAccount" serializeAs="String">
<value>blah</value>
</setting>
</Unidata_Client.Properties.Settings>
</userSettings>
</configuration>
Here is how I am using the settings:
using (var session = UniObjects.OpenSession(Settings.Default.UnidataHost,
int.Parse(Settings.Default.UnidataPort),
Settings.Default.UnidataUsername,
Settings.Default.UnidataPassword,
Settings.Default.UnidataAccount,
"udcs"))
{
.....
}

You are using "usersettings" (scope "user" in the designer).
When changed (not default) these settings are stored somewhere in your personal profile.
These settings override the ones in the directory of your application
Could you try to change the settings to scope "application" in the designer and run again ?
If you have values then, u can be sure the usersettings are overridden in your profile directory.
Look for a file user.config in C:\Users\XX\AppData\Local\ApplicationName\Version\

Is your app.config being copied and renamed to MyApp.exe.config in your debug output directory?

Related

Changing a path for logger using Form application and implementing it to Service with C#

I am working on a File Watcher service which has a form application in it too (2 different projects in same solution). So I am getting a path for where to save the log with Forms application. Then I put that in my app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="location" value="C:\Users\user\Documents" />
<add key="logLocation" value="C:\Users\user\Documents" /> <!-- this is where it changes save it-->
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
And I have a Variables class where I define my variable.
using System.Configuration;
namespace FileWatchingService
{
public static class Variables
{
public static string FilePath { get; set; } = ConfigurationManager.AppSettings.Get("location");
public static string LogPath { get; set; } = ConfigurationManager.AppSettings.Get("logLocation");
}
}
Then I am trying put my LogPath in here:
using System;
using System.IO;
namespace FileWatchingService
{
public static class Logger
{
public static void Log(string message)
{
try
{
string _message = String.Format("{0} {1}", message, Environment.NewLine);
//File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "logFile.log", _message);
File.AppendAllText(Variables.LogPath + "logFile.log", _message);
}
catch (Exception ex)
{
//Implement logging on next version
}
}
}
}
Problem is that my way does not work. What can I do to change my log files path?
Looking solely at the code, it seems you're missing a \ at the end of the LogPath value.
You could also do File.AppendAllText(Variables.LogPath + "\logFile.log", _message); or just define the LogPath itself, such as:
<appSettings>
<add key="location" value="C:\Users\user\Documents" />
<add key="logLocation" value="C:\Users\user\Documents\log.txt" /> <!-- the file itself -->
</appSettings>
Nevertheless, I would advise to just use a library for logging, instead of developing your own. Go with NLog or Serilog

System.Configuration.ConfigurationErrorsException - Unrecognized element 'setting'

Unrecognized element 'setting'. (C:\Dev\DOT.NET\AutoPay\ibeam.config line 15)
AppInfo.Sections.Get("AutoPay.Common.Credentials") 'AppInfo.Sections.Get("AutoPay.Common.Credentials")'
threw an exception of type
'System.Configuration.ConfigurationErrorsException' System.Configuration.ConfigurationSection
{System.Configuration.ConfigurationErrorsException}
My config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="AppInfo" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="AutoPay.Common.Credentials"
type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
allowExeDefinition="MachineToLocalUser"
requirePermission="false" />
</sectionGroup>
</configSections>
<AppInfo>
<AutoPay.Common.Credentials>
<setting name="UserName" serializeAs="String"><value>********</value></setting>
<setting name="Password" serializeAs="String"><value>********</value></setting>
<setting name="ServiceUrl" serializeAs="String"><value>********</value></setting>
</AutoPay.Common.Credentials>
</AppInfo>
</configuration>
Base (abstract) class:
public abstract class BaseConfigInfo : ConfigurationSectionGroup
{
protected Configuration Configuration;
protected ConfigurationSectionGroup AppInfo;
protected ClientSettingsSection Credentials;
protected BaseConfigInfo(string configFile)
{
var fileMap = new ConfigurationFileMap(configFile);
Configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
AppInfo = Configuration.GetSectionGroup("AppInfo");
// THIS IS WHERE THE ERROR POPS //
Credentials = (ClientSettingsSection)AppInfo.Sections.Get("AutoPay.Common.Credentials");
}
protected string GetCredentialsString(string kvpName)
{
var setting = Credentials.Settings.Get(kvpName);
return setting.Value.ValueXml.InnerText;
}
public string UserName { get { return GetCredentialsString("UserName"); } }
public string Password { get { return GetCredentialsString("Password"); } }
public string ServiceUrl { get { return GetCredentialsString("ServiceUrl"); } }
}
Sample concrete class:
public class ConfigInfoIbeam : BaseConfigInfo
{
public ConfigInfoIbeam() : base(ConfigurationManager.AppSettings["ConfigInfoIbeam"]) { }
}
I know I am missing something simple here. I'm running in .NET 4. Nothing too usefull showing up when I try to google for this error. Any ideas?
I found the problem. In my config I had this:
<AppInfo>
<AutoPay.Common.Credentials>
<setting name="UserName" serializeAs="String"><value>********</value></setting>
<setting name="Password" serializeAs="String"><value>********</value></setting>
<setting name="ServiceUrl" serializeAs="String"><value>********</value></setting>
</AutoPay.Common.Credentials>
</AppInfo>
I changed it to:
<AppInfo>
<AutoPay.Common.Credentials>
<setting name="UserName" serializeAs="String">
<value>********</value>
</setting>
<setting name="Password" serializeAs="String">
<value>********</value>
</setting>
<setting name="ServiceUrl" serializeAs="String">
<value>********</value>
</setting>
</AutoPay.Common.Credentials>
</AppInfo>
Don't ask me why the underlying xml reader cannot differentiate between the two. However, problem solved! grrrr...
I think you need <settings> </settings> wrapping your three <setting> ......

unable to add data to SQL database using entity framework in windows service

I wrote a windows service for a project in which I needed to store some data in a database. I created the table with the required columns and created an entity model from the database. Context and mapping are done automatically by VS 2012. In order to test if the data is being saved, I hard coded some values and ran the service but the data doesn't get saved in the database.
Here is a sample service I wrote to test this out:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace serviceWithDatabase
{
public partial class testService : ServiceBase
{
Database1Entities db = new Database1Entities();
public testService()
{
InitializeComponent();
test();
}
protected override void OnStart(string[] args)
{
}
public void test()
{
Table t = new Table();
t.ticker = "goog";
t.Day1 = 1234;
t.Day2 = 4567;
t.Day3 = 7890.56;
db.Tables.Add(t);
db.SaveChanges();
}
protected override void OnStop()
{
}
}
}
model for the table:
namespace serviceWithDatabase
{
using System;
using System.Collections.Generic;
public partial class Table
{
public int Id { get; set; }
public string ticker { get; set; }
public Nullable<double> Day1 { get; set; }
public Nullable<double> Day2 { get; set; }
public Nullable<double> Day3 { get; set; }
}
}
App.config code:
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
I can manually go into the database via VS 2012 and add data but it won't save data via the windows service. Anyone have any suggestions ?
the database was stored within the project and VS was updating the wrong database. When you place the database outside of the project folder (e.g. on your desktop) it works perfectly fine. This issue cost me a weekend lol. Hope it helps others :)
Try deleting the App.config and passing in your connection string directly some other way.
The App.config seemed to prevent compilation for me.

The unit test adapter failed to connect to the data source

I'm having an issue with my Datasource for my unit test. I'm wanting to keep the records in XML. As far as I can tell this is supported but I keep getting this error "The unit test adapter failed to connect to the data source...".
I have set up my app.config as follows:
<configuration>
<configSections>
<section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<connectionStrings>
<add name="PersonTestData" connectionString="Dsn=XML Files;dbq=PersonTestData.xml;defaultdir=.\; driverid=790;maxbuffersize=2048;pagetimeout=5" providerName="System.Data.Odbc" />
</connectionStrings>
<microsoft.visualstudio.testtools>
<dataSources>
<add name="PersonTestData" connectionString="PersonTestData" dataTableName="PersonData" dataAccessMethod="Sequential"/>
</dataSources>
</microsoft.visualstudio.testtools>
</configuration>
The Code that I'm using is this:
[TestMethod()]
[DeploymentItem("PersonTestData.xml")]
[DataSource("PersonTestData")]
public void CompareToTest()
{
Person Test = (Person)TestContext.DataRow["Person"];
Int32 result = Main.CompareTo(Test);
Assert.IsNotNull(result);
}
And Finally the XML file It's self:
<?xml version="1.0" encoding="utf-8" ?>
<PersonData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<LastName>Jones</LastName>
<FirstName>Bill</FirstName>
<Age>24</Age>
</Person>
<Person>
<LastName>West</LastName>
<FirstName>John</FirstName>
<Age>24</Age>
</Person>
<Person>
<LastName>Jones</LastName>
<FirstName>Bill</FirstName>
<Age>24</Age>
</Person>
</PersonData>
Not sure where I'm going wrong at this point.
I think you don't need an ODBC connection string to read the xml file. Simply use the DataSource attribute as below. Also "PersonTestData.xml" properties. CopyToOutputDirectory set to "CopyAlways".
[TestClass]
public class UnitTest1
{
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[TestMethod]
[DeploymentItem("PersonTestData.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"|DataDirectory|\\PersonTestData.xml",
"Person",
DataAccessMethod.Sequential)]
public void CompareToTest()
{
var row = TestContext.DataRow;
var firstName = row["FirstName"].ToString();
var lastName = row["LastName"].ToString();
//Asserts...
}
}

StructureMap errors when using simple configuration based Constructor Injection

I have attempted a simple program to try out configuration based constructor injection. Here is the code:
using StructureMap;
namespace StructureMapConfig
{
class Program
{
static void Main(string[] args)
{
ObjectFactory.Initialize(x =>
{
x.PullConfigurationFromAppConfig = true;
});
var result = ObjectFactory.GetInstance<IIConstructor>();
}
}
public interface IIConstructor
{
}
public class Constructor : IIConstructor
{
public Constructor(bool test)
{
}
}
}
Here is my configuration file:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="StructureMap"
type="StructureMap.Configuration.StructureMapConfigurationSection,StructureMap"/>
</configSections>
<StructureMap>
<DefaultInstance MementoStyle="Attribute"
PluginType="StructureMapConfig.IIConstructor,StructureMapConfig"
PluggedType="StructureMapConfig.Constructor,StructureMapConfig"
test="false"/>
</StructureMap>
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
I keep getting a large stack trace when reading the config file, boiling down to this error:
Trying to visit parameter test of type System.Boolean in the
constructor for StructureMapConfig.Constructor, StructureMapConfig,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null --->
StructureMap.StructureMapException: StructureMap Exception Code: 205
Missing requested Instance property "test" for InstanceKey
"DefaultInstanceOfStructureMapConfig.IIConstructor,
StructureMapConfig, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null
The code definitely has a constructor argument called "test" and the destination type is correct - a boolean.
Can someone please give me guidance as to where I'm going wrong?
--
Note: I want to keep this in configuration only, as it will require a re-compile if this value is changed from "false" to "true", hence defeating the point of defining it in config.
Got it,
"MementoStyle" should be on the <StructureMap> element, not on the <DefaultInstance>

Categories