Loading DataGridView from another form - vb.net

I have been a long time reader of questions and answers on this site and this is my first question.
I have a Datagridview I want to load from a MySQL database. I can get the code to work if the datagridview is contained in the form I am writing the code in. If I request try and load it onto another form it does not work
The top bit of code works and the latter bit does not.
Public Sub LoadGrid3()
Dim job As String = TextBox10.Text
MySql.AddParam("#job", job)
Try
MySql.ExecQuery("select * from imprint.jobs_commonfields where jobno = #job")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
If MySql.RecordCount > 0 Then DataGridView1.DataSource = MySql.mysqlds.Tables(0)
End Sub
Public Sub LoadGrid3()
Dim job As String = TextBox10.Text
MySql.AddParam("#job", job)
Try
MySql.ExecQuery("select * from imprint.jobs_commonfields where jobno = #job")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
If MySql.RecordCount > 0 Then Form3.job_detail.DataSource = MySql.mysqlds.Tables(0)
End Sub

Related

SSIS Script Task supress onerror

I have a script task which downloads a file using a HTTP connection object. This script task is part of a package which is called by another package. Sometimes the connection cannot be established. In these instances I want to retry the connection a number of times before finally raising an error if the connection attempts fail.
I tried to implement this. It appeared to work and the task does not fail. However an OnError event is still propagated every time an exception happens in the script task even though the script task doesn't fail. The fail occurs once control is passed from the child package back to the parent package.
Public Sub Main()
Dim tryTimes As Integer = 0
Dim maxTimes As Integer = 4
While (True)
Try
Dim nativeObject As Object = Dts.Connections("HTTP Connection Manager").AcquireConnection(Nothing)
'Create a new HTTP client connection
Dim connection As New HttpClientConnection(nativeObject)
Dim filename As String = Dts.Variables("Working_File").Value
connection.DownloadFile(filename, True)
Dts.TaskResult = ScriptResults.Success
Exit While
Catch ex As Exception
If (tryTimes < maxTimes) Then
tryTimes = tryTimes + 1
Thread.Sleep(30000)
Else
MsgBox(ex.Message)
Dts.TaskResult = ScriptResults.Failure
Throw
End If
End Try
End While
End Sub
I am hoping to get a solution where the OnError event is not called unless the connection attempts fails a certain number of times.
Try writing the same code an Fire a Warning on first 4 trial and on the 5th trial fire an error, i am not sure if it will works:
Public Sub Main()
Dim tryTimes As Integer = 0
Dim maxTimes As Integer = 4
While (True)
Try
Dim nativeObject As Object = Dts.Connections("HTTP Connection Manager").AcquireConnection(Nothing)
'Create a new HTTP client connection
Dim connection As New HttpClientConnection(nativeObject)
Dim filename As String = Dts.Variables("Working_File").Value
connection.DownloadFile(filename, True)
Dts.TaskResult = ScriptResults.Success
Exit While
Catch ex As Exception
If (tryTimes < maxTimes) Then
tryTimes = tryTimes + 1
Dts.Events.FireWarning(0, "Error ignored", _
"Retrying in 30 seconds", String.Empty, 0)
Thread.Sleep(30000)
Else
Dts.Events.FireError(-1, "", "Error message: " & ex2.ToString(), "", 0)
Dts.TaskResult = ScriptResults.Failure
End If
End Try
End While
End Sub
Reference
How to suppress OnError event for a specific error in a Script task (SSIS 2005)
You'll want to use a label, outside the try, and a GoTo within your catch
Public Sub Main()
Dim tryTimes As Integer = 0
Dim maxTimes As Integer = 4
RunCode: 'Label here
While (True)
Try
'your code here
Exit While
Catch ex As Exception
If (tryTimes < maxTimes) Then
tryTimes = tryTimes + 1
Thread.Sleep(30000)
GoTo RunCode 'after we catch the exception and eval tryTimes go back and retry
Else
'MsgBox(ex.Message)
Dts.Events.FireError(-1, "", "Error message: " & ex.ToString(), "", 0)
Dts.TaskResult = ScriptResults.Failure
'Throw
End If
End Try
End While
End Sub

