SSL/TLS connection not working in webclient after being in background - vb.net

So if I use my program normally no error occurs. But if it is in background for longer time and I use the webclient to visit a web address it immidiately throws could not create a SSL/TLS secure channel error but if I try again the error dissapears. I already set the TLS to 1.2 and expect100continue to false.
Imports System.Net
Imports System.Text.RegularExpressions
Public Class CinemaLinker
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MaximizeBox = False
If Not HaveInternetConnection() Then
MessageBox.Show("Warning: no internet connection!")
End If
ServicePointManager.Expect100Continue = False
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
End Sub
Public Property TextFromBox As String
Public Property StatusLink As String
Private Client As New WebClient
Private GoogleSearch = "****"
Private BingSearch = "*****"
Private AskSearch = "*****"
Private Sub Search() Handles Button1.Click
Cursor.Current = Cursors.WaitCursor
TextFromBox = RichTextBox1.Text
If Button3.Enabled And Button4.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please choose a category!")
Exit Sub
End If
If TextFromBox.Contains("Type movie or tv series name here") Or String.IsNullOrEmpty(TextFromBox) Or String.IsNullOrWhiteSpace(TextFromBox) Then
Cursor.Current = Cursors.[Default]
If Not Button3.Enabled Then
MessageBox.Show("Please type the name of the movie!")
Exit Sub
End If
If Not Button4.Enabled Then
If Not (String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Or RichTextBox3.Text.Contains("E")) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series! Episode number missing!")
Exit Sub
End If
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series! Season and episode numbers missing!")
Exit Sub
End If
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series!")
Exit Sub
End If
End If
If Not Button4.Enabled Then
If String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Or RichTextBox3.Text.Contains("E") Then
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Season and episode numbers missing!")
Exit Sub
End If
Cursor.Current = Cursors.[Default]
MessageBox.Show("Episode number missing!")
Exit Sub
ElseIf String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Season number missing!")
Exit Sub
End If
End If
If Not HaveInternetConnection() Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("No internet connection!")
Exit Sub
End If
Dim ImdbURL As String = getIMDbUrl(TextFromBox)
If Not ImdbURL.Contains("******") And Not Button3.Enabled Then
ImdbURL = getIMDbUrl(TextFromBox) + " movie"
If Not ImdbURL.Contains("***") And Not Button3.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name!")
Exit Sub
End If
End If
If Not ImdbURL.Contains("***") And Not Button4.Enabled Then
ImdbURL = getIMDbUrl(TextFromBox) + " TV series"
If Not ImdbURL.Contains("****") And Not Button4.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name!")
Exit Sub
End If
End If
Dim LinkFinal As String = (GetLink(ImdbURL))
If String.IsNullOrEmpty(LinkFinal) Or String.IsNullOrWhiteSpace(LinkFinal) Then
Cursor.Current = Cursors.[Default]
Exit Sub
End If
Clipboard.SetText(LinkFinal)
MessageBox.Show("Link in clipboard. Paste it into desired browser!")
TextFromBox = String.Empty
StatusLink = "0"
Cursor.Current = Cursors.[Default]
End Sub
Public Function HaveInternetConnection() As Boolean
Dim result As Boolean
Try
result = My.Computer.Network.Ping("www.google.com")
Catch ex As Exception
result = False
End Try
Return result
End Function
Private Function GetIP() As String
Return Client.DownloadString("https://api.ipify.org").ToString()
End Function
Private Function matchAll(ByVal regex As String, ByVal html As String, ByVal Optional i As Integer = 1) As ArrayList
Dim list As ArrayList = New ArrayList()
For Each m As Match In New Regex(regex, RegexOptions.Multiline).Matches(html)
list.Add(m.Groups(i).Value.Trim())
Next
Return list
End Function
Private Function getIMDbUrl(MovieName As String, Optional searchEngine As String = "google") As String
Dim address As String = GoogleSearch + MovieName
If searchEngine.ToLower().Equals("bing") Then
address = BingSearch + MovieName
End If
If searchEngine.ToLower().Equals("ask") Then
address = AskSearch + MovieName
End If
Dim html As String = Client.DownloadString(address)
Dim arrayList As ArrayList = matchAll("<a href=""(*****\d{7}/)"".*?>.*?</a>", html, 1)
If arrayList.Count > 0 Then
Return CStr(arrayList(0))
ElseIf searchEngine.ToLower().Equals("google") Then
Return getIMDbUrl(MovieName, "bing")
ElseIf searchEngine.ToLower().Equals("bing") Then
Return getIMDbUrl(MovieName, "ask")
Else
Return String.Empty
End If
End Function
Private Function GetLink(ImdbURL As String) As Object
Dim ID = ImdbURL.Replace("*****/", "")
ID = ID.Replace("/", "")
Dim result As Object
If StatusLink = "1" Then
Cursor.Current = Cursors.[Default]
Exit Function
ElseIf Not Button4.Enabled Then
Dim SeasonNumber As String = "&s=" + RichTextBox2.Text
Dim EpisodeNumber As String = "&e=" + RichTextBox3.Text
Dim TVSeasonNumber As String = "&tv=1" + SeasonNumber
If Not Client.DownloadString("*****/" & ID).Contains(">Episode Guide<") Then
ImdbURL = getIMDbUrl(TextFromBox + " TV series")
StatusLink = "1"
If String.IsNullOrEmpty(ImdbURL) Or String.IsNullOrWhiteSpace(ImdbURL) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
ID = ImdbURL.Replace("*****", "")
ID = ID.Replace("/", "")
result = (GetLink(ImdbURL))
If String.IsNullOrEmpty(result) Or String.IsNullOrWhiteSpace(result) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
Return result.ToString()
result = String.Empty
Exit Function
End If
End If
Else
Dim address As String = "******" & ID & TVSeasonNumber & "&ip=" & GetIP()
Dim token As String = Client.DownloadString(address)
result = "*****" & ID & TVSeasonNumber & EpisodeNumber & "&ticket=" & token
Return result.ToString
Exit Function
End If
ElseIf Not Button3.Enabled Then
If Client.DownloadString("****" & ID).Contains(">Episode Guide<") Then
ImdbURL = getIMDbUrl(TextFromBox + " movie",)
StatusLink = "1"
If String.IsNullOrEmpty(ImdbURL) Or String.IsNullOrWhiteSpace(ImdbURL) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
ID = ImdbURL.Replace("****", "")
ID = ID.Replace("/", "")
result = (GetLink(ImdbURL))
If String.IsNullOrEmpty(result) Or String.IsNullOrWhiteSpace(result) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
Return result.ToString()
result = String.Empty
Exit Function
End If
End If
Else
Dim address2 As String = "****" & ID & "&ip=" & GetIP()
Dim token2 As String = Client.DownloadString(address2)
result = "****" & ID & "&ticket=" & token2
Return result.ToString
result = String.Empty
Exit Function
End If
End If
#Disable Warning BC42105 ' Function doesn't return a value on all code paths
End Function
Private Sub RichTextBox1_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox1.GotFocus
If RichTextBox1.Text.Contains("Type movie or tv series name here") Then RichTextBox1.Text = String.Empty
End Sub
Private Sub RichTextBox2_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox2.GotFocus
If RichTextBox2.Text.Contains("S") Then RichTextBox2.Text = String.Empty
End Sub
Private Sub RichTextBox3_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox3.GotFocus
If RichTextBox3.Text.Contains("E") Then RichTextBox3.Text = String.Empty
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Button3.Enabled = False
Button4.Enabled = True
RichTextBox1.Enabled = True
RichTextBox2.Enabled = False
RichTextBox3.Enabled = False
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Button4.Enabled = False
Button3.Enabled = True
RichTextBox1.Enabled = True
RichTextBox2.Enabled = True
RichTextBox3.Enabled = True
End Sub
Private Sub RichTextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox2.KeyPress
If Char.IsLetter(e.KeyChar) Then
e.Handled = True
End If
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
End Sub
Private Sub RichTextBox3_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox3.KeyPress
If Char.IsLetter(e.KeyChar) Then
e.Handled = True
End If
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
End Sub
Private Sub RichTextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
If Char.IsUpper(e.KeyChar) Then e.KeyChar = Char.ToLower(e.KeyChar)
End Sub
Private Sub RichTextBox1_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox1.LostFocus
If String.IsNullOrEmpty(RichTextBox1.Text) Or String.IsNullOrWhiteSpace(RichTextBox1.Text) Then
RichTextBox1.Text = "Type movie or tv series name here..."
End If
End Sub
Private Sub RichTextBox2_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox2.LostFocus
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Then
RichTextBox2.Text = "S:"
End If
End Sub
Private Sub RichTextBox3_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox3.LostFocus
If String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Then
RichTextBox3.Text = "E:"
End If
End Sub
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
StatusLink = "0"
End Sub
Private Sub RichTextBox2_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox2.TextChanged
StatusLink = "0"
End Sub
Private Sub RichTextBox3_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox3.TextChanged
StatusLink = "0"
End Sub
End Class
all of the ***** are https website addresses.
Tried switching the Net version to 4.7. Did not help. It is also legal in my country to stream (interior minister dropped a bomb on the DMCA here lol) and this is streaming only. The code is not operational so i had not given you anything dangerous if it is illegal in yours.

