VB.Net, sending emails out uniquely - vb.net

im an intern at a packaging company and we have an interface that sends out summary emails out to several people on mondays. There are about 70 groups that the code sees. every group has a specific section that people enter a log in. if you are a recipient in that group on monday you will recieve a summary email of all the active logs entered for groups you are in. if user A is in group 1 and 2, he or she should recieve 2 emails with active logs pretaining to those 2 groups. Problem is he or she is signed up in all 70 groups and if there are only 2 active logs from group 1 and 2 she recieves 70 identical emails with summaries containing active logs for those 2 groups. here is the code.
Private Sub SendEmails()
Try
Dim message As New PCA.Core.Messaging.Message(PCA.Core.Messaging.MessageTypes.JumperLog)
'Dim distLists As List(Of PCA.Core.DistributionList) = (From r In Trident.Core.Globals.TridentApp.ApplicationCache.DistributionLists.DistributionLists Where r.ID.Contains("JL_")).ToList
Dim distLists As List(Of PCA.Core.DistributionList) = (From r In PCA.Core.DistributionList.GetDistributionLists Where r.Id.Contains("JL_")).ToList
For Each distlist As PCA.Core.DistributionList In distLists
Dim recipients As System.Collections.Generic.List(Of Trident.Core.User)
recipients = Trident.Core.Core.Message.GetTridentDistributionList("TRIMAINT", distlist.Id)
If recipients.Count > 0 Then
message.Recipients.AddRange(recipients)
End If
Next
If message.Recipients.Count = 0 Then Exit Sub
Dim ds As New DataSet
Dim dbConn As New Trident.Core.DBConnection
Dim sql As String = "SELECT * FROM ***.Maintenance.JumperLogs WHERE Removed <> 1 AND Plant = #Plant ORDER BY InstallDate "
dbConn("#Plant") = Trident.Core.Globals.TridentApp.DefaultPlant.Plant
Dim tmpJL As Trident.Objects.Maintenance.JumperLogs.JumperLog
message.Subject = "Jumper Log - Active Jumpers"
ds = dbConn.FillDataSet(sql)
If ds.Tables(0).Rows.Count = 0 Then Exit Sub
For Each dr As DataRow In ds.Tables(0).Rows
tmpJL = New Trident.Objects.Maintenance.JumperLogs.JumperLog(dr)
message.Body += "Jumper Log # " & tmpJL.LogId & " - Installed: " & tmpJL.InstallDate & vbCrLf
message.Body += "Mill: " & Trident.Core.Globals.TridentApp.DefaultPlant.Description & vbCrLf
message.Body += "Facility: " & tmpJL.FacilityObject.Description & vbCrLf
If Not tmpJL.MachineAreaObject Is Nothing Then
message.Body += "Area: " & tmpJL.MachineAreaObject.Description & vbCrLf
End If
If Not tmpJL.LocationObject Is Nothing Then
message.Body += "Location: " & tmpJL.LocationObject.Description & vbCrLf
End If
If Not tmpJL.EquipmentObject Is Nothing Then
message.Body += "Equipment: " & tmpJL.EquipmentObject.Description & vbCrLf
End If
message.Body += "Installed By: " & tmpJL.InstalledBy.FullName & vbCrLf
'message.Body += "Install Date: " & tmpJL.InstallDate & vbCrLf
message.Body += "Tag: " & tmpJL.Tag & vbCrLf
message.Body += "Tag Attached To: " & tmpJL.TagAttachedTo & vbCrLf
message.Body += "Work Order: " & tmpJL.WorkOrder & vbCrLf
message.Body += vbCrLf
message.Body += "Reason: " & tmpJL.Reasons.ToUpper & vbCrLf
message.Body += vbCrLf
message.Body += "---------------------------------------------------------------------------------------------------------------------------------------------------" & vbCrLf
message.Body += vbCrLf
Next
message.Send()
Catch ex As Exception
Throw New PCA.Core.Exceptions.PCAErrorException(ex)
End Try
End Sub
Now i think that modifying the if statement that initializes the range, might do it?
Ok a user that is in "JL_001" group recieved a summary email on monday that JL_001 group is label by facilities and this one is called #1paper machine" since. he is only in one group that paper machine group he got one email with only one active jumperlog which happens to be from his facility (#1 paper Machine.) Now this is the issue, there is a group of users that have all been added to groups "JL_001 to JL_070". since there was only one acitve log entered that previous week on monday they should only get one summary email because they are also in the #1 paper machine facility group(JL_001). they shouldnt receive anything else from any other group because there were no active logs from those groups yet they recieved 70 emails of that same summary pretaining to JL_001. Does this help clear it up?

