Detect response from Modem? - vb.net

I'm working with a Teltonika G10 GSM modem and wrote up a basic program to send out SMS. I put a 1.5 second timer between each AT command to allow the modem to simulate the wait for the "OK" from the modem. This works for now but I'd rather use a branching statement wait for an actual response such as "OK" or "ERROR" rather than using a timer.
SerialPort1.Write("AT+CMGD=1,4" & vbCrLf)
Thread.Sleep(1250)
SerialPort1.Write("AT+CMGF=1" & vbCrLf)
Thread.Sleep(1250)
SerialPort1.Write("AT+CMGS=" & Chr(34) & "3475558223" & Chr(34) & vbCrLf)
Thread.Sleep(1250)
SerialPort1.Write(":|" & Chr(26))

I was new to programming with AT commands and had spent a good deal of time with Putty to get an understanding of it. Hans Passant suggeested to use .ReadLine() and it's worked great.
Below is a sample of code that's worked great. It basically submits a command to the modem and will only continue if the modem responds with an "OK".
If modem.IsOpen() Then
modem.Write("AT+CMGD=" & Chr(34) & "ALL" & Chr(34) & vbCrLf) 'deletes last received message
'Sets Modem to Text
While (modem.ReadLine().ToString <> "OK")
modem.Write("AT+CMGF=1" & vbCrLf)
End While
While (modem.ReadLine().ToString <> "OK")
modem.Write("AT+CSMP=17,167,0,0" & vbCrLf)
End While
While (modem.ReadLine().ToString <> "OK")
modem.Write("AT+CNMI=1,1,0,0,0" & vbCrLf)
End While
End If

Related

Send email containing text and ics file to Outlook

I want to send an email containing some text in the body and a .ics calendar file attachment. This is some test code:
Dim strAppointment As New System.Text.StringBuilder
strAppointment.Append("BEGIN:VCALENDAR" & vbCrLf)
strAppointment.Append("VERSION:2.0" & vbCrLf)
strAppointment.Append("CALSCALE:GREGORIAN" & vbCrLf)
strAppointment.Append("PRODID:ExcelDent" & vbCrLf)
strAppointment.Append("METHOD:REQUEST" & vbCrLf)
strAppointment.Append("BEGIN:VEVENT" & vbCrLf)
strAppointment.Append("DTSTART:20230219T140000Z" & vbCrLf)
strAppointment.Append("DTEND:20230219T170000Z" & vbCrLf)
strAppointment.Append("DTSTAMP:" & Now.ToUniversalTime().ToString("yyyyMMddTHHmmssZ" & vbCrLf))
strAppointment.Append("SUMMARY:Dental Appointment" & vbCrLf)
strAppointment.Append("DESCRIPTION:Appointment with Dr Doe" & vbCrLf)
strAppointment.Append("LOCATION:8888 address of the clinic" & vbCrLf)
strAppointment.Append("ORGANIZER;CN=DentalOffice1:MAILTO:me#me.com" & vbCrLf)
strAppointment.Append("ATTENDEE;PARTSTAT=ACCEPTED;RSVP=False;CN=Mike;ROLE=REQ-PARTICIPANT:MAILTO:TheRecipient#whatever.com" & vbCrLf)
strAppointment.Append("UID:MyTest1" & vbCrLf)
strAppointment.Append("SEQUENCE:1" & vbCrLf)
strAppointment.Append("STATUS:CONFIRMED" & vbCrLf)
strAppointment.Append("END:VEVENT" & vbCrLf)
strAppointment.Append("END:VCALENDAR" & vbCrLf)
Dim strHeader As New System.Text.StringBuilder
strHeader.Append("Content-Type: text/calendar; charset=utf-8; method=REQUEST; name=invite.ics" & vbCrLf)
strHeader.Append("Content-Transfer-Encoding: base64" & vbCrLf)
strHeader.Append("Content-Disposition: attachment; filename=invite.ics" & vbCrLf)
Sending the ICS file via email to gmail and Yahoo for instance is no issue as both are recognizing and processing the ICS file correctly. But when the email is received on an Outlook application, all we see is the ICS file in attachment, no email body whatsoever. Sure if the recipient clicks on the attachment, the appointment gets added to the calendar. But the point is that the email looks really unprofessional and downright fishy. I've seen a lot of posts which discuss this topic but I haven't seen a solution. It would be great to compare to a properly formatted email which has been proven to work. If this issue rings a bell for anyone, I'd really appreciate getting some pointers.
Thanks everyone !

