SMS Sending Application in VB.net - vb.net

I'm trying to develop an application with vb.net 2008 to send sms to phone numbers from my pc. I've connected my nokia phone to my pc using USB cable (connected with COM3 port). Given bellow code which I have written should work but message is not being sent and I'm getting my app as deadlock condition:
Imports System
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim ports As String() = SerialPort.GetPortNames
Dim port As String
For Each port In ports
ComboBox1.Items.Add(port)
Next port
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub cmdConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdConnect.Click
Try
With SerialPort1
.PortName = ComboBox1.Text
.BaudRate = 9600
.Parity = Parity.None
.StopBits = StopBits.One
.DataBits = 8
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
.Open()
MsgBox("Connected !", MsgBoxStyle.Information)
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub cmdSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSend.Click
Try
If SerialPort1.IsOpen Then
With SerialPort1
.Write("AT" & vbCrLf)
.Write("AT+CMGF=1" & vbCrLf)
.Write("AT+CMGS=" & Chr(34) & TextBox1.Text & Chr(34) & vbCrLf)
.Write(RichTextBox1.Text & Chr(26))
.Close()
MsgBox("Message Sent!", MsgBoxStyle.Information)
End With
Else
MsgBox("Error on port")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

Public Function sendMsg(ByVal port As SerialPort, ByVal PhoneNo As String, ByVal Message As String) As Boolean
Dim isSend As Boolean = False
Try
Dim recievedData As String = ExecCommand(port,"AT", 300, "No phone connected")
recievedData = ExecCommand(port,"AT+CMGF=1", 300, "Failed to set message format.")
Dim command As String = "AT+CMGS=""" & PhoneNo & """"
recievedData = ExecCommand(port,command, 300, "Failed to accept phoneNo")
command = Message & Char.ConvertFromUtf32(26) & vbCr
recievedData = ExecCommand(port,command, 3000, "Failed to send message") '3 seconds
If recievedData.EndsWith(vbCrLf & "OK" & vbCrLf) Then
isSend = True
ElseIf recievedData.Contains("ERROR") Then
isSend = False
End If
Return isSend
Catch ex As Exception
Throw ex
End Try
End Function
ExecCommand
Public Function ExecCommand(ByVal port As SerialPort, ByVal command As String, ByVal responseTimeout As Integer, ByVal errorMessage As String) As String
Try
port.DiscardOutBuffer()
port.DiscardInBuffer()
receiveNow.Reset()
port.Write(command & vbCr)
Dim input As String = ReadResponse(port, responseTimeout)
If (input.Length = 0) OrElse (((Not input.EndsWith(vbCrLf & "> "))) AndAlso ((Not input.EndsWith(vbCrLf & "OK" & vbCrLf)))) Then
Throw New ApplicationException("No success message was received.")
End If
Return input
Catch ex As Exception
Throw ex
End Try
End Function

You can also try this coding..
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class Form1
'connect your mobile/GSM modem to PC,
'then go in device manager and check under ports which COM port has been slected
'if say com1 is there then put com2 in following statement
Dim SMSEngine As New SMSCOMMS("COM17")
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
SMSEngine.SendSMS() 'send the SMS
End Sub
End Class
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
'initialize all values
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 19200
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function SendSMS() As Boolean
Application.DoEvents()
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
Thread.Sleep(500)
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
Thread.Sleep(500)
' SMSPort.WriteLine("AT+CSCA=""+919822078000""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS=" & """" & Form1.TextBox1.Text & """" & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
Thread.Sleep(500)
SMSPort.WriteLine(Form1.TextBox2.Text & Chr(26)) 'SMS sending(specify the labl and the text box)
MessageBox.Show(":send")
SMSPort.Close()
End If
End Function
Public Sub Open()
If Not (SMSPort.IsOpen = True) Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen = True Then
SMSPort.Close()
End If
End Sub
End Class
you have to connect your phone with PC Suite or Bluetooth or using USB cable.
After that you have to check the port number and change in coding part according to your port number.
Dim SMSEngine As New SMSCOMMS("COM17")
It is working for me..

Related

sending sms message with vb and modem 3g

Hello guys I'm created a windows form that has a basic function of sending sms message to a phone by using my 3g modem. My modem 3g has load that will be use for texting. I check my device manager and I saw my modem 3g is already connected but Unfortunately, it's not sending sms message to my phone's number. here's my code so far. By the way my portname of device is com4
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim ports As String() = SerialPort.GetPortNames
Dim port As String
For Each port In ports
ComboBox1.Items.Add(port)
Next port
ComboBox1.SelectedIndex = 0
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
With SerialPort1
.PortName = ComboBox1.Text
.BaudRate = 9600
.Parity = Parity.None
.StopBits = StopBits.One
.DataBits = 8
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
.Open()
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
If SerialPort1.IsOpen Then
With SerialPort1
.Write("AT" & vbCrLf)
.Write("AT+CMGF=1" & vbCrLf)
.Write("AT+CMGS=" & Chr(34) & TextBox1.Text & Chr(34) & vbCrLf)
.Write(RichTextBox1.Text & Chr(26))
MsgBox("Succesfully Send!")
End With
Else
MsgBox("Port not open!")
End If
Catch ex As Exception
End Try
End Sub
End Class

tcp connection with machine via ethernet using vb.net

I want to make a simple formapp using vb.net to send ASCII strings to a machine, that responds after every command. i.e., if i send "AA" it responds "123".
I can already open the connection cause if i check the connection with hyperterminal it says that the port is already being used. Yet, when i send commands i have no answer back.
I kinda adapted the template codes for server/client chat with tcp:
Imports System.Net.Sockets
Imports System.Threading
Dim Listener As New TcpListener(65535)
Dim Client As New TcpClient
Dim Message As String = "
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
If Listener.Pending = True Then
Message = ""
Client = Listener.AcceptTcpClient()
Dim Reader As New StreamReader(Client.GetStream())
While Reader.Peek > -1
Message = Message + Convert.ToChar(Reader.Read()).ToString
End While
RichTextBox1.ForeColor = Color.Black
RichTextBox1.Text += Message + vbCrLf
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSend.Click
If txtName.Text = "" Or cmbAddress.Text = "" Then
MessageBox.Show("All Fields must be Filled", _
"Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Try
Client = New TcpClient(cmbAddress.Text, 65535)
Dim Writer As New StreamWriter(Client.GetStream())
Writer.Write(txtName.Text & " Says: " & txtmessage.Text)
Writer.Flush()
RichTextBox1.Text += (txtName.Text & " Says: " & txtmessage.Text) + vbCrLf
txtmessage.Text = ""
Catch ex As Exception
Console.WriteLine(ex)
Dim Errorresult As String = ex.Message
MessageBox.Show(Errorresult & vbCrLf & vbCrLf & _
"Please Review Client Address", _
"Error Sending Message", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
is there a muuuuuuuch better way to do this? i read about .net.sockets but i coulndt get out of this.
and the manuals say nothing about how the machine operates. if it's a client, server, host.. can someone help me here? thank you !
Imports System.Net
Imports System.Net.Sockets
Imports System.Text.UTF7Encoding
Public Class Form1
Dim open As TcpListener
Dim server As TcpListener
Dim client, host As TcpClient
Dim dati, hdat As NetworkStream
Dim ip As String = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ip = TextBox1.Text
client = New TcpClient
client.Connect(ip, 2101)
If client.Connected = True Then
dati = client.GetStream
MsgBox("Connected", MsgBoxStyle.Information)
Button1.Enabled = False
Timer1.Start()
Else
MsgBox("Error", MsgBoxStyle.Critical)
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If client.Available > 0 Then
Dim t(client.Available - 1) As Byte
dati.Read(t, 0, t.Length)
Dim testo As String = UTF7.GetString(t)
RichTextBox1.Text += vbCrLf & "server : " & testo & vbCrLf
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim t() As Byte = UTF7.GetBytes(TextBox2.Text & vbCrLf)
dati.Write(t, 0, t.Length)
RichTextBox1.Text += vbCrLf & TextBox2.Text & vbCrLf
End Sub
End Class

My Program Freezes when sending a message using gsm shield VB.net

My program is hangs when sending a messsage my code show no error and when i am testing my gsm shield in hyperterminal i can send message and recieve it through my phone using AT commands. But in my program it just freezes.
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class Form1
'connect your mobile/GSM modem to PC,
'then go in device manager and check under ports which COM port has been slected
'if say com1 is there then put com2 in following statement
Dim SMSEngine As New SMSCOMMS("COM4")
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
SMSEngine.SendSMS() 'send the SMS
End Sub
End Class
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
'initialize all values
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 9600
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function SendSMS() As Boolean
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
SMSPort.WriteLine("AT+CSCA="" +639170000130""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS= + TextBox1.text + " & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
SMSPort.WriteLine("+ TextBox1.text +" & vbCrLf & Chr(26)) 'SMS sending
MessageBox.Show(":send")
SMSPort.Close()
End If
End Function
Public Sub Open()
If Not SMSPort.IsOpen Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen Then
SMSPort.Close()
End If
End Sub
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
If Not BackgroundWorker1.IsBusy Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
SMSPort.WriteLine("AT+CSCA="" +639170000130""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS= + TextBox1.text + " & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
SMSPort.WriteLine("+ TextBox1.text +" & vbCrLf & Chr(26)) 'SMS sending
MessageBox.Show(":send")
SMSPort.Close()
End If
End Sub

How to save Received Messages From Gsm Modem to your Mysql Database?

I am trying to save received sms from my modem to MySQL database, and I am using MySQL Workbench for my database.
Here's my functionalities:
1. Auto detect modem
2. Connect modem
3. Send Messages
4. Read Messages
5. Handles (SerialPort Data received)
Here's the Code:1. Auto Detect Modem
'Some Imports
Imports System.Management
Imports System.Threading
Imports System.Text.RegularExpressions
Imports MySql.Data.MySqlClient
Public Class Form1
Dim result() As String
Dim query As String
Dim rcvdata As String = ""
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim ports() As String
ports = Split(ModemsConnected(), "***")
For i As Integer = 0 To ports.Length - 2
ComboBox1.Items.Add(ports(i))
Next
End Sub
Public Function ModemsConnected() As String
Dim modems As String = ""
Try
Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_POTSModem")
For Each queryObj As ManagementObject In searcher.Get()
If queryObj("Status") = "OK" Then
modems = modems & (queryObj("AttachedTo") & " - " & queryObj("Description") & "***")
End If
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
Return ""
End Try
Return modems
End Function
'Show Detected or Available modem
Private Sub ComboBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged
Label1.Text = Trim(Mid(ComboBox1.Text, 1, 5))
End Sub
2. Connect/Disconnect Modem
'button connect
Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
Try
With SerialPort1
.PortName = Label1.Text
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Handshake = IO.Ports.Handshake.None
.RtsEnable = True
.ReceivedBytesThreshold = 1
.NewLine = vbCr
.ReadTimeout = 1000
.Open()
End With
If SerialPort1.IsOpen Then
Label3.Visible = True
btnDisconnect.Visible = True
Label3.Text = "Connected - Port " & Label1.Text & " is used"
Else
Label3.Text = "Got some Error, Check your connection with your Modem."
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Text Messaging")
End Try
End Sub
'button Disconnect
Private Sub btnDisconnect_Click(sender As System.Object, e As System.EventArgs) Handles btnDisconnect.Click
Try
If SerialPort1.IsOpen Then
With SerialPort1
.Close()
.Dispose()
Label1.Visible = False
Label3.Visible = False
btnDisconnect.Visible = False
ListView1.Items.Clear()
End With
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
3. Send Messages
Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
Dim query As String
Try
Connection()
query = "INSERT INTO thesis.tblsentitems (PhoneNumber, message) VALUES('" & txtNumber.Text & "', '" & txtMessage.Text & "')"
sqlcmd = New MySqlCommand(query, conn)
sqlreader = sqlcmd.ExecuteReader
With SerialPort1
.Write("at" & vbCrLf)
Threading.Thread.Sleep(200)
.Write("at+cmgf=1" & vbCrLf)
Threading.Thread.Sleep(200)
.Write("at+cmgs=" & Chr(34) & txtNumber.Text & Chr(34) & vbCrLf)
.Write(txtMessage.Text & Chr(26))
Threading.Thread.Sleep(200)
End With
If rcvdata.ToString.Contains(">") Then
MsgBox("Message Succesfully Sent")
conn.Close()
Else
MsgBox("Got some error!")
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Text Messaging")
End Try
End Sub
4. Read Messages
Private Sub btnReadsms_Click(sender As System.Object, e As System.EventArgs) Handles btnReadsms.Click
Try
With SerialPort1
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CPMS=""SM""" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CMGL=""ALL""" & vbCrLf)
Threading.Thread.Sleep(1000)
'MsgBox(rcvdata.ToString)
readmsg()
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'Save Received message to ListView1
Private Sub readmsg()
Try
Dim lineoftext As String
Dim i As Integer
Dim arytextfile() As String
lineoftext = rcvdata.ToString
arytextfile = Split(lineoftext, "+CMGL", , CompareMethod.Text)
For i = 1 To UBound(arytextfile)
Dim input As String = arytextfile(i)
Dim pattern As String = "(:)|(,"")|("","")"
result = Regex.Split(input, pattern)
Dim concat() As String
With ListView1.Items.Add("null")
'for index
.SubItems.AddRange(New String() {result(2).ToString})
'for status
.SubItems.AddRange(New String() {result(4).ToString})
'for number
Dim my_string, position As String
my_string = result(6)
position = my_string.Length - 2
my_string = my_string.Remove(position, 2)
.SubItems.Add(my_string)
'for date and time
concat = New String() {result(8)}
.SubItems.AddRange(concat)
'for message
Dim lineoftexts As String
Dim arytextfiles() As String
lineoftexts = arytextfile(i)
arytextfiles = Split(lineoftexts, "+32", , CompareMethod.Text)
.SubItems.Add(arytextfiles(1))
End With
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
5. Handles (SerialPort Data received)
Private Sub SerialPort1_datareceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim datain As String = ""
Dim numbytes As Integer = SerialPort1.BytesToRead
For i As Integer = 1 To numbytes
datain &= Chr(SerialPort1.ReadChar)
Next
test(datain)
End Sub
Private Sub test(ByVal indata As String)
rcvdata &= indata
End Sub
Hope someone can Help, please... :/

Why is my form disappearing when I press ENTER?

Good-day,
I'm experiencing a very strange event that just started happening. Whenever I press the ENTER button on my keyboard, I expect the KeyDown event of my textbox to be raised and the corresponding code run. Instead, the form disappears (as if the .Hide() method has been called). When I debug, I see that the code that's supposed to run after the KeyDown event is raised is executing accordingly - but the form just disappears.
I've never encountered this before, so I don't know what to do. Any help would be appreciated. Thanks.
HERE'S THE CODE OF MY FORM:
Imports System.Net
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class FormAdd
#Region "VARIABLE DECLARATIONS CODE"
'FOR MySQL DATABASE USE
Public dbConn As MySqlConnection
'FOR CARD NUMBER FORMATTING
Private CF As New CardFormatter
'FOR CARD ENCRYPTION
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encryptedCard As String
#End Region
#Region "SUB-ROUTINES AND FUNCTIONS"
Private Sub GetDBdata()
Try
If TextBoxAccount.Text = "" Then
MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!")
TextBoxAccount.Focus()
Else
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Dim dbTable As New DataTable
dbAdapter.Fill(dbTable)
If dbTable.Rows.Count > 0 Then
'MessageBox.Show("Customer Account Found!")
Call recordFound()
TextBoxLastName.Text = dbTable.Rows(0).Item("nameLAST")
TextBoxFirstName.Text = dbTable.Rows(0).Item("nameFIRST")
TextBoxSalutation.Text = dbTable.Rows(0).Item("nameSALUTATION")
TextBoxCompanyName.Text = dbTable.Rows(0).Item("nameCOMPANY")
Else
'MessageBox.Show("No Customer Records Found! Please try again!")
Call recordNotFound()
ButtonReset.PerformClick()
End If
dbConn.Close()
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub SetDBData()
Try
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
Dim noCard As Boolean = True
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbQuery As String = "SELECT * FROM cc_master WHERE ccNumber = '" & TextBoxCard.Text & "';"
Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
dbCmd.CommandText = dbQuery
dbCmd.Connection = dbConn
dbAdapter.SelectCommand = dbCmd
dbData = dbCmd.ExecuteReader
While dbData.Read()
If dbData.HasRows() = True Then
MessageBox.Show("This Credit/Debit Card Already Exists! Try Another!")
noCard = False
Else
noCard = True
End If
End While
dbData.Close()
If noCard = True Then
'PERFORM CARD ENCRYPTION
'PERFORM DATABASE SUBMISSION
Dim dbQuery2 As String = "INSERT INTO cc_master (ccType, ccNumber, ccExpireMonth, ccExpireYear, ccZipcode, ccCode, ccAuthorizedUseStart, ccAuthorizedUseEnd, customer_accountNumber)" & _
"VALUES('" & ComboBoxCardType.SelectedItem & "','" & TextBoxCard.Text & "','" & TextBoxExpireMonth.Text & "','" & TextBoxExpireYear.Text & _
"','" & TextBoxZipCode.Text & "','" & TextBoxCVV2.Text & "','" & Format(DateTimePickerStartDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & Format(DateTimePickerEndDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & TextBoxAccount.Text & "');"
Dim dbData2 As MySqlDataReader
Dim dbAdapter2 As New MySqlDataAdapter
Dim dbCmd2 As New MySqlCommand
dbCmd2.CommandText = dbQuery2
dbCmd2.Connection = dbConn
dbAdapter2.SelectCommand = dbCmd2
dbData2 = dbCmd2.ExecuteReader
MessageBox.Show("Credit/Debit Card Information Saved SUCCESSFULLY!")
ButtonReset.PerformClick()
End If
dbConn.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub ResetForm()
TextBoxAccount.Clear()
TextBoxLastName.Clear()
TextBoxFirstName.Clear()
TextBoxSalutation.Clear()
TextBoxCard.Clear()
ComboBoxCardType.SelectedItem = ""
TextBoxCompanyName.Clear()
TextBoxCVV2.Clear()
TextBoxExpireMonth.Clear()
TextBoxExpireYear.Clear()
TextBoxZipCode.Clear()
CheckBoxConfirm.Checked = False
TextBoxAccount.SelectionStart = 0
TextBoxAccount.SelectionLength = Len(TextBoxAccount.Text)
TextBoxAccount.Focus()
GroupBoxInputError.Hide()
LabelInstruction.Show()
GroupBox1.Height = 75
End Sub
Private Sub recordFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Green
LabelError.ForeColor = Color.White
LabelError.Text = "RECORD FOUND!"
GroupBoxInputError.Visible = True
GroupBox1.Height = 345
ButtonReset.Show()
LabelInstruction.Hide()
ComboBoxCardType.Focus()
End Sub
Private Sub recordNotFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Red
LabelError.ForeColor = Color.White
LabelError.Text = "NO RECORD FOUND!"
GroupBoxInputError.Visible = True
End Sub
'Public Sub encryptCard()
' Try
' DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
' DES.Mode = System.Security.Cryptography.CipherMode.ECB
' Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateEncryptor
' Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxCard.Text)
' TextBoxCard.Text = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
' Catch ex As Exception
' MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
' End Try
'End Sub
#End Region
#Region "TOOLSTRIP MENU CONTROL CODE"
Private Sub ExitAltF4ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitAltF4ToolStripMenuItem.Click
End
End Sub
#End Region
#Region "BUTTON CONTROLS CODE"
Private Sub ButtonExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonExit.Click
FormMain.Show()
Me.Close()
End Sub
Private Sub ButtonReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonReset.Click
Call ResetForm()
End Sub
Private Sub ButtonSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSubmit.Click
Call SetDBData()
Call ResetForm()
End Sub
Private Sub ButtonEncrypt_Click(sender As System.Object, e As System.EventArgs) Handles ButtonEncrypt.Click
End Sub
#End Region
#Region "FORM CONTROLS CODE"
Private Sub FormAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
TextBoxAccount.Focus()
Me.KeyPreview = True
Timer1.Enabled = True
Timer1.Interval = 1
GroupBoxInputError.Hide()
ButtonSubmit.Hide()
ButtonReset.Hide()
GroupBox1.Height = 75
'LabelFooter.Text = "Welcome " & FormLogin.TextBoxUsername.Text() & " | Timestamp: " & Date.Now.ToString
Try
LabelIP.Text = "IP: " & Dns.GetHostEntry(Dns.GetHostName).AddressList(0).ToString
Catch ex As Exception
End Try
'Populate the Card Type combobox with the list of card types from the CardFormatter class
ComboBoxCardType.Items.AddRange(CF.GetCardNames.ToArray)
End Sub
#End Region
#Region "TEXTBOX CONTROLS CODE"
Private Sub TextBoxCard_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.GotFocus
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
Me.Refresh()
End Sub
Private Sub TextBoxCard_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.LostFocus
'//CARD VALIDATION//
' This code will check whether the card is a valid number or not. It doesn't check to see if the card is active.
' The code calls on the creditcard function stored in MyModules.vb
Try
If creditcard(TextBoxCard.Text) Then
'MsgBox("Card is Valid")
TextBoxCard.BackColor = Color.GreenYellow
TextBoxCard.ForeColor = Color.Black
GroupBoxInputError.Visible = False
TextBoxCard.Text = CF.GetFormattedString(ComboBoxCardType.Text, TextBoxCard.Text)
Me.Refresh()
Else
BWErrorNotice.RunWorkerAsync()
'MsgBox("Invalid Card")
GroupBoxInputError.Visible = True
TextBoxCard.Focus()
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBoxAccount_GotFocus(sender As Object, e As System.EventArgs) Handles TextBoxAccount.GotFocus
TextBoxAccount.SelectAll()
End Sub
Private Sub TextBoxAccount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxAccount.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
If TextBoxAccount.Text <> "" Then
Call GetDBdata()
Else
MsgBox("You must enter an account number!", MsgBoxStyle.Exclamation, "ATTENTION PLEASE!")
TextBoxAccount.Focus()
End If
End If
'If e.KeyCode = Keys.Enter Then
' e.Handled = True
' SendKeys.Send("{Tab}")
'End If
End Sub
Private Sub TextBoxCard_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBoxCard.MouseClick
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End Sub
#End Region
#Region "OTHER/MISCELLANEOUS CONTROLS CODE"
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LabelDateTime.Text = DateTime.Now
End Sub
Private Sub BWErrorNotice_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BWErrorNotice.DoWork
Do While Not creditcard(TextBoxCard.Text)
LabelError.BackColor = Color.Black
System.Threading.Thread.Sleep(500)
LabelError.BackColor = Color.Red
System.Threading.Thread.Sleep(500)
Loop
BWErrorNotice.CancelAsync()
End Sub
Private Sub CheckBoxConfirm_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxConfirm.CheckedChanged
If CheckBoxConfirm.Checked = True Then
ButtonSubmit.Show()
Else
ButtonSubmit.Hide()
End If
End Sub
#End Region
End Class
Although what follows will not likely solve the form disappearance problem, it will resolve a downstream issue:
In GetDBData(), you are assigning accountNumber to the value of TextBoxAcount.Text, which must be enclosed with quotes unless you employ a parameter which I strongly recommend you get in the habit of doing.
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Parameters offer a number of benefits including implicit type conversions, injection attack prevention, and will sometimes even cure unexpected behaviors.
I figured out the problem. I was calling Dispose() at the end of my GetDBData() function - so the form was getting disposed before execution returned back to the TextBox. I deleted it and all is well again.