Catch not reached on error

I have main windows form on which i have user control. From there I do some operation related to database. During database process I show user additional windows form so he can see nice circural graphic in meantime. I use task to place mentioned database process and from there if error occurs I want to show error message from try/catch. Unfortunetly MessageBox.Show is not showing up when i do tests - catch is even not reached. Could you help me out what is wrong. I am talking about this line in catch statment:
Catch sqlex As Exception
pic.Invoke(Sub() MessageBox.Show(pic, sqlex.Message))
Here's circural window's form code:
Public Class FrmCircularProgress
Sub New(progressType As DevComponents.DotNetBar.eCircularProgressType)
InitializeComponent()
CircularProgress1.ProgressBarType = progressType
StartCircular()
End Sub
Public Sub StartCircular()
Me.CircularProgress1.IsRunning = True
End Sub
Public Sub StopCircular()
Me.CircularProgress1.IsRunning = False
End Sub
End Class
This is example how i use it with Task:
Dim createArticle As New Artikel
Dim pic As New FrmCircularProgress(eCircularProgressType.Donut)
Dim tsk As Task(Of Boolean) = Task.Factory.StartNew(Of Boolean)(Function()
'--Run lenghty task
Dim resu = False
Try
resu = createArticle.ProcessArticle(_artikelsAndTheirVariationsFinal)
'--Close form once done (on GUI thread)
Catch sqlex As Exception
pic.Invoke(Sub() MessageBox.Show(pic, sqlex.Message))
Finally
pic.Invoke(New Action(Sub() pic.StopCircular()))
pic.Invoke(New Action(Sub() pic.Close()))
End Try
Return resu
End Function)
'--Show the form
pic.ShowDialog()
Task.WaitAll(tsk)
...
And just for you to see example database process in our case ProcessArticle which is returning either true or false
Public Function ProcessArticle(artikel As ArticlesVariations) As Boolean
Dim result = True
Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(System.String)).ToString()
Using connection As New SqlConnection(strcon)
'-- Open generall connection for all the queries
connection.Open()
'-- Make the transaction.
Dim transaction As SqlTransaction
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
Dim newArticleRowId As Integer = 0
Dim articleIndex As Integer = 0
Try
For Each kvp As KeyValuePair(Of Integer, Artikel) In artikel.collection
Dim ckey As Integer = kvp.Key
articleIndex = kvp.Key 'save article key
Dim data As Artikel = kvp.Value
'-- If given article contains images list (artikel_images is a list with pictures associated with article)
If Not IsNothing(artikel.collection(articleIndex).ArtikelImages) Then
For Each img In artikel.collection(articleIndex).ArtikelImages
'--Insert article's images if exists
Using cmd As New SqlCommand("INSERT INTO T_Article_Image (Path, FK_Artikel_ID, Position) VALUES (#Path, #FK_Artikel_ID, #Position)", connection)
cmd.CommandType = CommandType.Text
cmd.Connection = connection
cmd.Transaction = transaction
cmd.Parameters.AddWithValue("#Path", img.Path)
cmd.Parameters.AddWithValue("#FK_Artikel_ID", newArticleRowId)
cmd.Parameters.AddWithValue("#Position", img.Position)
cmd.ExecuteScalar()
End Using
Next
End If
'-- If given article contains articles variations list (artikel_variation_attributes is a list with variations associated with article)
If Not IsNothing(artikel.collection(articleIndex)._artikel_variation_attributes) Then
For Each var In artikel.collection(articleIndex)._artikel_variation_attributes
'--Insert article's images if exists
Using cmd As New SqlCommand("INSERT INTO T_Artikel_T_Variation (FK_Variation_VariationAttribute_ID, FK_Artikel_ID, Position) VALUES (#FK_Variation_VariationAttribute_ID, #FK_Artikel_ID, #Position)", connection)
cmd.CommandType = CommandType.Text
cmd.Connection = connection
cmd.Transaction = transaction
cmd.Parameters.AddWithValue("#FK_Variation_VariationAttribute_ID", New Variation_VariationAttribute(var.FkVariationId, var.FkVariationAttributeId).GetId())
cmd.Parameters.AddWithValue("#FK_Artikel_ID", newArticleRowId)
cmd.Parameters.AddWithValue("#Position", var.Position)
cmd.ExecuteScalar()
End Using
Next
End If
Next
transaction.Commit()
Catch ex As Exception
result = False
'-- Roll the transaction back.
Try
transaction.Rollback()
Catch ex2 As Exception
result = False
End Try
End Try
End Using
Return result
End Function
I would not expect your catch to be reached. In your ProcessArticle function you have another Try .. Catch If there is an error in the SQL operation, this is where it will be caught. You then return false! So the calling routine does not catch the error, because it has already been handled gracefully. If you want to catch the error in your calling routine, then you will need to Raise an error from your catch in the ProcessArticle function.
You could change your Try Catch in ProcessArticle to
Catch ex As Exception
result = False
'-- Roll the transaction back.
Try
transaction.Rollback()
Catch ex2 As Exception
Throw New Exception("Rollback failed after first exception.", ex2)
End Try
Throw New Exception("Rollback succeeded after exception.", ex)
End Try
Sorry it's some time since I did VB, but I think the syntax is correct. Using this, the calling routine should now catch the Exception (and you will have an Exception with an inner exception). You will need to examine the inner exception to find the cause.

