Solved

Object reference not set

Posted on 2009-05-06
8
423 Views
Last Modified: 2013-11-26
Im trying to read a COM port to see if something has come across itI get an error on this line of code:

btnDiscover.Invoke(New myDelegate(AddressOf UpdateGrid), New Object() {})

saying that object reference not set to an instance of an object?
Private Sub DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialCOMDiscover.DataReceived

        btnDiscover.Invoke(New myDelegate(AddressOf UpdateGrid), New Object() {})

    End Sub

    'This sub will read the COMport and populate the Discovery Grid to list all active Wireless Gauge in Range.

    Public Sub UpdateGrid()
 

        tempArray = strDataCOM1.Split(New Char() {Chr(13)}, StringSplitOptions.RemoveEmptyEntries)

        If tempArray.Length = 0 Then

            Exit Sub

        ElseIf tempArray.Length < 10 Then

            Exit Sub

        ElseIf GageID_Discovery = False Then

            Dim String1 As String = strDataCOM1

            GageID = String1.Substring(String1.IndexOf("L0"), String1.Substring(String1.IndexOf("L0")).IndexOf(" "))

            GageID = GageID.Replace(vbCrLf, vbTab).Replace(Chr(26), "").Replace(Chr(12), "").Replace(Chr(13), "")

            GageID_Discovery = True

            serialCOMDiscover.DiscardInBuffer()

            Me.btnDiscover.Enabled = True

            Me.GridSpread.Enabled = True
 

        Else

            Me.tmrDiscover.Enabled = False

            Me.GridSpread.ActiveSheet.SetValue(0, 0, tempArray(3))

            Me.GridSpread.ActiveSheet.SetValue(0, 2, tempArray(4))

            Me.GridSpread.ActiveSheet.SetValue(0, 1, tempArray(5))

            Me.GridSpread.ActiveSheet.SetValue(0, 3, tempArray(8))

            Me.GridSpread.ActiveSheet.SetValue(0, 4, tempArray(7))

        End If

        Array.Clear(tempArray, 0, tempArray.Length)

    End Sub

Open in new window

0
Comment
Question by:cmdolcet
  • 4
  • 3
8 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24316728
Well...the only object that couldn't possibly bet set is "btnDiscover"...

Is the error by chance happening when the form first loads but before it is displayed?

You could explicitly check with:

    Private Sub DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialCOMDiscover.DataReceived
        If Not IsNothing(btnDiscover) Then
            btnDiscover.Invoke(New myDelegate(AddressOf UpdateGrid), New Object() {})
        End If
    End Sub
0
 

Author Comment

by:cmdolcet
ID: 24318644
No I still get the error
 Private Sub btnDiscover_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiscover.Click

        Try

            Me.tmrDiscover.Enabled = True

            ReadOutWirelessInformation()

        Catch ex As Exception

            WirelessDevice.Text = "Wireless Signal: No Gauges in range can be found"

        End Try
 

    End Sub

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24318708
Same line?  Can you post the code for ReadOutWirelessInformation()?
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:cmdolcet
ID: 24318733
Here is that code!
  Private Sub ReadOutWirelessInformation()

        Try

            serialCOMDiscover.Write("<@:L" & GageID & "06<INFO>")

        Catch ex As Exception

            MessageBox.Show("Requested Serial String was incorrectly sent to wireless device")

        End Try

    End Sub

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24318844
Can you post the whole thing?
0
 

Author Comment

by:cmdolcet
ID: 24318871
yes I will
Imports System.IO.Ports

Imports System.Windows.Forms

Imports System.Threading

Imports System.math

Public Class frmSearch

#Region " Form Variables"
 

    Public WirelessCOM1Values As New ArrayList

    Public Delegate Sub myDelegate()

    Public Discover_Press As Boolean = False

    Public GageID_Discovery As Boolean = False

    Public WithEvents serialCOMDiscover As New IO.Ports.SerialPort

    Public B(7) As Byte

    Public output(2) As Byte

#End Region
 

    'Discovers Indicator COM Port

