Windows Forms SNMP Manager Code Example

The following example demonstrates an SNMP variable query in a Windows Forms environment. The query is executed asynchronously, without blocking the UI. The UI is updated with the agent's response.

 

Return to Features

 

private void button1_Click(object sender, EventArgs e)
{
    //This application has a User-Interface, which we do not want to block.
    //Start launches the specified method on a worker thread.
    //Event handlers execute on the UI thread.
    manager1.Start(sendGetRequest, manager1.Mib.CreateVariable(NodeName.sysContact));
}
 

private void sendGetRequest(Dart.Snmp.ManagerSlave slave, object state)
{
    //This function performs an SNMP Get operation using blocking calls.
    //Use the Start method to execute this function on a worker thread.
    try
    {
        GetMessage request = new GetMessage();
        request.Community = "public";
        request.Version = SnmpVersion.One;
        request.Variables.Add(state as Variable);

        //Send request and get response
        ResponseMessage response = slave.GetResponse(request, myAgentAddress);

        //Marshal message to the UI thread using the Message event.
        manager1.Marshal(new ResponseMessage[] { response }, ""null);
    }
    catch (Exception ex)
    {
        //Marshal exceptions to the UI thread via the Error event.
        manager1.Marshal(ex);
    }
}
 

private void manager1_Message(object sender, Dart.Snmp.MessageEventArgs e)
{
    //Display info about the first variable in the response, and its value.
    //This event fires on the UI thread when a Message is marshaled.
    Variable var = e.Messages[0].Variables[0] as Variable;
    label1.Text = var.Definition.ToString() + var.Value.ToString();
}
 

private void manager1_Error(object sender, ErrorEventArgs e)
{
    //Update the log with any exceptions that occur.
    //This event fires on the UI thread when an Exception is marshaled.
    textLog.AppendText("ERROR: " + e.GetException().Message + "\r\n");
}