Thursday, August 19, 2004 - Posts

.NET and integration with BCP


add following at beginning of the web.config between <configuration> and <system.web> tags

<configSections>
<section name="myapp_bcp_config"
type="System.Configuration.SingleTagSectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>


add following after closing </appSettings> tag

    <myapp_bcp_config
 bcp_Tbl = "destDB..destTable"
 bcp_usr = "myUser"
 bcp_pwd = "myPWD"
 bcp_SRVR = "myServer"
 bcp_format = "myapp_bcp_format.fmt" <!--- or custom stuff like -c -f2 depending on database vendor  --->
     />


load config values

    Sub loadParamConfig()
        Dim valueTable As IDictionary = CType(ConfigurationSettings.GetConfig("myapp_bcp_config"), IDictionary)
        bcp_Tbl = valueTable("bcp_Tbl")
        bcp_usr = valueTable("bcp_usr")
        bcp_pwd = valueTable("bcp_pwd")
        bcp_SRVR = valueTable("bcp_SRVR")
        bcp_format = valueTable("bcp_format")
    End Sub

build command

    Function buildBcpCmd(fileName as string)
        Dim sb As New System.Text.StringBuilder()
        sb = New System.Text.StringBuilder()
 '
        sb.Append(bcp_Tbl & " in " & fileName & " ")
        sb.Append("-U " & bcp_usr & " ")
        sb.Append("-P " & bcp_pwd & " ")
        sb.Append("-S " & bcp_SRVR & " ")
        sb.Append("bcp_format)
        Return sb.ToString
    End Function

run command

 invoke sub below with fowwing line of code
 runcmd("bcp", buildBcpCmd("myfile.txt"))

  
 '
        Sub runcmd(ByVal cmd As String, ByVal exeTxt As String)
            Dim proc As System.Diagnostics.Process
            Dim StartProcessInfo As New System.Diagnostics.ProcessStartInfo()
            proc = New System.Diagnostics.Process()
            StartProcessInfo.UseShellExecute = False
            StartProcessInfo.RedirectStandardOutput = True
            StartProcessInfo.RedirectStandardError = True
            StartProcessInfo.FileName = cmd & ".exe "
            StartProcessInfo.Arguments = exeTxt

            proc.EnableRaisingEvents = True
            Try
                ' start
                proc = proc.Start(StartProcessInfo)
                ' end
                procOut = proc.StandardOutput().ReadToEnd()
                procError = proc.StandardError().ReadToEnd()
  'wait
                proc.WaitForExit()
                ' check exit code
                If Not proc.ExitCode = 0 Then
  ' output message and log
                End If
            Catch cmdExecEx As System.ApplicationException
  ' log stuff
                Throw cmdExecEx
            Finally
             proc.Close()
             proc.Dispose()
             proc = Nothing
    End Try  
        End Sub