A first chance exception of type 'System.NullReferenceException' occurred in sss.exe

For the code here, I'm getting  think a null value returned from the recorset or my code for the select is wrong...I'm not sure how to resolve:

  Public Sub MoveFiles(ByVal sFolder As String)
        Dim files() As String = System.IO.Directory.GetFiles(sFolder, "*.TXT")
        For Each sFile As String In files

            Dim sFileName As String = System.IO.Path.GetFileName(sFile)

            Dim sPart As String = sFileName.Substring(0, 4)

            Dim sNewFolder As String = GetFolder(sPart)


            System.IO.File.Move(sFile, System.IO.Path.Combine(sNewFolder, sFileName))

        Next

    End Sub

    Private Function GetFolder(ByVal PartnerID As String) As String
        Dim result As String = ""
        Dim objConn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("MYConn"))
        Dim objComm As New SqlCommand("SELECT FTPFilePath FROM mnt_FileName_Map WHERE PartnerID = @PartnerID")

        objComm.Parameters.Add(New SqlParameter("@PartnerID", PartnerID))

        Try
            objComm.Connection.Open()
            result = objComm.ExecuteScalar()

        Catch ex As Exception
            ex.Message.ToString()
        Finally
            If objConn.State = ConnectionState.Open Then objConn.Close()

        End Try

        Return result
    End Function


ERROR: A first chance exception of type 'System.NullReferenceException' occurred in sss.exe
LVL 1
dba123Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Raju SrivatsavayeSoftware EngineerCommented:
Wheres the error pointing to anyway??
0
dba123Author Commented:
Ok, I found out it's pointing here:

System.IO.File.Move(sFile, System.IO.Path.Combine(sNewFolder, sFileName))

True error really is: Object Reference not set to an instance of an object
0
dba123Author Commented:
I'm assuming it's a problem with my GetFolder but not sure what
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Raju SrivatsavayeSoftware EngineerCommented:
Make these two changes and see if that makes any difference,

Dim objComm As New SqlCommand("SELECT FTPFilePath FROM mnt_FileName_Map WHERE PartnerID = @PartnerID",objConn)


and while opening:objConn.Open() instead of objComm.Connection.Open()
Might not be a mistake but lets do it the traditional way..Bcoz honestly i never used that
0
dba123Author Commented:
ok, sNewFolder is returning NULL
0
Raju SrivatsavayeSoftware EngineerCommented:
sNewFolder ???you might wanna post some more code here
0
Raju SrivatsavayeSoftware EngineerCommented:
ok got it ...sorry
0
dba123Author Commented:
Here's the whole thing:

Imports System.IO
Imports System
Imports System.Configuration
Imports System.Data
Imports System.Text
Imports System.Data.SqlClient