How to do DB backup with VistaDB?

I'm trying to do a XML export of the database with VistaDB.
Unfortuanently, I'm lost.
Here's my code so far:
Dim instance As IVistaDBDatabase
Dim value As System.Int64
SaveFileDialog2.InitialDirectory = "C:\"
Select Case SaveFileDialog2.ShowDialog()
Case Windows.Forms.DialogResult.OK
Try
instance.ExportXml(SaveFileDialog2.FileName, VistaDBXmlWriteMode.All)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Select
All I get is object not set to instance of an object (or something like that).
Can anyone provide so guidance?
I was able to figure it out with help from an old code package.
Here is the proper code:
Dim vdbDatabase As IVistaDBDatabase = Nothing
Dim filenameDB As String = SaveFileDialog2.FileName
Dim filenameXML As String = SaveFileDialog2.FileName
Select Case SaveFileDialog2.ShowDialog()
Case System.Windows.Forms.DialogResult.OK
Try
' Call the method that will open the connection to the database and return an open IVistaDBDatabase object for the database to us
vdbDatabase = DDA.VistaDBEngine.Connections.OpenDDA.OpenDatabase("C:\Ledger.vdb5", VistaDBDatabaseOpenMode.NonexclusiveReadOnly, Nothing)
' Clear the XML Transfer List - this is the list used by the Import/Export methods
vdbDatabase.ClearXmlTransferList()
' Loop through the tables in the database and add them to the XmlTransferList
For Each tableName As String In vdbDatabase.GetTableNames()
vdbDatabase.AddToXmlTransferList(tableName)
Next
' Call the ExportXML method with the name of the XML file and the WriteMode value indicating what to Export
vdbDatabase.ExportXml(filenameXML, VistaDBXmlWriteMode.All)
' If the database is open - close it
If Not vdbDatabase.IsClosed Then
vdbDatabase.Close()
End If
MsgBox("Database Export complete.", MsgBoxStyle.Information)
Catch ex As Exception
WriteErrorEvent("Error exporting Database in addin", ex)
MsgBox("An error occured attempting to export the Database. Error Message:" & vbCrLf & vbCrLf & ex.ToString, MsgBoxStyle.Exclamation)
Finally
' If we have a vdbDatabase object
If Not (vdbDatabase Is Nothing) Then
' If it is open, close it
If Not vdbDatabase.IsClosed Then
vdbDatabase.Close()
End If
' Dispose of the object
vdbDatabase.Dispose()
End If
End Try
End Select
A Little late but i've made a small change to your code, so you can see the exact time of your backup.
Dim vdbDatabase As IVistaDBDatabase = Nothing
Dim filenamedb As String = vdbDatabase
Dim filenameXML As String = "MyDataBaseName_" + Now.ToString("dd-MM-yyyy_hh-mm-ss") + ".Xml"
Dim path As String
path = System.IO.Path.GetFullPath(filenameXML)
Try
vdbDatabase = DDA.VistaDBEngine.Connections.OpenDDA.OpenDatabase("DataDirectory|MyDataBase.vdb5", VistaDBDatabaseOpenMode.NonexclusiveReadOnly, Nothing)
vdbDatabase.ClearXmlTransferList()
For Each tableName As String In vdbDatabase.GetTableNames()
vdbDatabase.AddToXmlTransferList(tableName)
Next
vdbDatabase.ExportXml(filenameXML, VistaDBXmlWriteMode.All)
If Not vdbDatabase.IsClosed Then
vdbDatabase.Close()
End If
MsgBox("Backup is in " + path, MsgBoxStyle.Information)
Catch ex As Exception
MsgBox("An error occured attempting to export the Database. Error Message:" & vbCrLf & vbCrLf & ex.ToString, MsgBoxStyle.Exclamation)
Finally
If Not (vdbDatabase Is Nothing) Then
If Not vdbDatabase.IsClosed Then
vdbDatabase.Close()
End If
vdbDatabase.Dispose()
End If
End Try