#Region "Indicator COM Port Discovery"

    'API Declarations

    Public Declare Function CreateFile Lib "kernel32.dll" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As SECURITY_ATTRIBUTES, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long

    Public Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long

    Public Structure SECURITY_ATTRIBUTES

        Dim nLength As Long

        Dim lpSecurityDescriptor As Long

        Dim bInheritHandle As Long

    End Structure

    'API constants

    Public Const FILE_SHARE_READ = &H1

    Public Const FILE_SHARE_WRITE = &H2

    Public Const OPEN_EXISTING = 3

    Public Const FILE_ATTRIBUTE_NORMAL = &H80

    'Return TRUE if the COM exists, FALSE if the COM does not exist

    Public Function COMAvailable(ByVal COMNum As Integer) As Boolean

        Dim hCOM As Long

        Dim ret As Long

        Dim sec As SECURITY_ATTRIBUTES
 

        'try to open the COM port

        hCOM = CreateFile("COM" & COMNum & "", 0, FILE_SHARE_READ + FILE_SHARE_WRITE, sec, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)

        If hCOM = -1 Then

            COMAvailable = False

        Else

            COMAvailable = True

            'close the COM port

            ret = CloseHandle(hCOM)

        End If

    End Function

    Public Sub DiscoverIndicatorCOMPort()

        Dim result As MsgBoxResult

        Dim strMessage As String

        ActiveCOM.Clear()

        Try

            Dim myWMIClassSearcher As New Management.ManagementObjectSearcher("root\cimv2", "SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%(COM%'") 'Get all Serial Ports

            Dim myPorts As Management.ManagementObjectCollection = myWMIClassSearcher.Get()

            'Cycle throug all COM ports on local PC

            For Each myPort As Management.ManagementObject In myPorts

                If myPort.GetPropertyValue("Name") = "Communications Port (COM1)" Then
 

                End If
 

                IndicatorCOMPort = myPort.GetPropertyValue("Name")

                Dim myStrings()

                myStrings = Strings.Split(IndicatorCOMPort)

                IndicatorCOMPort = myStrings(3).Trim("("c, ")"c, Chr(34))

                IndicatorCOMPort = IndicatorCOMPort.Trim("C", "O", "M")

                ActiveCOM.Add(IndicatorCOMPort)

                'Exit For

            Next

        Catch ex As Exception

            strMessage = "No COM Ports Discovered:" & vbCrLf & vbCrLf & "Select [ Yes ] rediscover COM Ports:" & vbCrLf & vbCrLf & "Select [ No ] To exit" & vbCrLf

            result = MsgBox(strMessage, MsgBoxStyle.Information + MsgBoxStyle.YesNo, "")

            If result = MsgBoxResult.Yes Then

                DiscoverIndicatorCOMPort()

            ElseIf result = MsgBoxResult.No Then

                Me.Close()

            End If

        End Try

    End Sub
 
 

#End Region
 

    'Currently this is hard set to COM 1 and Baudrate is at 9600

#Region " COM Port Setup"

    Public Sub SerialPortCOMControl()

        Try

            If IsNothing(serialCOMDiscover) Then

                serialCOMDiscover = New IO.Ports.SerialPort

            End If

            'set the properties of the com port

            serialCOMDiscover.PortName = "COM1"

            serialCOMDiscover.BaudRate = 57600

            serialCOMDiscover.Parity = Parity.None

            serialCOMDiscover.DataBits = 8

            serialCOMDiscover.RtsEnable = True

            serialCOMDiscover.Open()

            SerialPortStatus.Text = "Connection Status: " & " COM Port Enabled"

            ConnectionStatus.BackColor = System.Drawing.Color.LightGreen

        Catch ex As Exception

            SerialPortStatus.Text = "Connection Status: " & " COM Port NOT Enabled"

            ConnectionStatus.BackColor = System.Drawing.Color.Red

        End Try

    End Sub

#End Region
 

    'Form timers

#Region "Form Timers"

    'This trmDiscover Timer will only fire if a gauge has not been dsicovered in 5 secs.

    Private Sub tmrDiscover_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrDiscover.Tick

        Me.tmrDiscover.Enabled = False

        ' Dim msg As MessageBoxButtons

        MessageBox.Show("No Gauges could be found.!", "Wireless Signal", MessageBoxButtons.OK)

        WirelessDevice.Text = "Wireless Signal: No Gauges in range can be found"

        ConnectionStatus.BackColor = System.Drawing.Color.Red

        SerialPortStatus.Text = "Connection Status: " & " COM Port Enabled"

        ConnectionStatus.BackColor = System.Drawing.Color.LightGreen

    End Sub

