2

Sharp-SNMP Library (snmptrapd) に含まれる例に基づいてアプリケーションのプロトタイプを作成して、SNMP プロトコルからデータを取得しましたが、まったく動作しなくなりました。何らかの理由で動作を停止しましたが、例外をスローせずにコンパイルし、うまく実行します。

問題は、イベントが発生しないことにあります。

依存関係:

  • Microsoft の Unity コンテナ
  • SharpSNMP ライブラリ
  • SourceGrid (Windows.Forms)

2日前までは魅力的に機能していましたが、今ではアイデアが不足していることに注意する必要がありました。(そして、コード内で根本的なものを変更していませんでした)。

C# コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using Lextm.SharpSnmpLib;
using Lextm.SharpSnmpLib.Security;
using Lextm.SharpSnmpLib.Messaging;
using Lextm.SharpSnmpLib.Pipeline;
using Lextm.SharpSnmpLib.Mib;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.Utility;
using System.Configuration;
using SourceGrid;

namespace Kraken
{
    public partial class frmConsola : Form
    {
        internal static IUnityContainer Container { get; private set; }
        private SnmpEngine engine;

        // Delegates ....
        private delegate void MostrarMensajeDelegate(SourceGrid.Grid oGrd, DateTime eventTime, String eventType, IPAddress agentAddress, String Elemento, String Valor);

        public frmConsola()
        {
            InitializeComponent();
            this.crear_demonio_trampas();
            this.crear_grid();
        }

        private void crear_grid()
        {
            grdData.BorderStyle = BorderStyle.FixedSingle;

            grdData.ColumnsCount = 6;
            grdData.FixedRows = 1;
            grdData.Rows.Insert(0);

            grdData[0, 0] = new SourceGrid.Cells.ColumnHeader("Id");
            grdData[0, 1] = new SourceGrid.Cells.ColumnHeader("Hora");
            grdData[0, 2] = new SourceGrid.Cells.ColumnHeader("Tipo");
            grdData[0, 3] = new SourceGrid.Cells.ColumnHeader("Agente");
            grdData[0, 4] = new SourceGrid.Cells.ColumnHeader("Elemento");
            grdData[0, 5] = new SourceGrid.Cells.ColumnHeader("Valor");
            grdData.AutoSizeCells();
        }

        public void MostrarMensaje(SourceGrid.Grid oGrd, DateTime eventTime, String eventType, IPAddress agentAddress, String Elemento, String Valor)
        {
            int r = 0;
            if (!oGrd.IsDisposed)
            {
                r = oGrd.Rows.Count;
                oGrd.Rows.Insert(r);
                oGrd[r, 0] = new SourceGrid.Cells.Cell(r.ToString(), typeof(string));
                oGrd[r, 1] = new SourceGrid.Cells.Cell("?", typeof(string));
                oGrd[r, 2] = new SourceGrid.Cells.Cell(eventType, typeof(string));
                oGrd[r, 3] = new SourceGrid.Cells.Cell(agentAddress.ToString(), typeof(string));
                oGrd[r, 4] = new SourceGrid.Cells.Cell(Elemento, typeof(string));
                oGrd[r, 5] = new SourceGrid.Cells.Cell(Valor, typeof(string));
                grdData.AutoSizeCells();
            }
            else
            {
                throw (new ObjectDisposedException(oGrd.Name.ToString()));
            }
        }

        private void crear_demonio_trampas()
        {
            Container = new UnityContainer().LoadConfiguration("snmptrapd");
            var users = Container.Resolve<UserRegistry>();
            users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
            users.Add(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
            users.Add(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"),
                                                                         new MD5AuthenticationProvider(new OctetString("authentication"))));
            // -------------- Plantas de fuerza ----------------------
            users.Add(new OctetString("PCC"), DefaultPrivacyProvider.DefaultPair);
            users.Add(new OctetString("peacct"), DefaultPrivacyProvider.DefaultPair);
            // -------------------------------------------------------
            var trapv1 = Container.Resolve<TrapV1MessageHandler>("TrapV1Handler");
            trapv1.MessageReceived += WatcherTrapV1Received;
            var trapv2 = Container.Resolve<TrapV2MessageHandler>("TrapV2Handler");
            trapv2.MessageReceived += WatcherTrapV2Received;
            var inform = Container.Resolve<InformRequestMessageHandler>("InformHandler");
            inform.MessageReceived += WatcherInformRequestReceived;
            this.engine = Container.Resolve<SnmpEngine>();
        }