IndexOutOfRangeException was unhandled VBNET

I have a form that retrieves the CurrentYearyear_now and NextYearyear_next from the database. It gives me the error 'IndexOutOfRangeException was unhandled' bcoz I think there is no row to be retrieved. And I wanted to do is, even though there's no data from the table, I can still load the forms and give me a null value to be displayed. I tried everything I know to make it work but I cant resolve the problem. Is there anyway to recode this.
Sub LoadSchoolYear()
Dim conn1 As New MySqlConnection("server=localhost; userid=root; password=root; database=uecp_cens")
Dim dAdapter1 As New MySqlDataAdapter("SELECT year_now, year_next FROM uecp_cens.tblschoolyear", conn1)
Dim dTable1 As New DataSet
Try
dAdapter1.Fill(dTable1, "uecp_cens")
lblYearNow.Text = dTable1.Tables("uecp_cens").Rows(0).Item(0).ToString
lblYearNext.Text = dTable1.Tables("uecp_cens").Rows(0).Item(1).ToString
Catch ex As MySqlException
MsgBox(ex.Message)
Finally
conn1.Dispose()
End Try
End Sub
Any help is appreciated.
If there is no row in the table as you've mentioned you get that error. So check Rows.Count:
Dim yearNow As String = Nothing
Dim yearNext As String = Nothing
If dTable1.Tables("uecp_cens").Rows.Count > 0 Then
yearNow = dTable1.Tables("uecp_cens").Rows(0).Item(0).ToString()
yearNext = dTable1.Tables("uecp_cens").Rows(0).Item(1).ToString()
End If
lblYearNow.Text = yearNow
lblYearNext.Text = yearNext
If instead the field is NULL in the DB it is DBNull.Value and you get an exception if you use Rows(0).Item(0).ToString(). Then use DataRow.IsNull to check it:
If dTable1.Tables("uecp_cens").Rows.Count > 0 Then
Dim row = dTable1.Tables("uecp_cens").Rows(0)
yearNow = If(row.IsNull(0), Nothing, row.Item(0).ToString())
yearNext = If(row.IsNull(1), Nothing, row.Item(1).ToString())
End If

