0

The problem is: I get a NullReferenceException but I can't seem to find out why. (I just start with C#) and have read the C# for kids from Microsoft. It explained a lot but this I do not understand.

But I don't get the piece of code which throw the exception to my head.

Code is:

using System;  
using System.Collections.Generic;  
using System.Linq; using System.Text;  
using System.IO.Ports;  
using PlugwiseLib.BLL.BC;  
using plugwiseLib.BLL.BPC;  
using System.Text.RegularExpressions;  

using System.Threading;  
using System.IO;  
using PlugwiseLib.BLL.BPC;
using PlugwiseLib.UTIL;  
 namespace PlugwiseLib {  
       public class plugwiseControl  
     {  
         private SerialPort port;  
         private PlugwiseActions currentAction;  
         public delegate void PlugwiseDataReceivedEvent(object
 sender, System.EventArgs e,
 List<PlugwiseMessage> data);  
         public event PlugwiseDataReceivedEvent
 DataReceived;  

    private PlugwiseReader reader;

    /// <summary>
    /// Constructor for the Plugwise Control class
    /// </summary>
    /// <param name="serialPort">The serial port name that the plugwise stick takes</param>
    public plugwiseControl(string serialPort)
    {
        try
        {
            port = new SerialPort(serialPort);
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            port.BaudRate = 115200;
            currentAction = PlugwiseActions.None;
            reader = new PlugwiseReader();
        }
        catch (Exception e)
        {
            throw new Exception("Could not connect to plug.");
        }
    }

    /// <summary>
    /// This is the method that sends a command to the plugwise plugs.
    /// </summary>
    /// <param name="mac">The mac adress of the plug that needs to perform the action</param>
    /// <param name="action">The action that has to be performed</param>
    public void Action(string mac,PlugwiseActions action)
    {
        try
        {

            string message = "";
            switch (action)
            {
                case PlugwiseActions.On:
                    currentAction = PlugwiseActions.On;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.on,mac);


                    break;
                case PlugwiseActions.Off:
                    currentAction = PlugwiseActions.Off;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.off, mac);


                    break;
                case PlugwiseActions.Status:

                    currentAction = PlugwiseActions.Status;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.status, mac);

                    break;
                case PlugwiseActions.Calibration:
                    currentAction = PlugwiseActions.Calibration;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.calibration, mac);


                    break;
                case PlugwiseActions.powerinfo:
                    currentAction = PlugwiseActions.powerinfo;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.powerinfo,mac);

                    break;
                case PlugwiseActions.history:
                    message = "";
                    break;
            }
            if (message.Length > 0)
            {
                port.WriteLine(message);
                Thread.Sleep(10);
            }

        }
        catch (Exception e)
        {

            throw e;
        }
    }
    /// <summary>
    /// This is the method that sends a command to the plugwise plugs that retrieves the history power information
    /// </summary>
    /// <param name="mac">The mac adress of the plug that needs to perform the action</param>
    /// <param name="logId">The id of the history message that has to be retrieved</param>
    /// <param name="action">The action that has to be performed this MUST be history</param>
    public void Action(string mac,int logId,PlugwiseActions action)
    {
        string message = "";
        switch(action)
        {
            case PlugwiseActions.history:
             currentAction = PlugwiseActions.history;
             message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.history, MessageHelper.ConvertIntToPlugwiseLogHex(logId), mac);
         break;
        }

        if (message.Length > 0)
        {
            port.WriteLine(message);
            Thread.Sleep(10);
        }
    }

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {// Event for receiving data

        string txt = port.ReadExisting();
        List<PlugwiseMessage> msg = reader.Read(Regex.Split(txt, "\r\n"));
        DataReceived(sender, new System.EventArgs(), msg);


    }

    /// <summary>
    /// This method Opens the connection to the serial port
    /// </summary>
    public void Open()
    {
        try
        {
            if (!port.IsOpen)
            {
                port.Open();
            }
        }
        catch (System.IO.IOException ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// This method closes the connection to the serial port
    /// </summary>
    public void Close()
    {
        try
        {
            if (port.IsOpen)
            {
                port.Close();
            }
            Thread.Sleep(5);
        }
        catch (IOException ex)
        {
            throw ex;
        }
    }
  }
}

I get the exception at this piece (in Visual C# 2008 express)

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{// Event for receiving data

    string txt = port.ReadExisting();
    List<PlugwiseMessage> msg = reader.Read(Regex.Split(txt, "\r\n"));
    DataReceived(sender, new System.EventArgs(), msg);

alt text

I checked 'msg' but this is filled with so far i can see valid data. So I don't know why I get the exception.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Plumbum7
  • 109
  • 2
  • 11

3 Answers3

3

Do you have any subscribers for plugwiseControl.DataReceived event? A common way to raise event is

var handler = DataReceived;
if(handler != null) handler(sender, EventArgs.Empty, msg);
max
  • 33,369
  • 7
  • 73
  • 84
  • string txt = port.ReadExisting(); List msg = reader.Read(Regex.Split(txt, "\r\n")); var handler = DataReceived; if (handler != null) handler(sender, EventArgs.Empty, msg); DataReceived(sender, new System.EventArgs(), msg); but the same Exeption – Plumbum7 Jan 12 '11 at 20:12
  • you don't need `DataReceived(sender, new System.EventArgs(), msg);` line anymore – max Jan 12 '11 at 20:28
  • Thank you this solved the problem but the solution of tom hamming is the same.(so far i can see, only a little bit more efficient) It is a pitty that i can not set two "accepted answer" buttons.!!!! – Plumbum7 Jan 13 '11 at 15:28
2

I think DataReceived event is not initialized, by the calling method.

ShahidAzim
  • 1,446
  • 1
  • 10
  • 15
1

In .NET, if you raise an event and there are no registered listeners for that event (nothing has done to your event what you do to your port's DataReceived event in the second line of your try {} block in your constructor), it shows up as null, and raises that exception. In your Watch list screenshot, DataReceived is null, which makes me think this is the problem. So:

if (DataReceived != null)
  DataReceived(...arguments here...);
Tom Hamming
  • 10,577
  • 11
  • 71
  • 145