簡體   English   中英

自定義app.config WPF應用程序

[英]Custom app.config WPF application

我試圖在我的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: 

你在這里沒有正確提到命名空間

<configSections>
    <section name="queries" type="app.Config.QueriesSection, app" />
</configSections>

更改為

 <configSections>
    <section name="queries" type="app.Config.QueriesSection, app.Config" />
</configSections>

我還沒有時間進行測試,但是可以嘗試以下方法。 更改下面的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)]

希望這些幫助之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM