实现自定义配置节处理程序

发布于 2024-09-30 15:35:17 字数 5303 浏览 2 评论 0原文

从各种来源(包括 stackOverlflow)收集信息,但是当我开始使用它时,我收到以下错误消息

“配置属性‘deviceconfig’可能不是从 ConfigurationSection 派生的。”

我现在已经在这个问题上挣扎了一整天了,而且还没有找到解决方案,所以在这件事上的任何帮助将不胜感激。我是实现自定义配置部分的新手,所以请温柔地对待我:-)

app.config 文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="deviceconfig"  type="CNIMonitor.Core.CustomConfig.DeviceConfig,Core"/>
  </configSections>
<system.diagnostics>
    <sources>
        <!-- This section defines the logging configuration for My.Application.Log -->
        <source name="DefaultSource" switchName="DefaultSwitch">
            <listeners>
                <add name="FileLog"/>
                <!-- Uncomment the below section to write to the Application Event Log -->
                <!--<add name="EventLog"/>-->
            </listeners>
        </source>
    </sources>
    <switches>
        <add name="DefaultSwitch" value="Information" />
    </switches>
    <sharedListeners>
        <add name="FileLog"
             type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" 
             initializeData="FileLogWriter"/>
        <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
        <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
    </sharedListeners>
</system.diagnostics>
<deviceconfig>
  <devices>          
      <device deviceid = "1" 
              name = "localhost" 
              ipaddress="127.0.0.1" 
              port="10000"
              status="not listening"
              message="no message"
      />
      <device deviceid ="2" 
              name ="2nd localhost" 
              ipaddress="127.0.0.1" 
              port="20000" 
              status="not listening"
              message="no message"
      />
  </devices>  
</deviceconfig>

自定义部分处理程序代码如下:

Imports System.Configuration

命名空间 CNIMonitor.Core.CustomConfig

Public Class DeviceConfig
    Inherits ConfigurationSection
    <ConfigurationProperty("deviceconfig")> _
    Public ReadOnly Property DeviceConfig() As DeviceConfig
        Get
            Return CType(MyBase.Item("deviceconfig"), DeviceConfig)
        End Get
    End Property
End Class

<ConfigurationCollectionAttribute(GetType(Device))> _
Public Class Devices
    Inherits ConfigurationElementCollection
    Protected Overrides Function CreateNewElement() As ConfigurationElement
        Return New Device
    End Function
    Protected Overrides Function GetElementKey _
    (ByVal element As ConfigurationElement) As Object
        Return CType(element, Device).DeviceID
    End Function
    Public Sub Add(ByVal element As Device)
        Me.BaseAdd(element)
    End Sub
End Class
Public Class Device
    Inherits ConfigurationElement
    <ConfigurationProperty("deviceid", DefaultValue:="", IsKey:=True, IsRequired:=True)> _
    Public Property DeviceID() As String
        Get
            Return CType(MyBase.Item("deviceid"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("deviceid") = value
        End Set
    End Property
    <ConfigurationProperty("hostname", DefaultValue:="", IsKey:=True, IsRequired:=False)> _
    Public Property HostName() As String
        Get
            Return CType(MyBase.Item("RegisteredDate"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("RegisteredDate") = value
        End Set
    End Property
    <ConfigurationProperty("ipaddress", DefaultValue:="", IsKey:=True, IsRequired:=False)> _
    Public Property IpAddress() As String
        Get
            Return CType(MyBase.Item("ipaddress"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("ipaddress") = value
        End Set
    End Property
    <ConfigurationProperty("port", DefaultValue:="", IsKey:=True, IsRequired:=False)> _
    Public Property Port() As String
        Get
            Return CType(MyBase.Item("port"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("port") = value
        End Set
    End Property
    <ConfigurationProperty("status", DefaultValue:="", IsKey:=False, IsRequired:=False)> _
    Public Property Status() As String
        Get
            Return CType(MyBase.Item("status"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("status") = value
        End Set
    End Property
    <ConfigurationProperty("message", DefaultValue:="", IsKey:=False, IsRequired:=False)> _
    Public Property Message() As String
        Get
            Return CType(MyBase.Item("message"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("message") = value
        End Set
    End Property
End Class

End Namespace

gleanings from a variety of sources (including stackOverlflow), however when I come to use it, I get the following error message

"The Configuration property 'deviceconfig' may not be derived from ConfigurationSection."

I have been struggling with this for the better part of a day now, and am no nearer a solution, so any help in the matter would be greatly appreciated. I am a newbie in implementing custom config sections so please treat me gently :-)

The app.config file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="deviceconfig"  type="CNIMonitor.Core.CustomConfig.DeviceConfig,Core"/>
  </configSections>
<system.diagnostics>
    <sources>
        <!-- This section defines the logging configuration for My.Application.Log -->
        <source name="DefaultSource" switchName="DefaultSwitch">
            <listeners>
                <add name="FileLog"/>
                <!-- Uncomment the below section to write to the Application Event Log -->
                <!--<add name="EventLog"/>-->
            </listeners>
        </source>
    </sources>
    <switches>
        <add name="DefaultSwitch" value="Information" />
    </switches>
    <sharedListeners>
        <add name="FileLog"
             type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" 
             initializeData="FileLogWriter"/>
        <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
        <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
    </sharedListeners>
</system.diagnostics>
<deviceconfig>
  <devices>          
      <device deviceid = "1" 
              name = "localhost" 
              ipaddress="127.0.0.1" 
              port="10000"
              status="not listening"
              message="no message"
      />
      <device deviceid ="2" 
              name ="2nd localhost" 
              ipaddress="127.0.0.1" 
              port="20000" 
              status="not listening"
              message="no message"
      />
  </devices>  
</deviceconfig>

The Custom Section Handler code as follows:

Imports System.Configuration

Namespace CNIMonitor.Core.CustomConfig

Public Class DeviceConfig
    Inherits ConfigurationSection
    <ConfigurationProperty("deviceconfig")> _
    Public ReadOnly Property DeviceConfig() As DeviceConfig
        Get
            Return CType(MyBase.Item("deviceconfig"), DeviceConfig)
        End Get
    End Property
End Class

<ConfigurationCollectionAttribute(GetType(Device))> _
Public Class Devices
    Inherits ConfigurationElementCollection
    Protected Overrides Function CreateNewElement() As ConfigurationElement
        Return New Device
    End Function
    Protected Overrides Function GetElementKey _
    (ByVal element As ConfigurationElement) As Object
        Return CType(element, Device).DeviceID
    End Function
    Public Sub Add(ByVal element As Device)
        Me.BaseAdd(element)
    End Sub
End Class
Public Class Device
    Inherits ConfigurationElement
    <ConfigurationProperty("deviceid", DefaultValue:="", IsKey:=True, IsRequired:=True)> _
    Public Property DeviceID() As String
        Get
            Return CType(MyBase.Item("deviceid"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("deviceid") = value
        End Set
    End Property
    <ConfigurationProperty("hostname", DefaultValue:="", IsKey:=True, IsRequired:=False)> _
    Public Property HostName() As String
        Get
            Return CType(MyBase.Item("RegisteredDate"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("RegisteredDate") = value
        End Set
    End Property
    <ConfigurationProperty("ipaddress", DefaultValue:="", IsKey:=True, IsRequired:=False)> _
    Public Property IpAddress() As String
        Get
            Return CType(MyBase.Item("ipaddress"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("ipaddress") = value
        End Set
    End Property
    <ConfigurationProperty("port", DefaultValue:="", IsKey:=True, IsRequired:=False)> _
    Public Property Port() As String
        Get
            Return CType(MyBase.Item("port"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("port") = value
        End Set
    End Property
    <ConfigurationProperty("status", DefaultValue:="", IsKey:=False, IsRequired:=False)> _
    Public Property Status() As String
        Get
            Return CType(MyBase.Item("status"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("status") = value
        End Set
    End Property
    <ConfigurationProperty("message", DefaultValue:="", IsKey:=False, IsRequired:=False)> _
    Public Property Message() As String
        Get
            Return CType(MyBase.Item("message"), String)
        End Get
        Set(ByVal value As String)
            MyBase.Item("message") = value
        End Set
    End Property
End Class

End Namespace

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌辣 2024-10-07 15:35:17

顶层不需要 DeviceConfig 属性。您要做需要做的是为您的ConfigurationElementCollection设备添加一个属性。我还将您的 Devices 类重命名为稍微不那么模糊的名称,例如 DeviceElementCollection。试试这个:

Public Class DeviceConfig    
    Inherits ConfigurationSection    

    <ConfigurationProperty("Devices")> _    
    Public ReadOnly Property Devices() As DeviceElementCollection    
        Get    
            Return CType(Me("Devices"), DeviceElementCollection)    
        End Get    
    End Property    
End Class    

然后,在 DeviceElementCollection 的定义中,如果不添加以下内容,可能会遇到问题:

Public Overrides ReadOnly Property CollectionType() As System.Configuration.ConfigurationElementCollectionType
    Get
        Return ConfigurationElementCollectionType.BasicMap
    End Get
End Property

Protected Overrides ReadOnly Property ElementName() As String
    Get
        Return "Device"
    End Get
End Property

我为类似问题写了一个很长的答案(抱歉,在 C# 中)此处

更新 - 如何在代码中使用

Dim deviceConfiguration as DeviceConfig = ConfigurationManager.GetSection("deviceconfigs")
For Each device As Device in deviceConfiguration.Devices
    '...whatever you need to do
Next

The DeviceConfig property is not needed at the top level. What you do need to do is add a property for your ConfigurationElementCollection devices. I would also rename your Devices class something a little less ambiguous, say, DeviceElementCollection. Try this:

Public Class DeviceConfig    
    Inherits ConfigurationSection    

    <ConfigurationProperty("Devices")> _    
    Public ReadOnly Property Devices() As DeviceElementCollection    
        Get    
            Return CType(Me("Devices"), DeviceElementCollection)    
        End Get    
    End Property    
End Class    

Then, in your definition for DeviceElementCollection, you may have problems if you don't add the following:

Public Overrides ReadOnly Property CollectionType() As System.Configuration.ConfigurationElementCollectionType
    Get
        Return ConfigurationElementCollectionType.BasicMap
    End Get
End Property

Protected Overrides ReadOnly Property ElementName() As String
    Get
        Return "Device"
    End Get
End Property

I wrote up a pretty long answer to a similar question (sorry, in C#) here.

Update - how to use in code

Dim deviceConfiguration as DeviceConfig = ConfigurationManager.GetSection("deviceconfigs")
For Each device As Device in deviceConfiguration.Devices
    '...whatever you need to do
Next
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文