Related

How To Fetch Webpage Source simultaneously from thousands of URLs

I am attempting to load thousands of URLs into a list, then simultaneously download the webpage source of all of those URLs. I thought I had a clear understanding of how to accomplish this but it seems that the process goes 1 by 1 (which is painstakingly slow).
Is there a way to make this launch all of these URLs at once, or perhaps more than 1 at a time?
Public Partial Class MainForm
Dim ImportList As New ListBox
Dim URLList As String
Dim X1 As Integer
Dim CurIndex As Integer
Public Sub New()
Me.InitializeComponent()
End Sub
Sub MainFormLoad(sender As Object, e As EventArgs)
Try
Dim lines() As String = IO.File.ReadAllLines("C:\URLFile.txt")
ImportList.Items.AddRange(lines)
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
label1.Text = "File Loaded"
X1 = ImportList.Items.Count
timer1.Enabled = True
If Not backgroundWorker1.IsBusy Then
backgroundWorker1.RunWorkerAsync()
End If
End Try
End Sub
Sub BackgroundWorker1DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
URLList = ""
For Each item As String In ImportList.Items
CheckName(item)
CurIndex = CurIndex + 1
Next
End Sub
Sub BW1_Completed()
timer1.Enabled = False
label1.Text = "Done"
End Sub
Sub CheckName(ByVal CurUrl As String)
Dim RawText As String
Try
RawText = New System.Net.WebClient().DownloadString(CurUrl)
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
If RawText.Contains("404") Then
If URLList = "" Then
URLList = CurUrl
Else
URLList = URLList & vbCrLf & CurUrl
End If
End If
End Try
End Sub
Sub Timer1Tick(sender As Object, e As EventArgs)
label1.Text = CurIndex.ToString & " of " & X1.ToString
If Not URLList = "" Then
textBox1.Text = URLList
End If
End Sub
Sub Button1Click(sender As Object, e As EventArgs)
Clipboard.Clear
Clipboard.SetText(URLList)
End Sub
End Class