DataGridView - Data added does not stay after closing application

I have created a VB windows form Application with text boxes and a datagridview.
The idea is for the user to enter information onto the text boxes, and then click a button to save to the grid view. This works fine, but when closing the application and reopening the data is gone.
The below code is what i use to save the data to the grid view.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim rnum As Integer = DataGridView1.Rows.Add()
If Me.CheckBox1.Checked = True Then
Clipboard.SetText("Situation:" & vbNewLine & Me.TextBox1.Text & vbNewLine & vbNewLine & "Actions:" & vbNewLine & Me.TextBox2.Text & vbNewLine & vbNewLine & "Next Steps:" & vbNewLine & Me.TextBox3.Text & vbNewLine & vbNewLine & "Notes:" & vbNewLine & Me.TextBox4.Text)
Else
Clipboard.SetText("Situation:" & vbNewLine & Me.TextBox1.Text & vbNewLine & vbNewLine & "Actions:" & vbNewLine & Me.TextBox2.Text & vbNewLine & vbNewLine & "Next Steps:" & vbNewLine & Me.TextBox3.Text)
End If
DataGridView1.Rows.Item(rnum).Cells("Situation").Value = Me.TextBox1.Text
DataGridView1.Rows.Item(rnum).Cells("Actions").Value = Me.TextBox2.Text
DataGridView1.Rows.Item(rnum).Cells("NextSteps").Value = Me.TextBox3.Text
DataGridView1.Rows.Item(rnum).Cells("SupportingDocuments").Value = Me.TextBox4.Text
MsgBox("Added to Clipboard")
End Sub
The application is used by different users on different machine, so i want the gridview to have saved what that individual user has added.
I know im missing something easy, like adding a dataset but wouldnt this have to be on a static location used by everyone? And i also looked into xml files but cannot seem to find what im looking for.
Any help would be greatly appreciated.
All you have to do is to select your database in Project Explorer and navigate to its properties. In its properties, set "Copy to Output folder = Copy if Newer"
After trying to work around databases, but only seeming to get them static. I worked on using code to create xml files on the user profile, and then loading them.
This Link helped me alot

Sending meeting requests using ical through outlook

