2013-04-29 41 views
0

我試圖建立在我的app.config文件自定義欄目,但是當我運行它,我得到的是我不知道如何解決的錯誤。我一直在網上閱讀了關於如何創建這些類,但現在看來,我做錯了什麼。定製的app.config WPF應用程序

任何幫助,將不勝感激!

這是代碼給錯誤:

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

你沒有提到的命名空間中正確這裏

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

改變它

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

現在我收到一個稍微不同的錯誤:InnerException:System.IO.FileNotFoundException Message =無法加載文件或程序集「ClaimantWorkbookWpf.Config」或它的某個依賴項。該系統找不到指定的文件。 Source = System.Configuration – 2013-04-29 17:50:52

+0

請檢查文件的路徑 – 2013-04-29 17:52:56

+0

我應該檢查什麼文件路徑? – 2013-04-30 12:20:27

0

我還沒有時間來檢驗這一點,但我想嘗試以下。下面更改

[ConfigurationProperty("")] 
public QueriesCollection Queries 
{ 
    get { return (QueriesCollection)base[""]; } 
} 

中的ConfigurationProperty這樣

[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名稱值。當我有一個類似的名稱不能爲空或空我填寫空字符串

[ConfigurationProperty("namehere", IsKey=false, IsRequired=true, IsDefaultCollection=true)] 

希望其中一個幫助。

相關問題