Async Task - read database data, got: 'System.Data.SqlClient.SqlException' The query processor could not start the necessary thread resources

I'm creating Async Tasks in a loop, The task has to read data from sql database.
as the source data size gets bigger, I got this error:
The query processor could not start the necessary thread resources for parallel query execution.
here is my code:
For Each objLocDataTable In pLocationData
If objLocDataTable IsNot Nothing AndAlso objLocDataTable.ISVALID Then
listLocationELTTasks.Add(TaskEx.Run(
Async Function() As Task
Dim resTable As System.Data.DataTable = Await mDBUtil.QueryAsync(strQry)
....... 'do calculation works based on the query result
End Function))
END if
Next
Public Async Function QueryAsync(ByVal strSqlQuery As String) As Task(Of DataTable)
Dim returnDataTable As DataTable = Nothing
Dim nTriedNumber As Integer = 0, nMaxTryNumber = 10
Dim bStop As Boolean = False
While (Not bStop)
Try
Using dbConnection As New SqlConnection(mStrConn)
Using dbComm As New SqlCommand(strSqlQuery, dbConnection)
Await dbConnection.OpenAsync()
dbComm.CommandType = CommandType.Text
Dim readerTask As Task(Of SqlDataReader) = Task.Factory.FromAsync(AddressOf dbComm.BeginExecuteReader, AddressOf dbComm.EndExecuteReader, Nothing)
returnDataTable = Await readerTask.ContinueWith(
Function(pervTask)
Dim resultTable As New DataTable()
Dim reader As SqlDataReader = Nothing
Try
reader = pervTask.Result
reader.Read()
resultTable.Load(reader)
bStop = True
Catch ex As Exception
System.Diagnostics.Debug.WriteLine(String.Format("Thread ID [{0}]: nTriedNumber [{1}], QueryAsync error: {2}", Threading.Thread.CurrentThread.ManagedThreadId, nTriedNumber, ex.Message))
Finally
If (reader IsNot Nothing) Then
reader.Close()
End If
If (Not dbConnection.State = ConnectionState.Closed) Then
dbConnection.Close()
End If
End Try
Return resultTable
End Function)
End Using
End Using
Catch ex As Exception
System.Diagnostics.Debug.WriteLine(String.Format("Not datareader error, nTriedNumber [{0}], QueryAsync error: {1}", nTriedNumber, ex.Message))
Finally
'could be shorten as if( returnDataTable Is Nothing or returnDataTable.Rows.Count() = 5) Then
System.Diagnostics.Debug.WriteLine(String.Format("Thread ID [{0}]: QueryAsync is sleeping for 1 sec", Threading.Thread.CurrentThread.ManagedThreadId))
System.Threading.Thread.Sleep(1000)
End If
If (nTriedNumber >= nMaxTryNumber) Then
System.Diagnostics.Debug.WriteLine(String.Format("Thread ID [{0}]: Reach to max try number, failed to retrieve data", Threading.Thread.CurrentThread.ManagedThreadId))
bStop = True
End If
End Try
End While
Return returnDataTable
End Function
As in function QueryAsync, I tried
- close the db connection as quick as possible.
- even sleep for a while
none of them working
Note:
- the sql data source is about 50 million records, I can NOT load it into memory at once before the for loop to do in-memory linq query.
I tried to replace the Task with Parrel.foreach, same result.
what's the efficient way to read data from sql database in task.
It looks like you don't need async IO. Switch to synchronous database calls, and your life becomes very easy:
pLocationData
.AsParallel()
.WithDegreeOfParallelism(8) //choose the number by testing
.ForEach(objLocDataTable => Query(objLocDataTable));
(C# syntax). I've renamed QueryAsync to Query because it should be a good old synchronous method like we have always used it.
This executes your queries with 8 threads concurrently. A fixed amount of threads will not overload the DB.