Increasing memory usage while scrolling on listview items in vb.net

In a WinForm i have two listview(lvwTemplateCategory) one is listing folders at given directory and if you select folder, other listview(lvwTemplates) shows the files under this directory. I have also one picturebox(picTemplateImage) to show preview screenshot of that file.
While i'm scrolling on that form for 2-3 folders and 9-10 files it's memory usage goes from 62 MB to 120 MB.
I don't know how to manage the memory source also i tried to implement IDisposable but not know where to implement.
P.S. I'm using VS 2017 and calling that WinForm with .Show() method.
Also if you see non-logic codes please let me know.
Option Explicit On
Option Strict On
Imports System.IO
Public Class frmCreateNewModel
Implements IDisposable
Private Sub LoadForm(sender As Object, e As EventArgs) Handles MyBase.Load
Call AddRootDatabase()
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
End Sub
Private Sub ViewLargeIcons(sender As Object, e As EventArgs) Handles cmdViewLargeIcons.Click
lvwTemplateCategory.View = View.LargeIcon
End Sub
Private Sub ViewListIcons(sender As Object, e As EventArgs) Handles cmdViewList.Click
lvwTemplateCategory.View = View.List
End Sub
Private Sub AddRootDatabase()
Try
Dim DirDB As String = My.Settings.str_db__path_tpl
Dim DirInfoDB As New DirectoryInfo(DirDB)
For Each TplDirDB As DirectoryInfo In DirInfoDB.GetDirectories
If Not (TplDirDB.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
cboTemplateDatabase.Items.Add(TplDirDB.Name)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectRootDatabase(sender As Object, e As EventArgs) Handles cboTemplateDatabase.SelectedIndexChanged
Try
lvwTemplateCategory.Items.Clear()
lvwTemplates.Items.Clear()
Dim DirTempRootDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString
Dim DirTempDbInfo As New DirectoryInfo(DirTempRootDir)
Dim lstIcon As Integer
For Each TplCatDir As DirectoryInfo In DirTempDbInfo.GetDirectories
If Not (TplCatDir.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If imgIcons.Images.ContainsKey(TplCatDir.Name) = True Then
lstIcon = imgIcons.Images.IndexOfKey(TplCatDir.Name)
Else
lstIcon = imgIcons.Images.IndexOfKey("default")
End If
lvwTemplateCategory.Items.Add(TplCatDir.Name, lstIcon)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplateCategory(sender As Object, e As EventArgs) Handles lvwTemplateCategory.SelectedIndexChanged
If (CInt(lvwTemplateCategory.SelectedItems.Count.ToString) = 0) Then
Return
End If
Dim DirTempCatDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString
Dim DirTempInfo As New DirectoryInfo(DirTempCatDir)
lvwTemplates.Items.Clear()
Try
For Each TplFile As FileInfo In DirTempInfo.GetFiles
If Not (TplFile.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If Path.GetExtension(TplFile.Name) = ".spck" Or Path.GetExtension(TplFile.Name) = ".buspck" Then
lvwTemplates.Items.Add(TplFile.Name)
End If
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplate(sender As Object, e As EventArgs) Handles lvwTemplates.SelectedIndexChanged
If (CInt(lvwTemplates.SelectedItems.Count.ToString) = 0) Then
cmdQuickConfigure.Enabled = False
Return
End If
cmdQuickConfigure.Enabled = True
Dim TemplFileName As String = Path.GetFileNameWithoutExtension(lvwTemplates.SelectedItems(0).Text.ToString)
Dim DirTempDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString & "\" & TemplFileName
Dim imagePath As String = DirTempDir & ".png"
If File.Exists(imagePath) Then
picTemplateImage.ImageLocation = (imagePath)
picTemplateImage.SizeMode = PictureBoxSizeMode.StretchImage
picTemplateImage.Load()
Else
picTemplateImage.Image = picTemplateImage.ErrorImage
End If
txtModelName.Text = lvwTemplates.SelectedItems(0).Text.ToString
End Sub
Private Sub VisualViewControl(sender As Object, e As EventArgs) Handles cmdVisualControl.Click
If splCreateNewModel.Panel2Collapsed = False Then
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
cmdVisualControl.Text = ">>"
Else
cmdVisualControl.Text = "<<"
splCreateNewModel.Panel2Collapsed = False
Size = New Size(1300, 800)
End If
End Sub
Private Sub BrowseDirectory(sender As Object, e As EventArgs) Handles cmdBrowseDirectory.Click
Try
Dim sfd As New SelectFolderDialog With {
.Title = "Select a folder"
}
If sfd.ShowDialog(Me) = DialogResult.OK Then
txtModelDirectory.Text = sfd.FolderName
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub DialogOK(sender As Object, e As EventArgs) Handles cmdOk.Click
CreateModel()
Close()
End Sub
Private Sub DialogCancel(sender As Object, e As EventArgs) Handles cmdCancel.Click
Close()
End Sub
End Class

Update Database and datagridview from textboxes

I have an application with a datagridview on the bottom half of the page and textboxes, combo-boxes, buttons, etc... on the top half.
When the user changes the highlighted row in the grid then it displays all of the information for that row in the objects on the top half.
If user wants to change the data in a row then he clicks an edit button which enables the textboxes etc... and allows the user to edit the data.
(All of the above works fine).
When he wants to save the changes then he clicks the save button.
This should update the datasource to the grid and show the changes in the grid.
However, I have been unable to get it do this.
Any Help appreciated.
Code below:
Imports System.Data.SqlClient
Public Class frmEmployeeInformation
Public SQL As New SQLControl()
Dim strEditType As String
Private Sub frmEmployeeInformation_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadGrid()
End Sub
Public Sub LoadGrid(Optional query As String = "")
If query = "" Then
SQL.ExecuteQuery("Select * from EmployeeInformation;")
Else
SQL.ExecuteQuery(query)
End If
If SQL.HasException(True) Then Exit Sub
dgvEmployeeInformation.DataSource = SQL.DBDS.Tables(0)
dgvEmployeeInformation.Rows(0).Selected = True
SQL.DBDA.UpdateCommand = New SqlClient.SqlCommandBuilder(SQL.DBDA).GetUpdateCommand
End Sub
Private Sub DisplayValues()
If dgvEmployeeInformation.RowCount > 2 Then
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value <> Nothing Then
txtFirstName.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value.ToString 'EmployeeInformation.FirstName
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value <> Nothing Then
txtLastName.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value.ToString 'EmployeeInformation.LastName
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value IsNot Nothing Then
txtSSN.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value.ToString 'EmployeeInformation.SSN
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value <> Nothing Then
txtEmployeeID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value.ToString 'EmployeeInformation.EmployeeInformationID
End If
'If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value <> Nothing Then
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'End If
'If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value <> Nothing Then
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
'End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value <> Nothing Then
cboDefaultLocation.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value.ToString 'EmployeeInformation.DefaultLocation
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value <> Nothing Then
txtTableID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value.ToString 'EmployeeInformation.TableID
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value <> Nothing Then
chkbxActive.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value.ToString 'EmployeeInformation.EmployeeActive
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value <> Nothing Then
chkbxPrimaryFile.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value.ToString 'EmployeeInformation.PrimaryFile
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value <> Nothing Then
chkbxUnallocatedTime.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value.ToString 'EmployeeInformation.UnallocatedTime
End If
End If
End Sub
Private Sub ChangeButtons()
btnClose.Enabled = Not btnClose.Enabled
btnSave.Enabled = Not btnSave.Enabled
btnClear.Enabled = Not btnClear.Enabled
btnFind.Enabled = Not btnFind.Enabled
btnCancel.Enabled = Not btnCancel.Enabled
btnEdit.Enabled = Not btnEdit.Enabled
btnAdd.Enabled = Not btnAdd.Enabled
btnCopy.Enabled = Not btnCopy.Enabled
End Sub
Private Sub ChangeFields()
chkbxActive.Enabled = Not chkbxActive.Enabled
chkbxPrimaryFile.Enabled = Not chkbxPrimaryFile.Enabled
chkbxUnallocatedTime.Enabled = Not chkbxUnallocatedTime.Enabled
txtTableID.Enabled = Not txtTableID.Enabled
txtADPID.Enabled = Not txtADPID.Enabled
cboVP.Enabled = Not cboVP.Enabled
cboDefaultLocation.Enabled = Not cboDefaultLocation.Enabled
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
If txtEmployeeID.Text <> "" Then
SQL.AddParam("#EmployeeInformationID", txtEmployeeID.Text)
LoadGrid("select * from EmployeeInformation where EmployeeInformationID = #EmployeeInformationID;")
ElseIf txtSSN.Text <> "" Then
SQL.AddParam("#SSN", txtSSN.Text)
LoadGrid("select * from EmployeeInformation where SSN = #SSN;")
ElseIf txtFirstName.Text <> "" And txtLastName.Text <> "" Then
SQL.AddParam("#FirstName", txtFirstName.Text)
SQL.AddParam("#LastName", txtLastName.Text)
LoadGrid("select * from EmployeeInformation where FirstName = #FirstName and LastName = #LastName;")
Else
LoadGrid("Select * from EmployeeInformation;")
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtFirstName.Text = ""
txtLastName.Text = ""
txtSSN.Text = ""
txtEmployeeID.Text = ""
txtADPID.Text = ""
cboVP.Text = ""
cboDefaultLocation.Text = ""
txtTableID.Text = ""
chkbxActive.Checked = "False"
chkbxPrimaryFile.Checked = "False"
chkbxUnallocatedTime.Checked = "False"
End Sub
Private Sub dgvEmployeeInformation_DoubleClick(sender As Object, e As EventArgs) Handles dgvEmployeeInformation.DoubleClick
DisplayValues()
ChangeFields()
ChangeButtons()
End Sub
Private Sub dgvEmployeeInformation_SelectionChanged(sender As Object, e As EventArgs) Handles dgvEmployeeInformation.SelectionChanged
DisplayValues()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If strEditType = "Edit" Then
' The code below updates the grid but the changes are not saved to the database. Probably not the way to go
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value = txtFirstName.Text 'EmployeeInformation.FirstName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value = txtLastName.Text 'EmployeeInformation.LastName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value = txtSSN.Text 'EmployeeInformation.SSN
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value = txtEmployeeID.Text 'EmployeeInformation.EmployeeInformationID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value = cboDefaultLocation.Text 'EmployeeInformation.DefaultLocation
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value = txtTableID.Text 'EmployeeInformation.TableID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value = chkbxActive.Checked 'EmployeeInformation.EmployeeActive
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value = chkbxPrimaryFile.Checked 'EmployeeInformation.PrimaryFile
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value = chkbxUnallocatedTime.Checked 'EmployeeInformation.UnallocatedTime
' The code above updates the grid but the changes are not saved to the database.
dgvEmployeeInformation.EndEdit()
SQL.DBDS.Tables(0).AcceptChanges()
SQL.DBDA.Update(SQL.DBDS)
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
End If
ChangeFields()
ChangeButtons()
strEditType = ""
'LoadGrid()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
ChangeFields()
ChangeButtons()
strEditType = ""
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
dgvEmployeeInformation_DoubleClick(Nothing, EventArgs.Empty)
strEditType = "Edit"
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
btnClear_Click(Nothing, EventArgs.Empty)
txtFirstName.Focus()
strEditType = "Add"
ChangeFields()
ChangeButtons()
End Sub
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
cboDefaultLocation.Focus()
strEditType = "Copy"
ChangeFields()
ChangeButtons()
End Sub
End Class
TRY ANOTHER WAY!!
I suggest you, instead of doing this:
If strEditType = "Edit" Then
' The code below updates the grid but the changes are not saved to the database. Probably not the way to go
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value = txtFirstName.Text 'EmployeeInformation.FirstName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value = txtLastName.Text 'EmployeeInformation.LastName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value = txtSSN.Text 'EmployeeInformation.SSN
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value = txtEmployeeID.Text 'EmployeeInformation.EmployeeInformationID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value = cboDefaultLocation.Text 'EmployeeInformation.DefaultLocation
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value = txtTableID.Text 'EmployeeInformation.TableID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value = chkbxActive.Checked 'EmployeeInformation.EmployeeActive
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value = chkbxPrimaryFile.Checked 'EmployeeInformation.PrimaryFile
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value = chkbxUnallocatedTime.Checked 'EmployeeInformation.UnallocatedTime
' The code above updates the grid but the changes are not saved to the database.
dgvEmployeeInformation.EndEdit()
SQL.DBDS.Tables(0).AcceptChanges()
SQL.DBDA.Update(SQL.DBDS)
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
End If
to first update your DB and than to update the datagrid from your DB.
Something like
Sql = "update TABLE_Name set FirstName = #fName" 'write all your query'
myCmd = New SqlCommand(Sql, myConn)
myCmd.Parameters.Add("#fName", SqlDbType.VarChar).Value = txtFirstName.Text
myCmd.ExecuteNonQuery()
MsgBox("Update complete.")
myConn.Close()
And than you can update your datagrid! I'm always used to connect my DataGrid to my SQL table, so the code will be:
Public Sub Updating()
Me.Table_NameTableAdapter.Fill(Me.DB_NameDataSet1.Table_Name)
End Sub
Got it to work:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim dbconn As New SqlConnection("server=192.168.50.205;Database=SEMHC_Admin2018;trusted_Connection=True;")
Dim mycmd As SqlCommand
Dim mySQL As String
dbconn.Open()
If strEditType = "Add" Or strEditType = "Copy" Then
End If
If strEditType = "Edit" Then
mySQL = "update employeeInformation
set FirstName = #firstName,
LastName = #LastName,
SSN = #SSN,
EmployeeInformationID = #EmployeeInformationID,
Default_LocationID = #Default_LocationID,
EmployeeActive = #chkbxActive,
PrimaryFile = #chkbxPrimaryFile,
UnallocatedTime = #chkbxUnallocatedTime
from employeeInformation
WHERE SystemTableID = #SystemTableID
" 'write query'
mycmd = New SqlCommand(mySQL, dbconn)
mycmd.Parameters.Add("#SystemTableID", SqlDbType.VarChar).Value = txtTableID.Text
mycmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text
mycmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text
mycmd.Parameters.Add("#SSN", SqlDbType.VarChar).Value = txtSSN.Text
mycmd.Parameters.Add("#EmployeeInformationID", SqlDbType.VarChar).Value = txtEmployeeID.Text
mycmd.Parameters.Add("#Default_LocationID", SqlDbType.VarChar).Value = cboDefaultLocation.Text
mycmd.Parameters.Add("#chkbxActive", SqlDbType.VarChar).Value = chkbxActive.Checked
mycmd.Parameters.Add("#chkbxPrimaryFile", SqlDbType.VarChar).Value = chkbxPrimaryFile.Checked
mycmd.Parameters.Add("#chkbxUnallocatedTime", SqlDbType.VarChar).Value = chkbxUnallocatedTime.Checked
mycmd.ExecuteNonQuery()
'MsgBox("Update complete.")
dbconn.Close()
'SQL.DBDS.Tables(0).AcceptChanges()
'SQL.DBDA.Update(SQL.DBDS)
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
End If
ChangeFields()
ChangeButtons()
strEditType = ""
LoadGrid()
End Sub

Splitting data received from Arduino

I am new to vb and I'm trying to split serial data received from the Arduino board on Visual Basic. I've watched and followed tutorials online that outputs all the serial data in one textbox and it works. But now i need to split the data into textboxes that correspond to the sensor (i have 5 sensors).
I've tried using .Split and arrays to split and then store the data before moving it to the corresponding textbox but it doesn't work.
Appreciate all the help I can get
Dim receivedData As String = ""
Private Sub AirQuality_Load(sender As Object, e As EventArgs) Handles Me.Load
GetSerialPortNames()
Timer1.Enabled = False
txtPmax.Text = 14.7
txtPmin.Text = 10
txtO2max.Text = 21
txtO2min.Text = 15
txtCO2.Text = 1000
txtP25.Text = 25
txtP10.Text = 50
txtCO.Text = 35
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
cbCOMPort.Items.Add(sp)
Next
cbCOMPort.SelectedIndex = 0
End Sub
Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
Try
If (btnConnect.Text = "Connect") Then
If (cbCOMPort.Text <> "") Then
'Open Serial Port
SerialPort1.Close()
SerialPort1.PortName = cbCOMPort.Text
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default 'very important!
SerialPort1.ReadTimeout = 10000
SerialPort1.Open()
btnConnect.Text = "Dis-connect"
Timer1.Enabled = True
btnUpdate.PerformClick()
Else
MsgBox("Select a COM port first")
End If
Else
SerialPort1.Close()
btnConnect.Text = "Connect"
Timer1.Enabled = False
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Function ReceiveSerialData() As String
Dim Incoming As String
Dim Array() As String
Incoming = SerialPort1.ReadExisting
Array = Split(Incoming, ";")
Pactual.Text = Array(0)
O2actual.Text = Array(1)
COactual.Text = Array(2)
CO2actual.Text = Array(3)
P25actual.Text = Array(4)
P10actual.Text = Array(5)
txtUpdate.Text = Array(6)
End Function
Sub numberValidate()
Try
If (CDbl(txtPmax.Text) < CDbl(txtPmin.Text) Or (CDbl(txtO2max.Text) < CDbl(txtO2min.Text))) Then
MsgBox("Error. Must be numbers or Max < Min")
End If
Catch ex As Exception
MsgBox("Error. Must be numbers or Max < Min")
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Static bFlash As Boolean
receivedData = ReceiveSerialData()
If receivedData IsNot Nothing Then
txtUpdate.Text = receivedData
' Warning in GUI
Dim bWar As Boolean = receivedData.Contains("--Pressure not OK--" Or "--CO2 not OK--" Or "--O2 not OK--")
If receivedData.Contains("--Pressure not OK--" Or "--CO2 not OK--" Or "--O2 not OK--") Then
bFlash = Not bFlash
If bFlash Then
txtUpdate.BackColor = Color.FromArgb(255, 0, 0)
Else
txtUpdate.BackColor = Color.FromArgb(255, 255, 255)
End If
Else
txtUpdate.BackColor = Color.FromArgb(255, 0, 255)
End If
If receivedData.Contains("--Condition: Normal--") Then
txtUpdate.BackColor = Color.FromArgb(255, 255, 255)
End If
End If
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim writeText As String
writeText = "<" & CDbl(txtPmax.Text).ToString("00.0") & CDbl(txtPmin.Text).ToString("00.0") & CInt(txtO2max.Text).ToString("00") & CInt(txtO2min.Text).ToString("00") & CInt(txtCO2.Text).ToString("0000") & ">"
txtUpdate.Text = writeText
SerialPort1.Write(writeText)
End Sub

How to show MsgBox after finishing unzip process

I have this code:
Private Sub KickoffExtract()
actionStatus.Text = "Se instaleaza actualizarea.. va rugam asteptati."
lblProgress.Text = "Se extrage..."
Dim args(2) As String
args(0) = GetSettingItem("./updUrl.info", "UPDATE_FILENAME")
args(1) = extractPath
_backgroundWorker1 = New System.ComponentModel.BackgroundWorker()
_backgroundWorker1.WorkerSupportsCancellation = False
_backgroundWorker1.WorkerReportsProgress = False
AddHandler Me._backgroundWorker1.DoWork, New DoWorkEventHandler(AddressOf Me.UnzipFile)
_backgroundWorker1.RunWorkerAsync(args)
End Sub
Private Sub UnzipFile(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim extractCancelled As Boolean = False
Dim args() As String = e.Argument
Dim zipToRead As String = args(0)
Dim extractDir As String = args(1)
Try
Using zip As ZipFile = ZipFile.Read(zipToRead)
totalEntriesToProcess = zip.Entries.Count
SetProgressBarMax(zip.Entries.Count)
AddHandler zip.ExtractProgress, New EventHandler(Of ExtractProgressEventArgs)(AddressOf Me.zip_ExtractProgress)
zip.ExtractAll(extractDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
End Using
Catch ex1 As Exception
MessageBox.Show(String.Format("Actualizatorul a intampinat o problema in extragerea pachetului. {0}", ex1.Message), "Error Extracting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
End Try
End Sub
Private Sub SetProgressBarMax(ByVal n As Integer)
If ProgBar.InvokeRequired Then
ProgBar.Invoke(New Action(Of Integer)(AddressOf SetProgressBarMax), New Object() {n})
Else
ProgBar.Value = 0
ProgBar.Maximum = n
ProgBar.Step = 1
End If
End Sub
Private Sub zip_ExtractProgress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
If _operationCanceled Then
e.Cancel = True
Return
End If
If (e.EventType = Ionic.Zip.ZipProgressEventType.Extracting_AfterExtractEntry) Then
StepEntryProgress(e)
ElseIf (e.EventType = ZipProgressEventType.Extracting_BeforeExtractAll) Then
End If
End Sub
Private Sub StepEntryProgress(ByVal e As ExtractProgressEventArgs)
If ProgBar.InvokeRequired Then
ProgBar.Invoke(New ZipProgress(AddressOf StepEntryProgress), New Object() {e})
Else
ProgBar.PerformStep()
System.Threading.Thread.Sleep(100)
nFilesCompleted = nFilesCompleted + 1
lblProgress.Text = String.Format("{0} din {1} fisiere...({2})", nFilesCompleted, totalEntriesToProcess, e.CurrentEntry.FileName)
Me.Update()
End If
End Sub
and this code on a button:
If Not File.Exists("./" + GetSettingItem("./updUrl.info", "UPDATE_FILENAME")) Then
MessageBox.Show("Actualizarea nu s-a descarcat corespunzator.", "Nu se poate extrage", MessageBoxButtons.OK)
End If
If Not String.IsNullOrEmpty("./" + GetSettingItem("./updUrl.info", "UPDATE_FILENAME")) And
Not String.IsNullOrEmpty(extractPath) Then
If Not Directory.Exists(extractPath) Then
Directory.CreateDirectory(extractPath)
End If
nFilesCompleted = 0
_operationCanceled = False
btnUnzip.Enabled = False
KickoffExtract()
End If
How can I show a message after completing the UnZip process? I tried
If ProgBar.Maximum Then
MsgBox("finish")
End If
but it doesn't work. I'm using dotnetzip 1.9, and the most of the code is from UnZip example.
If you check the documentation of BackgroundWorker you will notice that there are two events that can be linked to an event handler in your code.
One of them is the RunWorkerCompleted and in the MSDN page they say
Occurs when the background operation has completed, has been canceled,
or has raised an exception.
So, it is just a matter to write an event handler and bind the event.
AddHandler Me._backgroundWorker1.RunWorkerCompleted, New RunWorkerCompletedEventHandler(AddressOf Me.UnzipComplete)
and then
Private Sub UnzipComplete(ByVal sender As System.Object, _
ByVal e As RunWorkerCompletedEventArgs)
If e.Cancelled = True Then
MessageBox.Show("Canceled!")
ElseIf e.Error IsNot Nothing Then
MessageBox.Show("Error: " & e.Error.Message)
Else
MessageBox.Show("Unzip Completed!")
End If
End Sub