You should be building the message body for each recipient, and then send your messages by recipient instead of group. You could do this by following these steps:
Create a global list of recipients
Get the list of recipients a group
Loop through the recipients list. If the recipient already exists, append the additional message body to their record. If not, create a new record in the global list.
Repeat steps 2-3 through all groups.
Loop through the global list of recipients, and send one message per recipient.

Related

Multiple sms send in AT commands VB.NET

I'm trying to send many or bulk sms using AT Command. I try send all number inside the datagrid but only first number is sending.
this is my code
Dim sql As New MySqlDataAdapter("select StudentID, StudentName,StudentContact, DueDate FROM issue inner join student on student.StudentID = issue.Student ", conn)
Dim ds As New DataSet
sql.Fill(ds, 0)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim wholenum As String
Dim wholesms As String
wholenum = ds.Tables(0).Rows(i).Item(2).ToString
wholesms = "Hello " & ds.Tables(0).Rows(i).Item(1).ToString & ", this is your Due Date " & ds.Tables(0).Rows(i).Item(3).ToString & " pls return it on your due date"
If SerialPort1.IsOpen Then
Try
With SerialPort1
.Write("AT" & vbCrLf)
.Write("AT+CMGF=1" & vbCrLf)
.Write("AT+CMGS=" & Chr(34) & wholenum & Chr(34) & vbCrLf)
.Write(wholesms & Chr(26))
MsgBox("Success sa SEND")
'update one
'Call ConnectDatabase()
'com = New MySqlCommand("UPDATE issue SET Sent='1' ", conn)
'com.ExecuteNonQuery()
'Call DisconnectDatabase()
End With
Catch ex As Exception
MsgBox("Bad Signal or No load")
End Try
Else
MsgBox("Pls insert a modem")
End If
I think the looping is working 'cuz it apppears the successful message of how many inside in the datagrid view. But it only send the first number.
You need to fix your AT command handling significantly. First of all you need to read and parse everything the modem sends back to you after sending a AT command line (which by the way should be terminated with just "\r" and not vbCrLf).
You should never start sending a new command line before you have received the Final result code. And for AT+CMGS specifically you should never send the sms payload before you have received the "\r\n >" prefix.
These issues are covered in this and this answer. But the very first thing you should to is to read all of the text in chapter 5 in the V.250 specification. It is a really important document when working with AT commands.

Asp.net SQL How to stop the user reserving a 'place' where there are no available seats

