I'm building an application that can communicate and send commands to game servers. In the gaming world we call this “rcon” for remote console, but in reality it's just a telnet session. After successful authentication, a text command can be issued to the server and a text response is sent back to the client.
Often times server admins/owners run multiple game servers and every server has its own distinct ip address, port & password. I would like my application to loop through a list/array/datatable/dictionary (or whatever method is best ) of servers, connect and authenticate to each server, then somehow store that connection so commands can be sent to it in the future (Without having to connect & authenticate again)
Below is the code I have that works for a single server. I store the TcpClient(client) & NetworkStream(stm) as global objects which keeps the connection/session open to the server. What is the best method for me to do this with multiple servers since each server will have it's own TcpClient & NetworkStream?
Is there some way for me to store each TcpClient(client) & NetworkStream(stm) in an array, dictionary or something? I'm completely lost with how to approach this.
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Security.Cryptography
Imports System.IO
Public Class Form1
Public client As TcpClient
Public stm As NetworkStream
Sub SendCmd(cmd As String)
Dim data
If cmd.Trim = "" Then
data = Encoding.GetEncoding(1252).GetBytes(cmd)
Else
data = Encoding.GetEncoding(1252).GetBytes(cmd & vbCrLf)
End If
stm.Write(data, 0, data.Length)
Dim resp As Byte() = New Byte(512) {}
Dim memStream = New MemoryStream()
Thread.Sleep(500)
Dim bytes As Integer = 0
If stm.DataAvailable Then
Do
Thread.Sleep(10)
bytes = stm.Read(resp, 0, resp.Length)
memStream.Write(resp, 0, bytes)
Loop While stm.DataAvailable
Dim responsedata As String = Encoding.GetEncoding(1252).GetString(memStream.ToArray())
If responsedata.Contains("### Digest seed: ") Then
'The server is asking for authentication: Login to the server now
Authenticate(responsedata)
End If
OutputRTB.Text &= responsedata
End If
memStream.Close()
End Sub
Sub GetPlayerList()
If stm.CanRead Then
Dim data = Encoding.GetEncoding(1252).GetBytes("bf2cc pl" & vbCrLf)
Dim PlayerDT As New DataTable
PlayerDT.Columns.Add("PlayerSlot", GetType(Integer))
PlayerDT.Columns.Add("HeroName", GetType(String))
PlayerDT.Columns.Add("Score", GetType(String))
PlayerDT.Columns.Add("HeroID", GetType(String))
PlayerDT.Columns.Add("PlayerID", GetType(String))
PlayerDT.Columns.Add("Level", GetType(Integer))
PlayerDT.Columns.Add("Class", GetType(String))
PlayerDT.Columns.Add("Ping", GetType(Integer))
stm.Write(data, 0, data.Length)
Dim resp As Byte() = New Byte(512) {}
Dim memStream = New MemoryStream()
Thread.Sleep(500)
Dim bytes As Integer = 0
If stm.DataAvailable Then
Do
Thread.Sleep(10)
bytes = stm.Read(resp, 0, resp.Length)
memStream.Write(resp, 0, bytes)
Loop While stm.DataAvailable
Dim responsedata As String = Encoding.GetEncoding(1252).GetString(memStream.ToArray())
If responsedata.Contains("### Digest seed: ") Then
'Login to the server
Authenticate(responsedata)
End If
OutputRTB.Text = responsedata.Replace(vbTab, "^")
Dim Rows() As String = responsedata.Split(Environment.NewLine)
For i = 0 To Rows.Length - 1
Dim Cols() As String = Rows(i).Split(vbTab)
If Cols.Length > 40 Then
PlayerDT.Rows.Add(Cols(0).ToString(), Cols(1).ToString(), Cols(37).ToString(), Cols(10).ToString(), Cols(47).ToString(), Cols(39).ToString(), Cols(34).ToString(), Cols(3).ToString)
End If
Next
End If
DataGridView1.DataSource = PlayerDT
DataGridView1.Update()
memStream.Close()
End If
End Sub
Sub Authenticate(ByVal rdata As String)
Dim DigestKeyStart As Integer = rdata.LastIndexOf(":") + 2
Dim DigestKeyLen As Integer = 16
Dim PWResponse As String = rdata.Substring(DigestKeyStart, DigestKeyLen) & PassTXT.Text
PWResponse = "login " & GenerateHash(PWResponse)
SendCmd(PWResponse)
End Sub
Private Function GenerateHash(ByVal SourceText As String) As String
Dim objMD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim arrData() As Byte
Dim arrHash() As Byte
' first convert the string to bytes (using UTF8 encoding for unicode characters)
arrData = System.Text.Encoding.UTF8.GetBytes(SourceText)
' hash contents of this byte array
arrHash = objMD5.ComputeHash(arrData)
' thanks objects
objMD5 = Nothing
' return formatted hash
Return ByteArrayToString(arrHash)
End Function
Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
Dim strOutput As New System.Text.StringBuilder(arrInput.Length)
For i As Integer = 0 To arrInput.Length - 1
strOutput.Append(arrInput(i).ToString("X2"))
Next
Return strOutput.ToString().ToLower
End Function
Private Sub Form1_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
stm.Close()
client.Close()
End Sub
Private Sub ConnectBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectBTN.Click
client = New TcpClient(ServerIPTXT.Text, PortTXT.Text)
stm = client.GetStream()
SendCmd(CommandTXT.Text)
End Sub
Private Sub SendCommandBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendCommandBTN.Click
SendCmd(CommandTXT.Text)
End Sub
Private Sub GetPlayerListBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetPlayerListBTN.Click
GetPlayerList()
End Sub
End Class
BTW This is my first post on stackoverflow, but I have learned so much from this site over the years =)
Related
I'm sorry for the log post but I am about to pull my hair out. I am attempting to import a PDF into a database.
The main error I am getting is: "Implicit conversion from data type varchar to varbinary(MAX) is not allowed. Use the CONVERT function to run this query."
Some of the coding included below is for a SEARCH function that is not yet completed. Please disregard that area of coding.
Basically I am loading a PDF in the AxAcroPDF1 box. This works great. It then pre-fills out a few of the textboxes. User inputs the Broker Load Number than hits save and a openfiledialog opens and the file is chosen to be imported. This then is where the failed import happens and the error above is given. I have tried many different avenues but always ending up with the same result. I am at a complete and total loss.
Table structure is as follows:
ID, int, NOT NULL IDENTITY(1,1) PRIMARY KEY,
BROKER_LOAD_NUMBER nvarchar(15) NOT NULL,
PDF_FILENAME,nvarchar(50) NOT NULL,
PETS_LOAD_NUMBER nvarchar(10) NOT NULL,
PAPERWORK varbinary(MAX) NOT NULL
My FULL code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
End Sub
Private Sub btnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
Private Sub SearchResult()
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
'SQL to get specific data from the Documents_Table
cmd.Parameters.Clear()
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
End Sub
Private Sub LbllSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
Dim Extension As String = Path.GetExtension(sFileToUpload)
upLoadImageOrFile(sFileToUpload, "PDF")
upLoadImageOrFile(sFileToUpload, Extension)
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, PAPERWORK)
VALUES ('#bl', '#fn', '#pl', '#pdf');"
cmd.Parameters.AddWithValue("#fn", tbFileName.Text)
cmd.Parameters.AddWithValue("#p1", tbPetsLoadNumber.Text)
cmd.Parameters.AddWithValue("#bl", tbBrokerLoadNumber.Text)
cmd.Parameters.AddWithValue("#fp", tbFilePath.Text)
cmd.Parameters.AddWithValue("#pdf", data)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub upLoadImageOrFile(sFilePath As String, sFileType As String)
Dim cmd As New SqlCommand
Dim Data As Byte()
Dim sFileName As String
Dim qry As String
Try
'Read Image Bytes into a byte array
Data = ReadFile(sFilePath)
sFileName = Path.GetFileName(sFilePath)
'Set insert query
qry = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, PAPERWORK)
VALUES ('#bl', '#fn', '#pl', '#pdf')"
'Initialize SqlCommand object for insert.
cmd = New SqlCommand(qry, cmd.Connection)
'We are passing File Name and Image byte data as sql parameters.
cmd.Parameters.AddWithValue("#fn", tbFileName.Text)
cmd.Parameters.AddWithValue("#p1", tbPetsLoadNumber.Text)
cmd.Parameters.AddWithValue("#bl", tbBrokerLoadNumber.Text)
cmd.Parameters.AddWithValue("#fp", tbFilePath.Text)
cmd.Parameters.AddWithValue("#pdf", Data)
cmd.ExecuteNonQuery()
MessageBox.Show("File uploaded successfully")
Catch ex As Exception
MessageBox.Show("File could not uploaded")
End Try
End Sub
Private Function ReadFile(sFilePath As String) As Byte()
Throw New NotImplementedException()
End Function
End Class
I get this SQL Server error and I can't figure out where the trouble is:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
xception Details: System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.'
Source Error: Line: 46
Error Line: cmdsql.ExecuteNonQuery()
Code:
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
On Error Resume Next
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
FileAdd.Text = OpenFileDialog1.FileName
connexcel = New OleDbConnection("provider = Microsoft.ace.OLEDB.12.0; data source =" & FileAdd.Text & "; Extended Properties = Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
ExcelSheetList.Items.Add(sheet)
Next
End Sub
Private Sub ExcelSheetList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcelSheetList.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & ExcelSheetList.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
DGVImpData.DataSource = dsexcel.Tables(0)
DGVImpData.ReadOnly = True
End Sub
Sub connections()
connsql = New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
connsql.Open()
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
For line As Integer = 0 To DGVImpData.RowCount - 2
Call connections()
Dim save As String = "insert into InvoiceData values ('" & DGVImpData.Rows(line).Cells(0).Value & "', '" & DGVImpData.Rows(line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
Keep your database objects local so you can be sure they are closed and disposed. Enclosing these objects with `Using...End Using blocks will accomplish this even if there is an error. You don't need variables for DataAdapters, DataSets, or DataReaders. I suggest only one form level variable for the Excel connection string since it is used in 2 methods.
A little bit of Linq will get the retrieved sheet names from the DataTable and fill an array. The array can then be passed to the list box with .AddRange.
I wouldn't use the SelectedIndexChanged event because the user can too easily click the wrong sheet or change their mind. I used a Button.Click event to fill the grid.
The Sql connection string looks strange to me. I suggest you test it separately. If it doesn't work, this is a good resource. https://www.connectionstrings.com/
I would specifically state the column names in the Insert statement. Replace FirstColumnName and SecondColumnName with the real column names. The parameter names can be anything you wish as long as the names in the statement match the names in the Parameters.Add method. I have guessed at the datatypes and the size. Check your database for correct values.
We add the parameters only once outside the loop then change only values inside the loop.
Private ExcelConString As String
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
Dim strFileName As String
Dim dtSheets As DataTable
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
strFileName = OpenFileDialog1.FileName
ExcelConString = "provider = Microsoft.ace.OLEDB.12.0; data source =" & strFileName & "; Extended Properties = Excel 8.0;"
Using connexcel = New OleDbConnection(ExcelConString)
connexcel.Open()
dtSheets = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
End Using
Dim exSheets() As Object = (From dRow In dtSheets.AsEnumerable() Select dRow("TABLE_Name")).ToArray
ExcelSheetList.Items.AddRange(exSheets)
End Sub
Private Sub DisplayData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisplayData.Click
Dim dt As New DataTable
Using cn As New OleDbConnection(ExcelConString)
'In older versions of Visual Studio you may have to use String.Format instead of the interpolated string.
Using cmd As New OleDbCommand($"select * from [{ExcelSheetList.Text}];", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DGVImpData.DataSource = dt
DGVImpData.ReadOnly = True
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
Using cn As New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
Using cmd As New SqlCommand("Insert Into InvoiceData (FirstColumnName, SecondColumnName) Values (#FirstColumn, #SecondColumn);", cn)
cmd.Parameters.Add("#FirstColumn", SqlDbType.VarChar, 100)
cmd.Parameters.Add("#SecondColumn", SqlDbType.VarChar, 100)
cn.Open()
For line As Integer = 0 To DGVImpData.RowCount - 2
cmd.Parameters("#FirstColumn").Value = DGVImpData.Rows(line).Cells(0).Value
cmd.Parameters("#SecondColumn").Value = DGVImpData.Rows(line).Cells(1).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
As to error handling... On Error Resume Next is generally not used in new code. We have Try...Catch...Finally blocks. After your code is running add these blocks where needed.
EDIT
To use String.Format...
Using cmd As New OleDbCommand(String.Format("select * from [{0}];", ExcelSheetList.Text))
The first parameter is the string in which you wish to place variables. It contains indexed placeholders enclosed in braces. The following parameters are the variables you want for the placeholder substitution.
Thank you for helping me to a fixed error in my code. Here is Final code without System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.' error.
Now I tried to improve code with the last section(mention below) to define parameters for exporting data. Because I have a large number of data for exporting to SQL Server I get a Timeout error. Can anyone be able to improve code for quick exporting data to SQL Server?
connsql.Open() "System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'"
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub Import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub PKGAbtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpExcelFile.Click
On Error Resume Next
'OpenFileDialog1.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx|All files (*.*)|*.*"
PKGAofdImpOpenExcel.ShowDialog()
PKGAtxtImpFileAdd.Text = PKGAofdImpOpenExcel.FileName
connexcel = New OleDbConnection("provider=Microsoft.ace.OLEDB.12.0;data source=" & PKGAtxtImpFileAdd.Text & ";Extended Properties=Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
PKGAtxtImpExlSheetL.Items.Add(sheet)
Next
End Sub
Private Sub PKGAtxtImpExlSheetL_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAtxtImpExlSheetL.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & PKGAtxtImpExlSheetL.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
PKGAdgvImpData.DataSource = dsexcel.Tables(0)
PKGAdgvImpData.ReadOnly = True
End Sub
'Last Section
Sub Connectonsql()
connsql = New SqlConnection("Data Source=DESKTOP-MIQGJTK\MSSMLBIZ;Initial Catalog=PkGlobalAccounting;Integrated Security=True")
connsql.Open()
End Sub
Private Sub PKGAbtnImpSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpSave.Click
For Line As Integer = 0 To PKGAdgvImpData.RowCount - 2
Call Connectonsql()
Dim save As String = "insert into Test values('" & PKGAdgvImpData.Rows(Line).Cells(0).Value & "','" & PKGAdgvImpData.Rows(Line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("Data Saved Successfully")
PKGAdgvImpData.Columns.Clear()
End Sub
Thanks for Your Help.
since i have the code of the auto generated text box
Insert data from auto generated textbox to SQL Server database
i am try to write a code for ensuring of the auto generated text box in FlowLayoutPanel1 contain data
the auto generated text box build depends on the number in Val(Label2.Text) of the real part
and if any text box is null or empty then the process will stop until fill all fields
the auto generated text box will be like this if the Val(Label2.Text)
is equal to 3
so i try this in the save button
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
so i getting error after leave some text box and back to fill it again
and the all of form code is
Imports System.Data.SqlClient
'library for create folders
Imports System.IO
Public Class part
Dim cLeft As Integer = 1
Dim top1 As Integer = 5
Dim i As Integer = 0
Dim path1 As String
Dim cmd As SqlCommand
Public Sub AddNewTextBox()
Dim txt As New System.Windows.Forms.TextBox()
txt.Top = cLeft * 30
txt.Left = 100
'txt.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
txt.ForeColor = Color.White
txt.BackColor = Color.Gray
txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
txt.Size = New Size(350, 31)
txt.Location = New Point(156, 130 + top1)
txt.TextAlign = HorizontalAlignment.Center
FlowLayoutPanel1.Controls.Add(txt)
End Sub
Private Sub part_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'college part number
Label2.Visible = False
'college path folder
Label3.Visible = False
For m As Integer = 1 To Val(Label2.Text)
AddNewTextBox()
top1 = top1 + 35
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub UpdateUsers()
Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Hazim M\Desktop\stud_project\stud_project\Database1.mdf;Integrated Security=True;User Instance=True")
Using cmd As New SqlCommand("INSERT INTO college_part ([name],[coll_of_part],[part_path]) Values (#name,#coll_of_part,#part_path);", cn)
If i < Val(Label2.Text) Then
path1 = Label3.Text & "\" & FlowLayoutPanel1.Controls(i).Text.Trim & Date.Now.Year
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = FlowLayoutPanel1.Controls(i).Text
cmd.Parameters.Add("#coll_of_part", SqlDbType.NVarChar).Value = Label1.Text
cmd.Parameters.Add("#part_path", SqlDbType.NVarChar).Value = path1
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
If Not Directory.Exists(path1) Then
Directory.CreateDirectory(path1)
Else
MsgBox("folder is existing")
End If
End If
End Using
End Using
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
End Class
thank u
I think you need to move dim i Integer=0 to local variable in the Button3_click method. ANd Pass i to the UpdateUser call (add the param to UpdateUser). The current global i keeps adding 1 and eventually out of range.
I am creating an app in VB.NET that will play a song on user given time. User store song location and play time in ms-access database. when system time match with database time the song will play automatically. I've tried this with given below code but this is not working.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Timer1.Tick
Call Play(Format(Now, "Long Time"))
End Sub
Sub Play(ByVal tm As String)
Dim ConnectionString As String
ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=" & Application.StartupPath & "\VideoPlay.accdb;"
Dim AccessConnection As New
System.Data.OleDb.OleDbConnection(ConnectionString)
AccessConnection.Open()
Dim da As New System.Data.OleDb.OleDbDataAdapter("SELECT *
FROM VideoPlay", AccessConnection)
Dim ds As New DataSet
da.Fill(ds, "VideoPlay")
Dim dt As DataTable
dt = ds.Tables("VideoPlay")
Dim x As Integer
If dt.Rows.Count > 0 Then
For x = 0 To dt.Rows.Count - 1
If tm = dt.Rows(x).Item("TM") Then
MsgBox("yes")
End If
Next
End If
AccessConnection.Close()
da.Dispose()
ds.Dispose()
dt.Dispose()
AccessConnection.Close()
End Sub
End Class
Can any one tell me what is wrong in my code or any other way to compare system time with database time.
thanks in advance.
I am trying to develop a code that manages the firewall ports using vb.net. The first part is to list all ports enabled. so I am trying this code:
Function portsList()
Dim ports As INetFwOpenPorts
Dim port As INetFwOpenPort
Dim myPorts() As INetFwOpenPorts
Dim NetFwMgrType As Type = Type.GetTypeFromProgID("HNetCfg.FwMgr", False)
Dim mgr As INetFwMgr = DirectCast(Activator.CreateInstance(NetFwMgrType), INetFwMgr)
ports = DirectCast(mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts, INetFwOpenPorts)
Dim enumerate As System.Collections.IEnumerator = ports.GetEnumerator()
Dim i As Integer
While enumerate.MoveNext()
port = DirectCast(enumerate.Current, INetFwOpenPort)
myPorts(i) = port
i += 1
End While
Dim portAsString() As String
For j As Integer = 0 To i
portAsString(j) = myPorts(j).ToString
Next
Return portAsString
End Function
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim ports() As String = portsList()
Dim n As String = ports.Length
Dim newString As String = ""
For h As Integer = 0 To n
newString = ports(h) & vbNewLine
Next
RichTextBox1.Text = newString
End Sub
What I want to do is list all the ports in Richtextbox1 after clicking Button4. The error that I am getting is:
NullReferenceException was unHandled. Object reference not set to an instance of an object.
I am new to Vb, how can I get over this?
Try this:
For port As Integer = 1 to maxPorts
Dim host As String = "192.168.1.7"
Dim hostadd As Net.IPAddress = Net.Dns.GetHostEntry(host).AddressList(0)
Dim EPhost As New Net.IPEndPoint(hostadd, port)
Dim s As New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
Try
s.Connect(EPhost)
Catch
End Try
If s.Connected Then
'Port opened
Else
'Port closed
End If
Next
Here you have the complete project.