#End Region
 

    Private Sub btnDiscover_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiscover.Click

        Try

            Me.tmrDiscover.Enabled = True

            ReadOutWirelessInformation()

        Catch ex As Exception

            WirelessDevice.Text = "Wireless Signal: No Gauges in range can be found"

        End Try
 

    End Sub

    Private Sub frmSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Dim dlgSetupMode As New dlgSetModeNotice

        'dlgSetupMode.TopMost = True

        'dlgSetupMode.Focus()

        ' Me.Enabled = False

        'dlgSetupMode.Show()

        'DiscoverIndicatorCOMPort()

        SerialPortCOMControl()

        LoadPageVariables()

        serialCOMDiscover.Write("<RS")

        Me.GridSpread.Enabled = False

    End Sub

    'Is the initial command after the Discovery button is pressed that will request the INFO

    'from the Wireless Device

    Private Sub ReadOutWirelessInformation()

        Try

            serialCOMDiscover.Write("<@:L" & GageID & "06<INFO>")

        Catch ex As Exception

            MessageBox.Show("Requested Serial String was incorrectly sent to wireless device")

        End Try

    End Sub

    Private Sub DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialCOMDiscover.DataReceived

        If Not IsNothing(btnDiscover) Then

            btnDiscover.Invoke(New myDelegate(AddressOf UpdateGrid), New Object() {})

        End If

    End Sub

    'This sub will read the COMport and populate the Discovery Grid to list all active Wireless Gauge in Range.

    Public Sub UpdateGrid()
 

        tempArray = strDataCOM1.Split(New Char() {Chr(13)}, StringSplitOptions.RemoveEmptyEntries)

        If tempArray.Length = 0 Then

            Exit Sub

        ElseIf tempArray.Length < 10 Then

            Exit Sub

        ElseIf GageID_Discovery = False Then

            Dim String1 As String = strDataCOM1

            GageID = String1.Substring(String1.IndexOf("L0"), String1.Substring(String1.IndexOf("L0")).IndexOf(" "))

            GageID = GageID.Replace(vbCrLf, vbTab).Replace(Chr(26), "").Replace(Chr(12), "").Replace(Chr(13), "")

            GageID_Discovery = True

            serialCOMDiscover.DiscardInBuffer()

            Me.btnDiscover.Enabled = True

            Me.GridSpread.Enabled = True
 

        Else

            Me.tmrDiscover.Enabled = False

            Me.GridSpread.ActiveSheet.SetValue(0, 0, tempArray(3))

            Me.GridSpread.ActiveSheet.SetValue(0, 2, tempArray(4))

            Me.GridSpread.ActiveSheet.SetValue(0, 1, tempArray(5))

            Me.GridSpread.ActiveSheet.SetValue(0, 3, tempArray(8))

            Me.GridSpread.ActiveSheet.SetValue(0, 4, tempArray(7))

        End If

        Array.Clear(tempArray, 0, tempArray.Length)

    End Sub

    Private Sub GridSpread_CellDoubleClick(ByVal sender As Object, ByVal e As FarPoint.Win.Spread.CellClickEventArgs) Handles GridSpread.CellDoubleClick

        Me.Hide()

        serialCOMDiscover.Close()

        Dim frmGaugeInfo As New Form1

        frmGaugeInfo.Show()

    End Sub

    Private Sub LoadPageVariables()

        Me.lblSoftwareVersion.Text = Software_Version

        Me.lblFirmwareVersion.Text = "Version 3.2.0"

        Me.lblCOMPort.Text = serialCOMDiscover.PortName

        Me.lblBaudRate.Text = serialCOMDiscover.BaudRate

    End Sub

    Private Sub DiscoverModeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DiscoverModeToolStripMenuItem.Click

        serialCOMDiscover.Write("<RS")

    End Sub

    Private Sub EndDiscoverToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EndDiscoverToolStripMenuItem.Click

        serialCOMDiscover.Write("<RN")

    End Sub

    Private Sub ResetWirelessReceiverToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResetWirelessReceiverToolStripMenuItem.Click

        serialCOMDiscover.Write("<RN")

        serialCOMDiscover.Write("<RS")

    End Sub

End Class

Open in new window

0
 

Accepted Solution

by:
cmdolcet earned 0 total points
ID: 24355017
Idle_Mind, modus_operandi, I was able to find my answer as to why it was throwing the error. When I put the readline command in It didn;t throw the error again.
Can this be closed now?

Thanks
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now