?
Solved

Problem OccurredObject reference not set to an instance of an object

Posted on 2006-03-23
16
Medium Priority
?
423 Views
Last Modified: 2010-04-23
I am trying to split the function IPlookup in to two separate functions. The splitting of the functions is an attempt to reduce the amount of times the application has to go to the database by populating a datatable and selecting information from it.  This approach was suggested as a performance enhancement in a post I made for suggestions on performance enhancements. Please see the URL below for questions:

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21784599.html

I attempted several different approaches, but am still struggling to make it work.

I’m getting an error “Problem OccurredObject reference not set to an instance of an object.”

Original code:
     
Public Function IPLookup(ByVal DottedIP As String) As String
        Dim lngIP As Long
        Dim strCountry As String
        Dim con As New OleDbConnection
        Dim dtm As DataTableMapping
        Dim da As New OleDbDataAdapter
        Dim cmdSelect As New OleDbCommand
        Dim ds As New DataSet
        Dim dt As DataTable

        lngIP = Dot2LongIP(DottedIP)
        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\resource\master.mdb"
        dtm = da.TableMappings.Add("Table", "Country")
        cmdSelect.CommandText = "SELECT countryname FROM Country WHERE " & lngIP.ToString & " >= ipl1 and " _
                   & lngIP.ToString & "  <= ipl2"

        cmdSelect.Connection = con
        da.SelectCommand = cmdSelect
        da.Fill(ds)
        dt = ds.Tables("Country")
        If dt.Rows.Count = 0 Then
            strCountry = "Not is Database!"
        Else
            strCountry = dt.Rows(0).Item("countryname")
        End If

        Return strCountry
    End Function
End Class

Split code


