我正在尝试在app.config文件中创建自定义部分,但是当我运行它时,我收到一个错误,我不确定如何修复。我一直在网上阅读如何创建这些类,但看起来我做错了。
对此的任何帮助将不胜感激!
这是给出错误的代码:
public void LoadConfiguration()
{
try
{
// error is on the following line
QueriesSection section = ConfigurationManager.GetSection("queries") as QueriesSection;
Assert.IsNotNull(section, "section is null");
QueriesCollection queries = section.Queries;
Assert.AreNotEqual(0, queries.Count, "queries.Count != 0; actual = " + queries.Count);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
App.config
文件:
<configuration>
<configSections>
<section name="queries" type="app.Config.QueriesSection, app" />
</configSections>
<queries>
<add name="TableAvailability" sql="SELECT stuff FROM sometable" />
</queries>
</configuration>
这些是配置类:
namespace app.Config
{
public sealed class QueriesSection : ConfigurationSection
{
public QueriesSection()
{
}
[ConfigurationProperty("")]
public QueriesCollection Queries
{
get { return (QueriesCollection)base[""]; }
}
}
public sealed class QueryElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true)]
public String Name {
get { return (String)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("sql")]
public String Sql {
get { return (String)base["sql"]; }
set { base["sql"] = value; }
}
}
public sealed class QueriesCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new QueryElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((QueryElement)element).Name;
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
protected override string ElementName
{
get { return "query"; }
}
}
}
这是一个巨大的例外:
System.Windows.Markup.XamlParseException was unhandled
Message='The invocation of the constructor on type 'app.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'.
Source=PresentationFramework
LineNumber=3
LinePosition=9
StackTrace:
at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
at System.Windows.Application.DoStartup()
at System.Windows.Application.<.ctor>b__1(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at app.App.Main() in C:\Documents and Settings\C15919\my documents\visual studio 2010\Projects\app\app\obj\x86\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Configuration.ConfigurationErrorsException
Message=An error occurred creating the configuration section handler for queries: The string cannot be null or empty.
Parameter name: name
Source=System.Configuration
BareMessage=An error occurred creating the configuration section handler for queries: The string cannot be null or empty.
Parameter name: name
Line=0
StackTrace:
at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
at System.Configuration.BaseConfigurationRecord.CreateSectionDefault(String configKey, Boolean getRuntimeObject, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at app.MainWindow..ctor() in C:\Documents and Settings\C15919\my documents\visual studio 2010\Projects\app\app\MainWindow.xaml.cs:line 26
InnerException: System.ArgumentException
Message=The string cannot be null or empty.
Parameter name: name
Source=System.Configuration
ParamName=name
StackTrace:
at System.Configuration.ConfigurationProperty.ValidatePropertyName(String name)
at System.Configuration.ConfigurationProperty.ConstructorInit(String name, Type type, ConfigurationPropertyOptions options, ConfigurationValidatorBase validator, TypeConverter converter)
at System.Configuration.ConfigurationProperty..ctor(PropertyInfo info)
at System.Configuration.ConfigurationElement.CreateConfigurationPropertyFromAttributes(PropertyInfo propertyInformation)
at System.Configuration.ConfigurationElement.CreatePropertyBagFromType(Type type)
at System.Configuration.ConfigurationElement.PropertiesFromType(Type type, ConfigurationPropertyCollection& result)
at System.Configuration.ConfigurationElement.get_Properties()
at System.Configuration.ConfigurationElement.Reset(ConfigurationElement parentElement)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithFullTrust(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
InnerException:
答案 0 :(得分:0)
你没有在这里正确提到命名空间
<configSections>
<section name="queries" type="app.Config.QueriesSection, app" />
</configSections>
将其更改为
<configSections>
<section name="queries" type="app.Config.QueriesSection, app.Config" />
</configSections>
答案 1 :(得分:0)
我没有时间测试这个,但我会尝试以下方法。更改
下面的ConfigurationProperty[ConfigurationProperty("")]
public QueriesCollection Queries
{
get { return (QueriesCollection)base[""]; }
}
像这样
[ConfigurationProperty("", IsKey=false, IsRequired=true, IsDefaultCollection=true)]
我相信应该修复你的错误。但如果没有,你的堆栈跟踪中仍然有以下内容
InnerException: System.ArgumentException
Message=The string cannot be null or empty.
Parameter name: name
Source=System.Configuration
然后,它很可能是指 ConfigurationProperty 中的名称值。当我有一个类似的名字不能为null或空时我填写空字符串
[ConfigurationProperty("namehere", IsKey=false, IsRequired=true, IsDefaultCollection=true)]
希望其中一个有所帮助。