0

This is first time I am doing with Bluetooth connection in C#. I am trying to send byte (data type) from application written in C# over Bluetooth.

This is my code:

public class ConnectionManager
{
    private StreamSocket socket;

        private DataWriter dataWriter;

        public void Initialize()
        {
        socket = new StreamSocket();
        }

        public void Terminate()
        {
            if (socket != null)
                {
                    socket.Dispose();
                }
        }

        public async void connect(HostName hostName)
        {
                if (socket != null)
                {
                    await socket.ConnectAsync(hostName, "1");
                    dataWriter = new DataWriter(socket.OutputStream);
                }
        }

        //sending data via Bluetooth
        public void sendCommand(byte command)
        {
                dataWriter.WriteByte(command);
        }
}

private ConnectionManager connectionManager;

// Constructor
public MainPage()
{
    InitializeComponent();
        connectionManager = new ConnectionManager();
}

private async void AppToDevice()
{
    PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
        var pairedDevices = await PeerFinder.FindAllPeersAsync();

        if (pairedDevices.Count == 0)
        {
            Debug.WriteLine("No devices found.");
        }
        else
        {
            foreach (var pairedDevice in pairedDevices)
                {
                        if (pairedDevice.DisplayName == "HC-06")
                        {
                            connectionManager.connect(pairedDevice.HostName);
                            continue;
                        }
                }
        }
}

private void send_Click(object sender, RoutedEventArgs e)
{
    byte command = Convert.ToByte(commandTextBox.Text);
        connectionManager.sendCommand(command);
}

private void connect_Click(object sender, RoutedEventArgs e)
{
    AppToDevice();
}

When I enter some value (for example 1 or 2) in commandTextBox and tap on Send button application crashes. This is the error message: An exception of type 'System.NullReferenceException' occurred in TestBluetooth.DLL but was not handled in user code

Can someone help me?

Wolf5
  • 16,600
  • 12
  • 59
  • 58

1 Answers1

0

Sounds like a very basic error. Some object is null. It will happen when you try to access a method or a property on an object that is null.

Troubleshooting:

  • Check the stacktrace of the error. It says where it fails.
  • Turn on break on all exceptions when you debug so you can see where exactly it fails, and see which object is null.
  • If you can not debug it, add a try/catch around all the code in every method you have and use a MessageBox.Show(ex.ToString()) to display the full error with stacktrace when it fails.
  • If the error occurs in a third party dll, make sure to turn off Debugging->"Enable Just My Code" in Options in Visual Studio.
  • Download and install Red Gate's Reflector if it fails outside your code and you dont have the source for it. Reflector will "extract" out the code of the DLL and show you exactly the line it fails (or so I believe it does).

When you get an error saying "was not handled in user code" it means an Exception was thrown and not handled by a try/catch by you. I have a finger on the async method you have there.

If I ever play around with threads, i ALWAYS have a try/catch around all my code within the threaded code. I recommend adding a try/catch in the AppToDevice() method. Also add it for all your Form events. Show a message of error to the user or handle it and hide the error from the user.

Check these:
Best Practice for Exception Handling in a Windows Forms Application?
Exception handling in threads

Community
  • 1
  • 1
Wolf5
  • 16,600
  • 12
  • 59
  • 58
  • I did break when this error happened. It looks like the problem is: dataWriter.WriteByte(command); dataWriter and socket are both null, but I don't know why. command is 1 as I entered. – user3266591 Feb 27 '14 at 13:29
  • It means that the dataWriter = new () never happened. Break you code and see that the code enters connect() and if so that the socket actually is not null. And unless you feel you are good with "async" commands. Try writing the code without those. I put the use of those as stuff for the more advanced programmer. – Wolf5 Feb 27 '14 at 14:11