System.Configuration.ConfigurationErrorsException - Unrecognized element 'setting' - c#

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> ......

Related

Configuring instances in Unity Container configured in App.Config at runtime

I have a speciifc configuration problem.
<configuration>
<configSections>
<section name="custom" type="ConfigurationSample.CustomConfigurationSection, ConfigurationSample"/>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<custom>
<customConfigurations>
<configuration id="CAT1">
<name>Tom</name>
<address type="rent">
<area>Misissipi</area>
</address>
<conifugration/>
<configuration id="Mouse1">
<name>Jerry</name>
<address type="own">
<area>Seatle</area>
</address>
<conifugration/>
<customConfigurations>
</custom>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IAnimal" type="MyApp.IAnimal, MyApp" />
<alias alias="CAT" type="MyApp.CAT, MyApp" />
<alias alias="Mouse" type="MyApp.Mouse, MyApp" />
<container>
<!-- should register CAT instance with name CAT1 at runtime and mapto IAnimal !-->
<!-- should register Mouse with name Mouse1 at runtime and mapto IAnimal !-->
</container>
</unity>
</configuration>
This is my app.config. All I am looking for runtime registering instances in unity container while reading the custom config section since CAT class CAT configuration in its constructor.
My classes:
public interface IAnimal
{
public string Name {get;set}
pubic bool IsLiving();
}
public class Mouse
{
MouseConfig config;
public Mouse(IAnimalConfig config)
{
this.config=config;
}
public string Name {get;set}
pubic bool IsLiving(){
//do something with config
}
}
public class Cat
{
CATConfig config;
public CAT(IAnimalConfig config)
{
this.config=config;
}
public string Name {get;set}
pubic bool IsLiving(){
//do something with config
}
}
I hope you understand where i am leading to. I need to provide config objects as parameter to the derived classes. So based on my customconfig i want to register instances in unity container. So i can work with those instances in my application. since i already know their types and name of those instances i can resolve from container.
Please let me know if i have to add anything more. Thanks

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...
}
}

How do I resolve NHibernate.MappingException

I have a database, hbm mapping file and the App.config located in a class library. Now from a test project I reference that library and attempt to call a HibernateHelper class I create, at runtime the following error is thrown :
NHibernate.MappingException : Could not compile the mapping document: HibernateExample.Mappings.Products.hbm.xml
Please keep in mind that this is a class library that is being reference from a Test project.
If I change it output type to console application, it runs fine. But when I change it back to class library and reference it from my Test Project it throws the above mention error.
I tried adding config.Configure() but that throws a NhibernateDuplicateMapping exception.
FIXED:
Fixed the duplication mapping issue by removing from appconfig. and fixed the problem mapping entity by placing a hibernate.cfg.xml file in my Test project as well.
public sealed class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
const string Connectionstring = "servicestring";
public static void OpenSession()
{
var config = new Configuration();
config.Configure();
config.AddAssembly(Assembly.GetCallingAssembly());
_sessionFactory = config.BuildSessionFactory();
}
public static ISession GetCurrentSession()
{
ISession session = null;
if (_sessionFactory == null)
OpenSession();
if (_sessionFactory != null)
{
session = _sessionFactory.OpenSession();
}
return session;
}
public static void CloseSessionFactory()
{
if (_sessionFactory != null)
{
_sessionFactory.Close();
}
}
// var dsn = ConfigurationManager.ConnectionStrings[Connectionstring].ConnectionString;
//config.SessionFactory().Integrate.Using<MsSqlCeDialect>().Connected.ByAppConfing(dsn);
// System.Diagnostics.Debug.WriteLine("My connection string: "+dsn);
//Get NHibernate configuration
//_sessionFactory = config.BuildSessionFactory();
//config.AddAssembly("HibernateExample");
}
Any ideas?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory>
<property name="connection.driver_class"> NHibernate.Driver.SqlServerCeDriver</property>
<property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property>
<property name="connection.connection_string">Data Source=FirstSample.sdf;</property>
<property name="show_sql">true</property>
<mapping assembly="HibernateExample"/>
</session-factory>
</hibernate-configuration>
<connectionStrings>
<add name="testconnectionstring"
connectionString="Data Source=|DataDirectory|\FirstSample.sdf;Integrated Security=True"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urnchemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Data.SqlServerCe" publicKeyToken="89845DCD8080CC91" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-9.0.242.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="HibernateExample" namespace="HibernateExample.Domain" >
<class name="Product" table="Products">
<id name="Id" type="integer">
<generator class="identity"/>
</id>
<property name="Name" type="string"/>
<property name="Category" type="string"/>
<property name="Discontinued" />
</class>
</hibernate-mapping>
Exception Thrown:
Test 'NunitTest.TestClass.canquerydb' failed: NHibernate.MappingException : Could not compile the mapping document: HibernateExample.Mappings.Products.hbm.xml
----> System.InvalidOperationException : Could not find the dialect in the configuration
at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
at NHibernate.Cfg.Configuration.AddDeserializedMapping(HbmMapping mappingDocument, String documentFileName)
at NHibernate.Cfg.Configuration.ProcessMappingsQueue()
at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
at NHibernate.Cfg.Configuration.AddAssembly(String assemblyName)
NHibernateTest\NHibernateHelper.cs(21,0): at HibernateExample.NHibernateTest.NHibernateHelper.openSession()
NHibernateTest\NHibernateHelper.cs(28,0): at HibernateExample.NHibernateTest.NHibernateHelper.GetCurrentSession()
TestClass.cs(21,0): at NunitTest.TestClass.canquerydb()
--InvalidOperationException
at NHibernate.Dialect.Dialect.GetDialect(IDictionary`2 props)
at NHibernate.Cfg.Configuration.AddDeserializedMapping(HbmMapping mappingDocument, String documentFileName)
From the error, it appears that you are not configuring the Dialect before adding the mapping. This is required.
Here's a simple piece of basic configuration code:
var configuration = new Configuration();
configuration.SessionFactory().Integrate.Using<MsSql2012Dialect>()
.Connected.ByAppConfing("connName");//sic
//now you can add the mappings

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>

problem with windows forms application settings

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?

Categories