I currently have it so that a user can reserve a seat, and the number in the database reduces by one via an SQL query. However, I can't figure out how to stop the user from reserving a seat when the number is at 0.
UPDATE Route
SET NumOfSeats = NumOfSeats - 1
WHERE ([Origin] = #Origin) and destination = #destination and DepartTime=#time
When the number of seats is at '0', the user is still able to reserve a place therefore bringing number of seats to '-1'.
Any help would be appreciated!
You could add the condition that NumOfSeats must be > 0:
Dim sql = "UPDATE Route " & vbCrLf & _
"NumOfSeats = NumOfSeats - 1 " & vbCrLf & _
"WHERE ([Origin] = #Origin) and destination = #destination and DepartTime=#time " & vbCrLf & _
"AND NumOfSeats > 0"
Using con = New SqlConnection("Connection...")
Using command As New SqlCommand(sql, con)
command.Parameters.Add("#Origin", SqlDbType.Int).Value = Origin
command.Parameters.Add("#destination", SqlDbType.Int).Value = destination
command.Parameters.Add("#destination", SqlDbType.DateTime).Value = time
con.Open()
Dim numUpdated As Int32 = command.ExecuteNonQuery()
If numUpdated = 0 Then
' tell user that no seat is available '
End If
End Using
End Using

items in listview load not showing

i have a problem in viewing items in listview
this is my code
rs.Open("select tableStudentRecords.*, tableTransaction.*, tablePayments.* from tableStudentRecords, tableTransaction , tablePayments" & _
" where tableStudentRecords.studnum = tableTransaction.studnum and tablePayments.psitscode = tableTransaction.psitscode", con, 3, 3)
Dim i As Integer = 0
With lvPaymentRecords
Do Until rec.EOF
.Items.Add(rec("tableTransaction.studnum").Value)
x = rec("sname").Value & ", " & rec("fname").Value & " " & rec("mi").Value & " " & rec("ext").Value
.Items(i).SubItems.Add(x)
lvPaymentRecords.Items(i).SubItems.Add(rec("sem").Value)
.Items(i).SubItems.Add(rec("sy").Value)
.Items(i).SubItems.Add(rec("total").Value)
i = i + 1
rec.MoveNext()
Loop
End With
rec.Close()
con.Close()
the thing is, items wont appear in listview, i dont know what is the cause,
tableStudentRecords and tablePayments are both PRIMARY keys,
here is the database relationships
(im sorry i cant post the image due to less reputation)
tableStudentRecords _____ tableTransaction _____ tablePAyments
-studnum _____________ -psitscode _____________-psitscode
-sname _______________ -studnum ____________-sem
-fname ________________ -sy __________________-payname
-gndr __________________-total _______________-amount
i only need to view the sem from tablePayments in listview load,
You must declare a ListViewItem variable. The codes should be
Dim lpRec As ListViewItem
With lvPaymentRecords
Do Until rec.EOF
lpRec=.Items.Add(rec("tableTransaction.studnum").Value)
x = rec("sname").Value & ", " & rec("fname").Value & " " & rec("mi").Value & " " & rec("ext").Value
lpRec.SubItems.Add(x)
lpRec.SubItems.Add(rec("sem").Value)
lpRec.Items(i).SubItems.Add(rec("sy").Value)
lpRec.Items(i).SubItems.Add(rec("total").Value)
i = i + 1
rec.MoveNext()
Loop
End With
rec.Close()
con.Close()
Hope it can help you.

VB.NET Database Retrieval

I have a VB.NET application that has instant messaging-like functionality with a database. It can retrieve the values just fine, but the problem is the formatting isnt coming out right. I want the format to be as follows:
Sender: Message
(so...)
David: Hey guys
What I've tried below doesn't get me the result I'm looking for, it just prints the sender at the top of the rich textbox in my application and the message at the bottom, does anyone have any ideas?
'-------------------Retreives the message-------------------------------------------------------------
Dim sqlStr As String = "SELECT * FROM dojodb.chats"
Dim chatcommand As New MySqlCommand(sqlStr, MysqlConn)
Dim rdr As MySqlDataReader = chatcommand.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(rdr)
'-------For every row, print the message, skip a line, and add 1 so it goes to next msg-- ------
For i As Integer = 0 To tbl.Rows.Count - 1
rowIndex = i
strSender &= CStr(tbl.Rows(rowIndex)("Sender")) & vbNewLine
strMessage &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
strOutPut = strSender + ": " + strMessage
Next
txtGroupChat.Text = strOutPut
'Keeps the richtextbox scrolled to the bottom so that most recent msg is always shown
txtGroupChat.SelectionStart = txtGroupChat.Text.Length
txtGroupChat.ScrollToCaret()
strOutPut = "" 'clearing the string so that it does not print out duplicate info next time
strSender = ""
strMessage = ""
'-------------------------End Retrive---------------------------------------
I feel a bit embarrassed posting this, but...
strSender = CStr(tbl.Rows(rowIndex)("Sender")) & ": "
strMessage = CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
strOutPut &= strSender & strMessage
What do you think vbNewLine does? Also, be careful of &=

"Pinging" an email address using VB.Net coding

Is there a way in VB.Net to "Ping" an email address to see if that email is a real one that does not give any errors?
If yes, can you show what the VB.Net coding looks like to implement this?
I plan to use this in an app that requires the Customer email and it would be nice to validate it as the call taker enters it into a form before saving the Customer details.
Here is the code we are using to send an email promotion to all of the customers in our customer table:
Private Sub RibbonButtonSendTestEmail_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButtonSendTestEmail.Click
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
Dim strSqlStatement As String = "Select CustomerName, Email " & _
"From Customers "
Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection)
With objSqlCommand
' Open the SqlConnection before executing the query.
'---------------------------------------------------
Cursor = Cursors.WaitCursor
ObjConnection.Open()
Dim objDataReader As SqlDataReader = .ExecuteReader()
' Go through all the customers and send out the promotion emails.
'----------------------------------------------------------------
If objDataReader.HasRows Then
SmtpServer.Host = TextBoxSMTPServer.Text
SmtpServer.Port = TextBoxPort.Text
If TextBoxUseSSL.Text = "Yes" Then
SmtpServer.EnableSsl = True
Else
SmtpServer.EnableSsl = False
End If
If TextBoxUseDefaultCredentials.Text = "Yes" Then
SmtpServer.UseDefaultCredentials = True
Else
SmtpServer.UseDefaultCredentials = False
End If
SmtpServer.Credentials = New Net.NetworkCredential(TextBoxUserName.Text, TextBoxPassword.Text)
While objDataReader.Read()
Try
mail.To.Add(objDataReader("Email").ToString)
mail.From = New MailAddress(TextBoxEmailFrom.Text)
mail.Subject = "Promotion: " & TextBoxID.Text
mail.Body = "Dear " & objDataReader("CustomerName") & "," & vbCrLf & vbCrLf & TextBoxPromotionBodyText.Text
SmtpServer.Send(mail)
Catch exSMTP As SmtpException
MessageBox.Show("Sorry, I could not send an email for: " & _
vbCrLf & objDataReader("CustomerName") & "." & vbCrLf & _
"Please make sure it is correct.", _
"Error")
Catch exFormat As FormatException
MessageBox.Show("Sorry, this customer's email is not properly formatted: " & _
vbCrLf & objDataReader("CustomerName") & "." & vbCrLf & _
"Please make sure it is correct.", _
"Error")
End Try
End While
LabelEmail.Text = "Sent email promotions to the customers."
End If
objDataReader.Close()
ObjConnection.Close()
Cursor = Cursors.Default
End With ' objSqlCommand
End Using ' objSqlCommand
End Sub
Yes it's perfectly possible:
1 DNS Lookup the MX records for the domain
There may be multiples, you can pick anyone, although technically the one with the lowest preference indicator is the prefered one.
2 TCP Connect to the mail server (port 25)
Say hello: HELO
Identify yourself: mail from:<test#example.com>
Say who you're writing to: rcpt to<testaddress#example.com>
At this point the server will reply with a response, you'll get an OK or a 550 error with a message (like: The email account that you tried to reach does not exist)
Disconnect and the message will be dropped.
But dude, you want the VB code to do this? You just need a DNS talking piece and TCP connection building piece (or likely there are some SMTP libraries out there that'll do all this for you - or provide you with inspiration to figure it out yourself). Don't forget you can probably find a C# code example that does it and use Visual Studio's conversion tool to switch it to VB.
Note
Many domains have black holes/catch alls... the former will accept any email address and just delete it if it's invalid, the latter will accept any email address and forward them to a central account (no guarantees as to what happens then... sell the sender's address to spammers?) In both cases you won't get the 550 message, so you can never be certain.
There most reliable way to do this is to send a test email and have the recipient verify receipt by clicking on a link, which you then read and mark the email as active.
You should do primitive checks on the syntax of the email using regular expressions, but beyond that the most reliable way to validate an email is to attempt delivery and confirm the receipt.