        private void WatcherInformRequestReceived(object sender, InformRequestMessageReceivedEventArgs e)
        {
            string sTipo = "";
            uint[] codigo;
            Object[] oParams = new Object[6];
            oParams[0] = this.grdData;
            oParams[1] = new DateTime(e.InformRequestMessage.TimeStamp);
            codigo = e.InformRequestMessage.Enterprise.ToNumerical();
            foreach (int num in codigo)
            {
                if (sTipo != null)
                    sTipo += ".";
                sTipo += num.ToString();
            }
            oParams[2] = sTipo;
            oParams[3] = null;
            oParams[4] = e.InformRequestMessage.Variables()[0].ToString();
            oParams[5] = "";
            BeginInvoke(new MostrarMensajeDelegate(MostrarMensaje), oParams);
        }

        private void WatcherTrapV2Received(object sender, TrapV2MessageReceivedEventArgs e)
        {
            string sTipo = "";
            uint[] codigo;
            Object[] oParams = new Object[6];
            oParams[0] = this.grdData;
            oParams[1] = new DateTime(e.TrapV2Message.TimeStamp);
            codigo = e.TrapV2Message.Enterprise.ToNumerical();
            foreach (int num in codigo)
            {
                if (sTipo != null)
                    sTipo += ".";
                sTipo += num.ToString();
            }
            oParams[2] = sTipo;
            oParams[3] = null;
            oParams[4] = e.TrapV2Message.Variables()[0].Id.ToString();
            oParams[5] = e.TrapV2Message.Variables()[0].Data.ToString();
            BeginInvoke(new MostrarMensajeDelegate(MostrarMensaje), oParams);
        }

        private void WatcherTrapV1Received(object sender, TrapV1MessageReceivedEventArgs e)
        {
            string sTipo = "";
            uint[] codigo;
            Object[] oParams = new Object[6];
            oParams[0] = this.grdData;
            oParams[1] = new DateTime(e.TrapV1Message.TimeStamp);
            codigo = e.TrapV1Message.Enterprise.ToNumerical();
            foreach (int num in codigo)
            {
                if (sTipo != null)
                    sTipo += ".";
                sTipo += num.ToString();
            }
            oParams[2] = sTipo;
            oParams[3] = e.TrapV1Message.AgentAddress;
            oParams[4] = e.TrapV1Message.Variables()[0].Id.ToString();
            oParams[5] = e.TrapV1Message.Variables()[0].Data.ToString();
            //DateTime eventTime, String eventType, IPAddress agentAddress, String infoText
            BeginInvoke(new MostrarMensajeDelegate(MostrarMensaje), oParams);
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            this.engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, 162));
            this.engine.Start();
            this.txtStatus.Text = "Iniciando Captura ...";
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.engine.Stop();
            this.txtStatus.Text = "... Finalizando Captura.";
        }

    }
}

App.Config

