SSIS : Exception has been thrown by the target of an invocation - sql-server

I have developed new DTSX package in SSDT and it's executing fine when i run it through the SSDT window.
Same package i am trying to execute from the calling application (.EXE) using below code and it gives
Exception has been thrown by the target of an invocation" error.
Guide me in finding out the root cause and original error message
Then i tried to enable the logging in the DTSX (by enabling all events), still i am getting same error message and it's not pointing exact "task" which is causing the problem. I am unable to find the root cause and the exact error message.
Am i mismacthing any references ? Below is my code
Public Sub Execute()
Dim app As New Microsoft.SqlServer.Dts.Runtime.Application
Dim objPackageResults As Microsoft.SqlServer.Dts.Runtime.DTSExecResult
Try
objPackage = app.LoadPackage(PackageFile, Nothing)
InitPackageParams()
objPackageResults = objPackage.Execute()
Catch ex As System.IO.IOException
MsgBox(ex.InnerException)
blnError = True
End Try
End Sub
Private Sub InitPackageParams()
objPackage.Variables.Item("RegionCode").Value = RegionCode
objPackage.Variables.Item("UName").Value = _userName
objPackage.Variables.Item("Password").Value = (SecureStringHelper.GetStringFromSecureString(_password))
objPackage.Variables.Item("Server").Value = _server
objPackage.Variables.Item("Catalog").Value = _catalog
objPackage.Variables.Item("IsTrusted").Value = (CInt(_isTrusted))
objPackage.Variables.Item("ClearingDate").Value = ClearingDate
objPackage.Variables.Item("Currency").Value = CurrCode
objPackage.Variables.Item("Source").Value = Source
objPackage.Variables.Item("Destination").Value = Destination
End Sub

Related

Try Catch not catching Database connection error

I'm using the following code to open a database connection. If the connection fails for any reason, I get the typical VB error message with all of the details. and my program stops. It does not give me my graceful message and ending.
My try/catch does not work regardless of the connection error (whether it is password related, network related, or sql server related).
I need my program to continue on even if I can't connect to the database.
Public Class SQL_Connection
Public conn As New SqlConnection
Public cmd As New SqlCommand
Public Sub New()
conn.ConnectionString = my_connection_string
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Unable to open database. " + ex.ToString)
End Try
cmd = conn.CreateCommand()
End If
End Sub
End Class
Have a look at this article.
If the program is not run in debug mode, the try catch would do it's thing right away with out stopping the execution.

ApplicationDeployment.IsNetworkDeployed sometimes returning false

A WPF ClickOnce application occasionally returns False when checking IsNetworkDeployed. Usually uninstalling the app and reinstalling it again corrects this.
This is the code used to check the current version
Public Function ReturnCurrentVersion() As String
Try
Dim vBuild As String = "Debug"
If System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed Then
Dim vVersion As Version = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion
Dim vAssembly As Assembly = Assembly.GetExecutingAssembly()
Dim vAssemblyName As AssemblyName = vAssembly.GetName()
vBuild = vVersion.ToString
End If
Return vBuild
Catch ex As Exception
EmailError(ex)
Return "Error"
End Try
End Function
I can see other posts that relate to IsNetworkedDeployed returning false, but none of them appear to be just the odd intermittent issue as in this case.
Perhaps something odd happens during the install and it no longer sees itself as a ClickOnce app - but it would be useful to know why it's doing this.
Thanks

Error in File Temp__.rpt

I made reports using database name Test. SQL Server as backend.
Used DSN. Even configured in ODBC DataSource.
Now I changed my report to mainDb
Some reports worked fine. Others throw error when database name changed.
Error message shown below.
Any solution for this?
I searched on internet, found similar errors based on invalid login or some implementation error. I don't know what exactly my error means.
My small code is posted here.
Private Sub DisplayReport()
Try
Dim report As New Summary
Dim pubdbname as String = "mainDb" '-------This name is correct.'
With report
.DataSourceConnections.Item(0).SetConnection("bonny", Pubdbname, True)
.SetParameterValue("#CompYear", PubYear1)
.SetParameterValue("#CompNo", mComp1)
.SetParameterValue("#accode", PubAcCode)
.SetParameterValue("#Trtype", PubTrTp)
.SetParameterValue("#SBkCd", PubSBkCd)
.SummaryInfo.ReportTitle = "Summary Report" & "_" & Format(CDate(FromDate.Text), "ddMMyyyy") & "-" & Format(CDate(ToDate.Text), "ddMMyyyy")
CReports.CRViewer.ReportSource = report
CReports.Show()
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Thank You.

Detecting wirless network status change in .NET