Partial code (I included this partial code section because I wasn't sure if this was what was causing the error)

If (inFile.Length > 0) Then
            If (outFile.Length > 0) Then
                CountryDatatable() 'I added call to the datatable
                ConvertFiles(inFile, outFile)
                'Wave.Play("C:\resource\sounds\completed.wav")
                MsgBox("File Complete!")
            Else

Here is the modified code:

    Public Function CountryDatatable()
        Dim cmdSelect As New OleDbCommand
        Dim dtm As DataTableMapping
        Dim da As New OleDbDataAdapter
        Dim ds As New DataSet
        Dim dt As New DataTable
        Dim con As New OleDbConnection

        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\resource\master.mdb"
        cmdSelect.CommandText = "SELECT * from Country"
        dtm = da.TableMappings.Add("Table", "Country")
        cmdSelect.Connection = con
        da.SelectCommand = cmdSelect
        da.Fill(ds)
        dt = ds.Tables("Country")

    End Function

    Public Function IPLookup(ByVal DottedIP As String) As String
        Dim lngIP As Long
        Dim strCountry As String
        Dim ds As DataSet
        Dim dt As DataTable

        dt = ds.Tables("Country")
        lngIP = Dot2LongIP(DottedIP)
        Dim sql As String
        Dim foundrows() As DataRow
        sql = lngIP.ToString & ">=ipl1 and " & lngIP.ToString & " <= ipl2"
        foundrows = dt.Select(sql)

        If foundrows.Length = 0 Then
            strCountry = "unknown"

        Else
            strCountry = foundrows(0).Item("countryname")
        End If
        Return strCountry
    End Function


Thank you very much for your time and expertise,
Gr8life
0
Comment
Question by:gr8life
  • 7
  • 5
  • 4
16 Comments
 
LVL 39

Expert Comment

by:appari
ID: 16276933

where are you getting the error?
I think on this line
 dt = ds.Tables("Country")
in IPLookup function?
thats because ds is not yet created.
where are you calling function CountryDatatable()?

i think you are trying to call CountryDatatable() once and prepare the datatable and use it in IPLookup function many times in a loop. if thats the case remove
        Dim ds As DataSet
        Dim dt As DataTable

      dt = ds.Tables("Country") from IPLookup function

and shift Dim dt As New DataTable from CountryDatatable() to module level
and try
0
 
LVL 39

Accepted Solution

by:
appari earned 1000 total points
ID: 16276936
your modified code should look something like this

        Dim dt As DataTable

Public Function CountryDatatable()
        Dim cmdSelect As New OleDbCommand
        Dim dtm As DataTableMapping
        Dim da As New OleDbDataAdapter
        Dim ds As New DataSet

        Dim con As New OleDbConnection

        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\resource\master.mdb"
        cmdSelect.CommandText = "SELECT * from Country"
        dtm = da.TableMappings.Add("Table", "Country")
        cmdSelect.Connection = con
        da.SelectCommand = cmdSelect
        da.Fill(ds)
        dt = ds.Tables("Country")

    End Function

    Public Function IPLookup(ByVal DottedIP As String) As String
        Dim lngIP As Long
        Dim strCountry As String

        lngIP = Dot2LongIP(DottedIP)
        Dim sql As String
        Dim foundrows() As DataRow
        sql = lngIP.ToString & ">=ipl1 and " & lngIP.ToString & " <= ipl2"
        foundrows = dt.Select(sql)

        If foundrows.Length = 0 Then
            strCountry = "unknown"

        Else
            strCountry = foundrows(0).Item("countryname")
        End If
        Return strCountry
    End Function
0
 
LVL 34

Assisted Solution

by:Brian Crowe
Brian Crowe earned 1000 total points
ID: 16276976
within function IPLookup there is no table "Country" because that table is defined within the scope of the CountryDataTable function.  You will need to declare the dataset with class-level scope.

private ds as new dataset

public sub CountryDatatable() 'I'm surprised this compiles since a function must return a value
        Dim cmdSelect As New OleDbCommand
        Dim dtm As DataTableMapping
        Dim da As New OleDbDataAdapter
        Dim dt As New DataTable
        Dim con As New OleDbConnection

   with da
      .selectcommand = new oledbcommand
      with .selectcommand
         .connection = new oledbconnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\resource\master.mdb")
         .commandtext = "SELECT * from Country"
      end with

      .tablemapping.add("Table", "Country")
      .acceptchangesduringfill = true
   end with

   try
      da.Fill(ds)
   catch ex as exception
      messagebox.show("Unable to load Country data: " + ex.message)
   end try
End sub

Public Function IPLookup(ByVal DottedIP As String) As String
   Dim lngIP As Long
   Dim strCountry As String
   Dim foundroys() as datarow
   Dim sql as string

   lngIP = Dot2LongIP(DottedIP)

   sql = lngIP.ToString & ">=ipl1 and " & lngIP.ToString & " <= ipl2"
   foundrows = ds.tables("Country").Select(sql)

        If foundrows.Length = 0 Then
            strCountry = "unknown"
        Else
            strCountry = foundrows(0).Item("countryname")
        End If
        Return strCountry
    End Function
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:gr8life
ID: 16277073
I'm trying the code solution provided by BriCrowe and I'm getting an underlined error 'tablemapping" is not a member of the 'System.Data.OleDbDataAdapter'
In this row
    .tablemapping.add("Table", "Country")

Any suggestions,
Thank you very much!
Gr8life

0
 

Author Comment

by:gr8life
ID: 16277111
Also appari your are exactly right!
I am trying to call CountryDatatable() once and prepare the datatable and use it in IPLookup function many times in a loop.
Thank you for time,
Gr8life
0
 

Author Comment

by:gr8life
ID: 16277241
Here is the code where the CountryDatatable() is being called.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim inFile As String
        Dim outFile As String
        Dim openFileDialog1 As New OpenFileDialog
        openFileDialog1.InitialDirectory = "c:\resource"
        openFileDialog1.Filter = "txt files (*.txt|*.txt|All files(*.*)|*.*"
        openFileDialog1.FilterIndex = 2
        openFileDialog1.RestoreDirectory = True

        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            inFile = openFileDialog1.FileName
            outFile = Mid(inFile, 1, inFile.LastIndexOf("."))
            outFile += "-out.CSV"
        End If

        If (inFile.Length > 0) Then
            If (outFile.Length > 0) Then

                CountryDatatable() 'Here is where I am calling function

                ConvertFiles(inFile, outFile)
                'Wave.Play("C:\resource\sounds\completed.wav")
                MsgBox("File Complete!")
            Else
                MsgBox("No output file specified!")
            End If
        Else
            MsgBox("No input file specified!")
        End If
    End Sub

Thank you very much,
Gr8life
0
 
LVL 39

Expert Comment

by:appari
ID: 16277300

did you try the code i posted in my second post?
0
 
LVL 34

Expert Comment

by:Brian Crowe
ID: 16277576
i was doing it off the cuff...it should be

.tablemappings.add("Table", "Country")
0
 

Author Comment

by:gr8life
ID: 16279852
I tried both solutions and they both work great.  However I am receiving an error “Problem Occurred Index was outside the bounds of the array” I believe it is because of the way I am calling the CountryDatatable function.  Any suggestions?

Thanks for your time and expertise,
Gr8life
0
 
LVL 34

Expert Comment

by:Brian Crowe
ID: 16279953
can you run through it in debug mode and nail down which line of code is throwing the error?
0
 

Author Comment

by:gr8life
ID: 16280853
here is the output of the debug

'DefaultDomain': Loaded 'c:\windows\microsoft.net\framework\v1.1.4322\mscorlib.dll', No symbols loaded.
'performance testing': Loaded 'C:\Documents and Settings\home\My Documents\Visual Studio Projects\performance testing\bin\performance testing.exe', Symbols loaded.
'performance testing.exe': Loaded 'c:\windows\assembly\gac\system.windows.forms\1.0.5000.0__b77a5c561934e089\system.windows.forms.dll', No symbols loaded.
'performance testing.exe': Loaded 'c:\windows\assembly\gac\system\1.0.5000.0__b77a5c561934e089\system.dll', No symbols loaded.
'performance testing.exe': Loaded 'c:\windows\assembly\gac\system.data\1.0.5000.0__b77a5c561934e089\system.data.dll', No symbols loaded.
'performance testing.exe': Loaded 'c:\windows\assembly\gac\system.xml\1.0.5000.0__b77a5c561934e089\system.xml.dll', No symbols loaded.
'performance testing.exe': Loaded 'c:\windows\assembly\gac\system.drawing\1.0.5000.0__b03f5f7f11d50a3a\system.drawing.dll', No symbols loaded.
'performance testing.exe': Loaded 'c:\windows\assembly\gac\microsoft.visualbasic\7.0.5000.0__b03f5f7f11d50a3a\microsoft.visualbasic.dll', No symbols loaded.
The program '[3776] performance testing.exe' has exited with code 0 (0x0).
0
 
LVL 34

Expert Comment

by:Brian Crowe
ID: 16281520
unfortunately that doesn't help much.  It would be much more useful if you could just step through the code and determine which line is throwing the error.
0
 
LVL 39

Expert Comment

by:appari
ID: 16281681
>>I tried both solutions and they both work great.  
>>However I am receiving an error “Problem Occurred Index was outside the bounds of the array” I believe it is because of the way I am calling the CountryDatatable function.
what does this mean, first statement says it works and next you are saying you are getting error.
just add try catch blocks to catch the exceptions and display proper error as follows

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
try
        Dim inFile As String
        Dim outFile As String
        Dim openFileDialog1 As New OpenFileDialog
        openFileDialog1.InitialDirectory = "c:\resource"
        openFileDialog1.Filter = "txt files (*.txt|*.txt|All files(*.*)|*.*"
        openFileDialog1.FilterIndex = 2
        openFileDialog1.RestoreDirectory = True

        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            inFile = openFileDialog1.FileName
            outFile = Mid(inFile, 1, inFile.LastIndexOf("."))
            outFile += "-out.CSV"
        End If

        If (inFile.Length > 0) Then
            If (outFile.Length > 0) Then

                CountryDatatable() 'Here is where I am calling function

                ConvertFiles(inFile, outFile)
                'Wave.Play("C:\resource\sounds\completed.wav")
                MsgBox("File Complete!")
            Else
                MsgBox("No output file specified!")
            End If
        Else
            MsgBox("No input file specified!")
        End If
catch ex as exception
                MsgBox("Error in Button1_Click :" & ex.description)
end try
    End Sub
0
 
LVL 39

Expert Comment

by:appari
ID: 16281694
sorry chaneg
 MsgBox("Error in Button1_Click :" & ex.description)

to

 MsgBox("Error in Button1_Click :" & ex.message)
0
 

Author Comment

by:gr8life
ID: 16282310
Same problem occurred after I added I the changes provided by appari.  I really appreciate all the help the two have you have given me.  I’m going to close this question and open another one with this problem.  So if you want to continue to help I would greatly appreciate it.  I wish I could have provided more points but the limit is 500.  Thank you very much for all your hard work and expertise.

Thank you for your valuable time,
Gr8life
0
 

Author Comment

by:gr8life
ID: 16282385
The thing that doesn't make the most sense is that the application finishes processing all the IP lookups and then it seams like it wants to continue through the looping.  Then it is almost like it errors because it can't stop the looping any other way.
Gr8life
0

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Watch the video to learn how one can deal with PST file corruption issue with an outstanding Kernel for Outlook PST Repair Tool easily. Using this tool, non-technical users can swiftly perform the repair process to restore their essential data witho…

594 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