Here is my dilemma. I have a vb.net application for requesting time using an asset. The user submits a request (can contain required and optional users), then an approver has to approve it. When it is approved, I want to send a meeting request. I can't do it using outlook code since it won't let me change the organizer. If I try to send it using outlook.application > outlook.olitemtype.olappointmentitem or whatever it is, it will default the organizer to the person sending the meeting request, which in this case is the approver, which I don't want. So I think I am left with trying to send an ical. This is where I am having issues. I can't use smtpclient to create the email and send it using the proper content-type, etc. I have to send it using outlook. So I create an ics file and add it as an attachment. I am not sure the difference between METHOD:PUBLISH and METHOD:REQUEST. All the searches I've have done say I should use method:request, but when i open the ICS file, it doesn't give me the options to accept, etc. It doesn't add to my calendar. I want the ability to be able to update and cancel the meeting as well, which I think I know how to do with uid, sequence, etc. I've done searches and just can't get to where I need to be. It looks like the best option is to use smtpclient to create the mail message where you add the headers and ical stuff, but I can't do that, is there a way to it using outlook?
If someone can help point me in the right direction, I would greatly appreciate it.
Here is my current code:
Dim msg As MailMessage = New MailMessage
msg.From = New MailAddress(br.requesting_user_email)
msg.To.Add(New MailAddress(br.requesting_user_email))
msg.Subject = variables.UserInfo.last_name & ", " + variables.UserInfo.first_name & " has approved your request through the Bench Scheduler."
Dim bodytxt As String = "User: " & variables.UserInfo.last_name & ", " + variables.UserInfo.first_name & vbLf & "5+2: " + variables.UserInfo.username & vbLf & vbLf
bodytxt += "Has approved your bench request for " & br.program_name & " - " & br.project_name & "." & vbLf & vbLf
bodytxt += "Start: " & br.start_time & vbLf & "End: " & br.end_time & vbLf
bodytxt += "Bench: " & br.bench_name & vbLf & "Priority: " & br.priority & vbLf & "Purpose: " & br.objective & vbLf & vbLf
bodytxt += "Request Notes: " & br.notes & vbLf & vbLf
bodytxt += vbLf & vbLf & vbLf & "This email was automatically generated by Bench Scheduler. You may respond to this email."
msg.Body = bodytxt
Dim str As StringBuilder = New StringBuilder
str.AppendLine("BEGIN:VCALENDAR")
str.AppendLine("PRODID:-//Microsoft Corporation//Outlook 15.0 MIMEDIR//EN")
str.AppendLine("VERSION:2.0")
If cancel Then
str.AppendLine("METHOD:CANCEL")
Else
str.AppendLine("METHOD:REQUEST")
End If
str.AppendLine("BEGIN:VEVENT")
str.AppendLine("X-MS-OLK-FORCEINSPECTOROPEN:TRUE")
str.AppendLine("BEGIN:VTIMEZONE")
str.AppendLine("TZID:Eastern Standard Time")
str.AppendLine("BEGIN:STANDARD")
str.AppendLine("DTSTART:16011104T020000")
str.AppendLine("RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=11")
str.AppendLine("TZOFFSETFROM:-0400")
str.AppendLine("TZOFFSETTO:-0500")
str.AppendLine("END:STANDARD")
str.AppendLine("BEGIN:DAYLIGHT")
str.AppendLine("DTSTART:16010311T020000")
str.AppendLine("RRULE:FREQ=YEARLY;BYDAY=2SU;BYMONTH=3")
str.AppendLine("TZOFFSETFROM:-0500")
str.AppendLine("TZOFFSETTO:-0400")
str.AppendLine("END:DAYLIGHT")
str.AppendLine("END:VTIMEZONE")
Dim dt As New DataTable
Dim ta As New BSDataSetTableAdapters.getUserRequestTableAdapter
dt = ta.GetData(br.request_id, "T")
For Each row As DataRow In dt.Rows
If row("type") = "Required" Then
str.AppendLine(String.Format("ATTENDEE;CN='{0}';RSVP=TRUE:mailto:{1}", row("username"), row("email")))
ElseIf row("type") = "Optional" Then
str.AppendLine(String.Format("ATTENDEE;CN='{0}';ROLE=OPT-PARTICIPANT;RSVP=TRUE:mailto:{1}", row("username"), row("email")))
End If
Next
str.AppendLine("CLASS:PUBLIC")
str.AppendLine("CREATED:" & Format(Date.Now, "yyyyMMddTHHmmssZ"))
str.AppendLine(String.Format("DESCRIPTION:{0}", br.objective))
str.AppendLine("DTEND;TZID=" & """" & "Eastern Standard Time" & """" & ":" & Format(CDate(br.end_time), "yyyyMMddTHHmmss"))
str.AppendLine("DTSTAMP:" & Format(Date.Now, "yyyyMMddTHHmmssZ"))
str.AppendLine("DTSTART;TZID=" & """" & "Eastern Standard Time" & """" & ":" & Format(CDate(br.start_time), "yyyyMMddTHHmmss"))
str.AppendLine(String.Format("LOCATION:{0}", br.bench_name))
str.AppendLine(String.Format("ORGANIZER;CN='" & br.requesting_username & "':mailto:" & br.requesting_user_email))
str.AppendLine("PRIORITY:5")
str.AppendLine("SEQUENCE:0")
str.AppendLine(String.Format("SUMMARY;LANGUAGE=en-us:{0}", "Approved Bench Request (ID-" & br.request_id & "): " & br.program_name & "-" & br.project_name & "-" & br.activity))
str.AppendLine("TRANSP:OPAQUE")
str.AppendLine(String.Format("UID:{0}", br.uid))
str.AppendLine(String.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", br.objective))
str.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY")
str.AppendLine("X-MICROSOFT-CDO-IMPORTANCE:1")
str.AppendLine("X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY")
str.AppendLine("X-MICROSOFT-DISALLOW-COUNTER:FALSE")
str.AppendLine("X-MS-OLK-AUTOFILLLOCATION:FALSE")
str.AppendLine("X-MS-OLK-CONFTYPE:0")
str.AppendLine("BEGIN:VALARM")
str.AppendLine("TRIGGER:-PT30M")
str.AppendLine("ACTION:DISPLAY")
str.AppendLine("DESCRIPTION:Reminder")
str.AppendLine("END:VALARM")
str.AppendLine("END:VEVENT")
str.AppendLine("END:VCALENDAR")
Dim smtpclient As SmtpClient = New SmtpClient
smtpclient.Host = "replaced for privacy"
smtpclient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
Dim contype As System.Net.Mime.ContentType = New System.Net.Mime.ContentType("text/calendar")
contype.Parameters.Add("method", "REQUEST")
contype.Parameters.Add("name", "Meeting.ics")
Dim avcal As AlternateView = AlternateView.CreateAlternateViewFromString(str.ToString, contype)
msg.AlternateViews.Add(avcal)
smtpclient.Send(msg)

Word in message box appears in a different line

I use the following VBA to open a message box:
Sub Message()
MsgBox ("Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file with all sheets visible will be saved on your desktop and opened. You can immediately start working with this file.")
End Sub
All this works fine.
However, as you can see in the screenshot the word "file" goes in a different line. Is it possible to format the messagebox or change the VBA code so the word "file" does not appear in a different line?
It depends on the resolution of the PC of the user. In my case I even get it like this:
If you want to control the lines, then you should write a custom form. There you would have much better control over the display, and if you play a bit with its properties, you would mimic exactly the MsgBox():
Some sample code, Label1 is a label element:
Private Sub UserForm_Initialize()
Me.Label1 = "Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file with all sheets visible will be saved on your desktop and opened." & _
vbCrLf & "You can immediately start working with this file."
End Sub
Perhaps adjust your code with line breaks to suit. For example:
Sub Message()
MsgBox ("Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file" _
& vbCr & " " _
& vbCr & "with all sheets visible will be saved on your desktop and opened." _
& vbCr & " " _
& vbCr & "You can immediately start working with this file.")
End Sub

Image not received, sent via mms using VBA, Twilio and Microsoft ACCESS

I need to send a image from my pc in a text message using Twilio and Microsoft Access.
I was able to successfully send a text message via Microsoft Access. However, the image wasn't sent. I found a parameter called "mediaURL". I am trying to have mediaURL refer to a image on my pc ("d:\imagefolder").
Has anyone been able to do this. Here is my code to send the text message.
Dim MessageUrl As String
Dim FromURLEncode As String
Dim ToURLEncode As String
Dim imageURL As String
On Error GoTo Error_Handler
' setup the URL
MessageUrl = BASEURL & "/2010-04-01/Accounts/" & ACCOUNTSID & "/Messages"
imageURL = "d:\imagefolder\mypicture.png"
' setup the request and authorization
Dim http As MSXML2.XMLHTTP60
Set http = New MSXML2.XMLHTTP60
http.Open "POST", MessageUrl, False, ACCOUNTSID, AUTHTOKEN
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
Dim postData As String
postData = "From=" & fromNumber _
& "&To=" & toNumber _
& "&Body=" & body _
& "&MediaURL=" & imageURL
Debug.Print postData
' send the POST data
http.send postData
' optionally write out the response if you need to check if it worked
Debug.Print http.responseText
If http.Status = 201 Then
ElseIf http.Status = 400 Then
MsgBox "Failed with error# " & _
http.Status & _
" " & http.statusText & vbCrLf & vbCrLf & _
http.responseText
ElseIf http.Status = 401 Then
MsgBox "Failed with error# " & http.Status & _
" " & http.statusText & vbCrLf & vbCrLf
Else
MsgBox "Failed with error# " & http.Status & _
" " & http.statusText
End If
Exit_Procedure:
On Error Resume Next
' clean up
Set http = Nothing
Exit Function
Error_Handler:
Select Case Err.Number
Case NOINTERNETAVAILABLE
MsgBox "Connection to the internet cannot be made or " & _
"Twilio website address is wrong"
Case Else
MsgBox "Error: " & Err.Number & "; Description: " & Err.Description
Resume Exit_Procedure
Resume
End Select
I was finally able to send text messages with images by using MediaUrl. My Code was using MediaURL. It has to be exactly "MediaUrl". Once, I figured that out, I have been able to send text messages with images.
Twilio developer evangelist here.
As Thomas G answered in a comment, your problem is that the image is on your computer. The URL needs to be available to Twilio.
You will need to upload the image to a server, either your own or a public service, and then using the for that server.
Check out the documentation on sending MMS with Twilio for more details.