<?xml version="1.0"?>
<configuration>
    <configSections>
      <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
    </configSections>
    <startup>
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
    <unity>
      <namespace name="Lextm.SharpSnmpLib.Pipeline"/>
      <namespace name="Lextm.SharpSnmpLib.Messaging"/>
      <namespace name="Lextm.SharpSnmpLib.Security"/>
      <namespace name="Lextm.SharpSnmpLib.Mib"/>
      <namespace name="Lextm.SharpSnmpLib"/>
      <assembly name="SharpSnmpLib"/>
      <assembly name="SharpSnmpLib.Engine"/>
      <assembly name="SharpSnmpLib.Mib"/>
      <aliases>
        <add alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity"/>
      </aliases>
      <containers>
        <container name="snmptrapd">
          <!-- users -->
          <register type="UserRegistry">
            <lifetime type="singleton"/>
            <constructor>
              <param name="users" dependencyType="User[]"/>
            </constructor>
          </register>
          <!-- message handler settings-->
          <register type="MessageHandlerFactory" name="MessageFactory">
            <lifetime type="singleton"/>
            <constructor>
              <param name="mappings">
                <array>
                  <!--here we only have four-->
                  <dependency name="TRAPV1"/>
                  <dependency name="TRAPV2"/>
                  <dependency name="INFORM"/>
                  <dependency name="ALL"/>
                </array>
              </param>
            </constructor>
          </register>
          <register type="HandlerMapping" name="TRAPV1">
            <lifetime type="singleton"/>
            <constructor>
              <param name="version" value="v1"/>
              <param name="command" value="TRAPV1"/>
              <param name="handler" dependencyType="IMessageHandler" dependencyName="TrapV1Handler"/>
            </constructor>
          </register>
          <register type="HandlerMapping" name="TRAPV2">
            <lifetime type="singleton"/>
            <constructor>
              <param name="version" value="v2,v3"/>
              <param name="command" value="TRAPV2"/>
              <param name="handler" dependencyType="IMessageHandler" dependencyName="TrapV2Handler"/>
            </constructor>
          </register>
          <register type="HandlerMapping" name="INFORM">
            <lifetime type="singleton"/>
            <constructor>
              <param name="version" value="v2,v3"/>
              <param name="command" value="INFORM"/>
              <param name="handler" dependencyType="IMessageHandler" dependencyName="InformHandler"/>
            </constructor>
          </register>
          <register type="HandlerMapping" name="ALL">
            <lifetime type="singleton"/>
            <constructor>
              <param name="version" value="*"/>
              <param name="command" value="*"/>
              <param name="handler" dependencyType="IMessageHandler" dependencyName="NullHandler"/>
            </constructor>
          </register>
          <register type="IMessageHandler" mapTo="TrapV1MessageHandler" name="TrapV1Handler">
            <lifetime type="singleton"/>
          </register>
          <register type="IMessageHandler" mapTo="TrapV2MessageHandler" name="TrapV2Handler">
            <lifetime type="singleton"/>
          </register>
          <register type="IMessageHandler" mapTo="InformRequestMessageHandler" name="InformHandler">
            <lifetime type="singleton"/>
          </register>
          <register type="IMessageHandler" mapTo="NullMessageHandler" name="NullHandler">
            <lifetime type="singleton"/>
          </register>
          <!-- application factory and its parts -->
          <register type="SnmpApplicationFactory">
            <lifetime type="singleton"/>
            <constructor>
              <!--<param name="logger" />-->
              <param name="store" dependencyType="ObjectStore"/>
              <param name="membershipProvider" dependencyType="IMembershipProvider" dependencyName="Composed"/>
              <param name="factory" dependencyType="MessageHandlerFactory"/>
            </constructor>
          </register>
          <register type="ObjectStore">
            <lifetime type="singleton"/>
          </register>
          <!-- this is the membership provider -->
          <register type="IMembershipProvider" mapTo="ComposedMembershipProvider" name="Composed">
            <lifetime type="singleton"/>
            <constructor>
              <param name="providers">
                <array>
                  <dependency name="v1"/>
                  <dependency name="v2"/>
                  <dependency name="v3"/>
                </array>
              </param>
            </constructor>
          </register>
          <register type="IMembershipProvider" mapTo="Version1MembershipProvider" name="v1">
            <lifetime type="singleton"/>
            <constructor>
              <param name="getCommunity" dependencyType="OctetString" dependencyName="get"/>
              <param name="setCommunity" dependencyType="OctetString" dependencyName="set"/>
            </constructor>
          </register>
          <register type="IMembershipProvider" mapTo="Version2MembershipProvider" name="v2">
            <lifetime type="singleton"/>
            <constructor>
              <param name="getCommunity" dependencyType="OctetString" dependencyName="get"/>
              <param name="setCommunity" dependencyType="OctetString" dependencyName="set"/>
            </constructor>
          </register>
          <register type="IMembershipProvider" mapTo="Version3MembershipProvider" name="v3">
            <lifetime type="singleton"/>
          </register>
          <register type="OctetString" name="get">
            <lifetime type="singleton"/>
            <constructor>
              <param name="content" value="public"/>
            </constructor>
          </register>
          <register type="OctetString" name="set">
            <lifetime type="singleton"/>
            <constructor>
              <param name="content" value="public"/>
            </constructor>
          </register>
          <!-- Engine -->
          <register type="SnmpEngine">
            <lifetime type="singleton"/>
            <constructor>
              <param name="factory" dependencyType="SnmpApplicationFactory"/>
              <param name="listener" dependencyType="Listener"/>
              <param name="group" dependencyType="EngineGroup"/>
            </constructor>
          </register>
          <register type="Listener">
            <lifetime type="singleton"/>
            <property name="Users" dependencyType="UserRegistry"/>
          </register>
        </container>
      </containers>
    </unity>
</configuration>
4

1 に答える 1

1

デバッグするには、まずパイプライン モデルに精通してください。

http://www.lextm.com/2010/11/honeycell-drops-snmp-pipeline-and-our.html

次に、デバッガーをアタッチし、使用する ListenerBinding (https://github.com/lextm/sharpsnmplib/blob/master/SharpSnmpLib/Messaging/ListenerBinding.cs) がネットワークから SNMP パケットを受信するかどうかを確認します。

その後、パイプライン SnmpApplication (https://github.com/lextm/sharpsnmplib/blob/master/SharpSnmpLib/Pipeline/SnmpApplication.cs) の次のオブジェクトに進みます。

イベントがトリガーされない理由は、段階を追ってわかるかもしれません。

さらに、SnmpEngine.ExceptionRaised にサブスクライブして、例外が発生するかどうかを確認することもできます。

于 2013-01-15T06:29:47.673 に答える