I have developed winform application using VB.NET. The application is deployed in the machine which is connected to wireless network. The machine is in the car(moving object).
The application has DataGridView loaded with the data get from MSSQL Server(in Remote machine). The data is refreshed for every 5 seconds.
I have used the NetworkAvailabilityChanged event to detect the network status. If the Network is available, then I retrieve the data from the table.
Code:
AddHandler NetworkChange.NetworkAvailabilityChanged, AddressOf NetworkStateChangeHandler
Public Sub NetworkStateChangeHandler(ByVal sender As Object,
ByVal e As NetworkAvailabilityEventArgs)
If e.IsAvailable = True Then
g_bNetworkAlive = True
Else
g_bNetworkAlive = False
End If
End Sub
private Sub GetData()
If g_bNetworkAlive = True
'code to get the data from table
End If
End Sub
Issue:
If the car movers out of the out of the network, the NetworkAvailabilityChanged event is not fired. so it throws the following error for every 5 seconds and application gets crashed.
A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not accessible.
Temporary fix: I have made Ping request to the SQL server machine for every 5 seconds to detect the network status. It affects the application's performance.
Note: If I manually switch off the Wifi, the NetworkAvailabilityChanged event is fired. The issue is only when the car moves out of the network.
Is there any some other feasible solution to detect the wireless network status?
Indeed there is.
Why send http request to some dummy website when you can check if you are connected to wifi or not locally.
Use ManagedWifi APIs, This will eliminate the slowdown you are facing.
//Create object at the beginning of your application
WlanClient wlanClient = new WlanClient();
//You this code to check wifi availability wherever you need
foreach (WlanInterface _interface in wlanClient.Interfaces)
{
If (_interface.CurrentConnection.wlanAssociationAttributes.dot11Ssid.SSID!=null)
{
// You are connected to wifi
}
}
EDIT: In case you you are not finding dll, direct link. Just reference the Dll and Voila! you are done.
Change your code as
Private Sub GetData()
If My.Computer.Network.IsAvailable AndAlso g_bNetworkAlive
' code to get the data from table
End If
End Sub
You also can check if you have an internet connection by using WebRequest like this:
Private Sub GetData()
If HasInternet AndAlso g_bNetworkAlive Then
'code to get the data from table
End If
End Sub
Public Shared Function HasInternet As Boolean
Return Not (HttpGet("http://www.google.com/") = "Error")
End Function
Public Shared Function HttpGet(url As String) As String
Dim request As WebRequest = WebRequest.Create(url)
request.Method = "GET"
Try
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
Catch ex As Exception
Return "Error"
End Try
End Function
And you can check the sql connection by using the following function:
Private Function IsDatabaseConnected() As Boolean
Try
Using sqlConn As New SqlConnection("YourConnectionString")
sqlConn.Open()
Return (sqlConn.State = ConnectionState.Open)
End Using
Catch e1 As SqlException
Return False
Catch e2 As Exception
Return False
End Try
End Function
I would simply use try..catch, so if you get exception, you can know, based on its id, why the code failed, and decide what to do next, and finally you can execute some more code regardless of data being retrieved or not
Private Sub GetData()
Try
'code to get the data from table
Catch ex As Exception
' Show the exception's message.
MessageBox.Show(ex.Message)
' Show the stack trace, which is a list of methods
' that are currently executing.
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
Finally
' This line executes whether or not the exception occurs.
MessageBox.Show("in Finally block")
End Try
End Sub

Database Connection Management in a Multi-Thread Service

I made a windows service that listens to a port(using HttpListner) and accepts XML Repuest and once the request is valid it connects to a database (usually on the same pc) and construct the xml response and sends it back.
So far, Everything is great except when the service accepts two or more requests that require retrieving 100+ records, it crashes. First, I was using just one shared connection to the database, it does crashes, then I changed to multiple connections i.e. when you need something from the database create your connection.
I did some troubleshooting using eventlog to get the exceptions, here are some of the exception I got before crashing:
A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
The ConnectionString property has not been initialized.
ExecuteReader requires an open and available Connection. The connection's current state is connecting.
ExecuteReader requires an open and available Connection. The connection's current state is open.
Invalid attempt to call Read when reader is closed.
Here is a sample of the code I am using:
Private Sub StartLisitng()
MyListener.Start()
Dim result As IAsyncResult
result = MyListener.BeginGetContext(New AsyncCallback(AddressOf ListnerCallback), MyListener)
End Sub
Private Sub ListnerCallback(ByVal result As IAsyncResult)
StartLisitng()
If result.IsCompleted Then
ctx = MyListener.EndGetContext(result)
Dim HandleRequestThread As New Thread(AddressOf New HandleRequest(ctx).RequestProcess)
HandleRequestThread.Start()
End If
End Sub
Public Function RemoteConnect(ByVal DNSBranch As String) As Boolean
Dim IsRemoteConnected As Boolean = False
RemoteConnString = "Data Source = " & DNSBranch & ";Initial Catalog=xxxxx;User ID=xxxxx;Password=xxxxx;Connect Timeout=5;MultipleActiveResultSets=True;"
RemoteConn = New SqlConnection(RemoteConnString)
Try
RemoteConn.Open()
Catch ex As Exception
IsRemoteConnected = False
End Try
If RemoteConn.State = 1 Then
IsRemoteConnected = True
Else
IsRemoteConnected = False
End If
Return IsRemoteConnected
End Function
Public Function RemoteExeComd(ByVal DNSBranch As String, ByVal query As String) As DataSet
Dim MyDataSet As New DataSet
RemoteConnect(DNSBranch)
Comd = New SqlCommand(query, RemoteConn)
Adapter = New SqlDataAdapter(Comd)
If query.StartsWith("Se") Or query.StartsWith("se") Or query.StartsWith("SE") Then
If RemoteConn.State = ConnectionState.Open Then
Try
Adapter.Fill(MyDataSet)
Catch ex As Exception
EventLog.WriteEntry("My Service", "Exception: " & ex.Message.ToString)
End Try
End If
Else
Try
Comd.ExecuteNonQuery()
Catch ex As Exception
EventLog.WriteEntry("My Service", "Exception: " & ex.Message.ToString)
End Try
End If
Comd.Dispose()
Adapter.Dispose()
Return MyDataSet
End Function
I do not have any problems with the listner or parsing the request, I know I have the problem on how i interact with the databse.
Any advice, Thanks for you time.

Resources