Module Module1

    Sub Main()

        Dim f As New Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.None)
        f.AllLocalFiles = Security.Permissions.FileIOPermissionAccess.Read

        Dim file As New IO.FileInfo("\\sss\f$\inetpub\wwwroot\sss\ssis\maintenance\sss\phase2\msss_input\sss_input.mnt")

        Dim filefs As New IO.FileStream(file.FullName, IO.FileMode.Open)
        Dim reader As New IO.StreamReader(filefs)
        Dim counter As Integer = 0

        Dim CurrentFS As IO.FileStream
        Dim CurrentWriter As IO.StreamWriter

        While Not reader.Peek < 0
            Dim Line As String = reader.ReadLine
            If IsNumeric(Line.Substring(0, 1)) Then
                Dim Parts() As String = Line.Split(" "c)
                If Parts(0).Length = 8 Then
                    counter += 1
                    If Not CurrentWriter Is Nothing Then CurrentWriter.Flush() : CurrentWriter.Close()
                    CurrentFS = New IO.FileStream(IO.Path.Combine(IO.Path.GetDirectoryName("\\sss\f$\inetpub\wwwroot\sss\ssis\maintenance\sss\phase2\sss_output\"), Line.Substring(59, 4) & "[" & counter.ToString & "]" & Now.ToString("MM-dd-yyyy") & IO.Path.GetExtension(file.FullName)), IO.FileMode.Create)
                    CurrentWriter = New IO.StreamWriter(CurrentFS)
                End If

                If Not CurrentWriter Is Nothing Then
                    CurrentWriter.WriteLine(Line)
                End If

            End If
        End While

        If Not CurrentWriter Is Nothing Then CurrentWriter.Flush() : CurrentWriter.Close()
        'Console.Read()

        MoveFiles("\\sss\f$\inetpub\wwwroot\sss\ssis\maintenance\sss\phase2\sss_output\")

    End Sub


    Public Sub MoveFiles(ByVal sFolder As String)
        Dim files() As String = System.IO.Directory.GetFiles(sFolder, "*.mnt")
        For Each sFile As String In files

            Dim sFileName As String = System.IO.Path.GetFileName(sFile)

            Dim sPart As String = sFileName.Substring(0, 4)

            Dim sNewFolder As String = GetFolder(sPart)

            MsgBox("sFileName:" & sFileName & "sNewFolder:" & sNewFolder)

            System.IO.File.Move(sFile, System.IO.Path.Combine(sNewFolder, sFileName))

        Next

    End Sub

    Private Function GetFolder(ByVal PartnerID As String) As String
        'MsgBox(PartnerID)
        Dim result As String = ""
        Dim objConn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("MYConn"))
        Dim objComm As New SqlCommand("SELECT FTPFilePath FROM mnt_FileName_Map WHERE PartnerID = @partnerID", objConn)

        objComm.Parameters.Add(New SqlParameter("@PartnerID", PartnerID))

        Try
            objComm.Connection.Open()
            result = objComm.ExecuteScalar()

        Catch ex As Exception
            MsgBox("Error:" & vbCrLf & ex.Message)
        Finally
            If objConn.State = ConnectionState.Open Then objConn.Close()

        End Try

        Return result
    End Function


End Module

0
dba123Author Commented:
so there's somethign not right in my GetFolder function but not sure what it is...preferably I'd like to reference a stored proc anyway rather than an inline select
0
dba123Author Commented:
The Lookup table definitely has valid lookup values...I'm sure something is malformed but can't pinpoint it in my code
0
Raju SrivatsavayeSoftware EngineerCommented:
I am sorry...did u check what objcomm.executescalar is returning...!!!!!
0
dba123Author Commented:
Ok, it's not getting there (to the result) because now the error is saying the ConnectionString property has not been initialized.
0
dba123Author Commented:
It's talking about ObjConn not being initialized
0
dba123Author Commented:
If I put in objConn.Open(), I still get the message saying that objConn hasn't been initialized.
0
Raju SrivatsavayeSoftware EngineerCommented:
change this

system.Configuration.ConfigurationSettings.AppSettings("MYConn") and see..
0
dba123Author Commented:
Warning      2      'Public Shared ReadOnly Property AppSettings() As System.Collections.Specialized.NameValueCollection' is obsolete: 'This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'

srivatsavaye , I'm coding in .NET 2.0, you can't use that anymore...
0
dba123Author Commented:
remember, this is a console application, not asp.net so you must use System.Configuration.ConfigurationManager.AppSettings("MYConn")
0
dba123Author Commented:
my connection string is in a app.config file, not web.config
0
Raju SrivatsavayeSoftware EngineerCommented:
The way you wrote is the way we write in web applications except for the appsettings...
Did you try that..anyway..bcoz I tried to type in configuration.configurationmanager..it did not have that configurationmanager..so just try it..
0
dba123Author Commented:
I did try it, it errors out, I just pasted the error did you see it:

Warning     2     'Public Shared ReadOnly Property AppSettings() As System.Collections.Specialized.NameValueCollection' is obsolete: 'This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'
0
dba123Author Commented:
this guy had a similar problem...but of course no resolution here:

http://www.dotnetjunkies.com/Forums/ShowPost.aspx?PostID=2769
0
Raju SrivatsavayeSoftware EngineerCommented:
Sorry...Lets debug carefully..

Do this..

dim conString as string=System.Configuration.ConfigurationManager.AppSettings("MyConn")

then
 Dim objConn As SqlConnection = New SqlConnection(constring)

just put a breakpoint and see if you are retrieving the connectionstring

Hope you did this right:appSettings is case sensitive in your app.config file..
0
dba123Author Commented:
Here's the app.config (I covered up our servername, etc. of course):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for My.Application.Log -->
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application Event Log -->
                    <!--<add name="EventLog"/>-->
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                 initializeData="FileLogWriter"/>
            <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
            <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
        </sharedListeners>
    </system.diagnostics>

  <connectionStrings>
    <add name="HEDIConn"
         connectionString="Data Source=myservername;Initial Catalog=mydbname; integrated security=SSPI;persist security info=False; Trusted_Connection=Yes"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
 
</configuration>
0
dba123Author Commented:
If I set breakpoints, how can I see the value being returned without using like a msgbox?  I look at the compiler but it tells me nothing interesting
0
dba123Author Commented:
If I run your code, it's still saying the ConnectionString is not initialized

    Private Function GetFolder(ByVal PartnerID As String) As String
        'MsgBox(PartnerID)
        Dim result As String = ""
        Dim conString As String = System.Configuration.ConfigurationManager.AppSettings("MyConn")
        Dim objConn As SqlConnection = New SqlConnection(conString)
        Dim objComm As New SqlCommand("SELECT FTPFilePath FROM mnt_FileName_Map WHERE PartnerID = @partnerID", objConn)

        objComm.Parameters.Add(New SqlParameter("@PartnerID", PartnerID))

        Try
            objComm.Connection.Open()
            result = objComm.ExecuteScalar()
            MsgBox("Result:" & result)
        Catch ex As Exception
            MsgBox("Error:" & vbCrLf & ex.Message)
        Finally
            If objConn.State = ConnectionState.Open Then objConn.Close()
            objConn.Close()
        End Try

        Return result
    End Function
0
dba123Author Commented:
defining the connection string right into the module seems to work, however, I stick to best practices, which allows me to manage the connection string in one file (app.config) so I'd rather not have to do it this way:

        Dim conString As String = "Data Source=server;Initial Catalog=dbname; integrated security=SSPI;persist security info=False; Trusted_Connection=Yes"
        Dim objConn As SqlConnection = New SqlConnection(conString)
0
dba123Author Commented:
I want to figure this out, why can't I do it the way we've been trying?  what's the misconnection with the app.config file?
0
Raju SrivatsavayeSoftware EngineerCommented:
Look you havent initialized your connectiostring in the appsettings.You did in the ConnectionStrings property..Try doing this

<appSettings>

    <add name="MyConn" value="Your ConnectionString here"/>
  </appSettings>

Then try..You will have to get it this time.

Yes please put a message box there and seee if you are retrieving the connection string after making this change
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dba123Author Commented:
Thanks, I'll assume that's it, if not I'll post a new thread but you're right, that is probably the problem, it's missing!
0
Raju SrivatsavayeSoftware EngineerCommented:
If you see carefully the name of the connectionstring is HEDIConn not MyConn..

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.