VB net. Morse code translator: cut correct signs using Mid() and match them with the letter - vb.net

I am trying to translate Morse code into text in VB.net.
Using below code, some of the letters in the text stays untranslated. I believe the problem is with "oddel" which should indicated how many letters should be cut in Mid(morsC, i, oddel), while selecting the case.
Code should be able to translate this >…./ ./ .-../ .-../ ---/< into Hello.
What's weird is that while translating "Hello", first letter "H" is correctly cut as " ..../" but it's not matched with the Case "H"
'Hello = …./ ./ .-../ .-../ ---/
Sub EE15a()
Dim veta As String, morsCod As String, st As String
morsCod = InputBox("Enter the morse code.")
veta = morsCodF(morsCod)
st = "Preklad dle funkce " + Chr(10) + veta + Chr(10)
MsgBox(st)
End Sub
Function morsCodF(morsC As String) As String
Dim pismeno As String, znak As String
Dim i As Integer, j As Integer, oddel As Integer
Dim nasel As Boolean
znak = "/"
morsC = Trim(morsC)
j = 1
For i = 1 To (morsC.Length)
i = j
Do
If Mid(morsC, j, 1) = znak Then
oddel = j - oddel
nasel = True
Exit Do
End If
j = j + 1
Loop Until nasel = True Or j > (morsC.Length)
If i = 1 Then
pismeno = (" " + Mid(morsC, i, oddel))
Else
pismeno = Mid(morsC, i, oddel)
End If
Select Case pismeno '" ...-/"
Case " .-/" : morsCodF = morsCodF + " a"
Case " -.../" : morsCodF = morsCodF + " b"
Case " -.-./" : morsCodF = morsCodF + " c"
Case " -../" : morsCodF = morsCodF + " d"
Case " ./" : morsCodF = morsCodF + " e"
Case " ..-./" : morsCodF = morsCodF + " f"
Case " --./" : morsCodF = morsCodF + " g"
Case " ..../" : morsCodF = morsCodF + " h"
Case " ../" : morsCodF = morsCodF + " i"
Case " .---/" : morsCodF = morsCodF + " j"
Case " -.-/" : morsCodF = morsCodF + " k"
Case " .-../" : morsCodF = morsCodF + " l"
Case " --/" : morsCodF = morsCodF + " m"
Case " -./" : morsCodF = morsCodF + " n"
Case " ---/" : morsCodF = morsCodF + " o"
Case " .--./" : morsCodF = morsCodF + " p"
Case " --.-/" : morsCodF = morsCodF + " q"
Case " .-./" : morsCodF = morsCodF + " r"
Case " .../" : morsCodF = morsCodF + " s"
Case " -/" : morsCodF = morsCodF + " t"
Case " ..-/" : morsCodF = morsCodF + " u"
Case " ...-/" : morsCodF = morsCodF + " v"
Case " .--/" : morsCodF = morsCodF + " w"
Case " -..-/" : morsCodF = morsCodF + " x"
Case " -.--/" : morsCodF = morsCodF + " y"
Case " --../" : morsCodF = morsCodF + " z"
Case "#" : morsCodF = morsCodF + " "
End Select
nasel = False
pismeno = ""
j = j + 1
Next
End Function
Code should translate whole word or sentence, but instead is translating only part of the text. E.g. > …./ ./ .-../ .-../ ---/
expected: "Hello", actual: "e o"

split the string morsCod with "/" as separator
Public Class Form1
Sub EE15a()
Dim veta As String, morsCod As String, st As String
'morsCod = InputBox("Enter the morse code.")
morsCod = "..../ ./ .-../ .-../ ---/ --"
morsCod = " .-/ -.../ -.-./ -../ ./ ..-./ --./ ..../ ../ .---/ -.-/ .-../ --/ -./ ---/ .--./ --.-/ .-./ .../ -/ ..-/ ...-/ .--/ -..-/ -.--/ --.."
veta = morsCodF(morsCod)
st = "Preklad dle funkce " + Chr(10) + veta + Chr(10)
MsgBox(st)
End Sub
Function morsCodF(morsC As String) As String
Dim arr As String() = morsC.Split("/"c)
For Each s As String In arr
Select Case s
Case " .-" : morsCodF = morsCodF + " a"
Case " -..." : morsCodF = morsCodF + " b"
Case " -.-." : morsCodF = morsCodF + " c"
Case " -.." : morsCodF = morsCodF + " d"
Case " ." : morsCodF = morsCodF + " e"
Case " ..-." : morsCodF = morsCodF + " f"
Case " --." : morsCodF = morsCodF + " g"
Case " ...." : morsCodF = morsCodF + " h"
Case " .." : morsCodF = morsCodF + " i"
Case " .---" : morsCodF = morsCodF + " j"
Case " -.-" : morsCodF = morsCodF + " k"
Case " .-.." : morsCodF = morsCodF + " l"
Case " --" : morsCodF = morsCodF + " m"
Case " -." : morsCodF = morsCodF + " n"
Case " ---" : morsCodF = morsCodF + " o"
Case " .--." : morsCodF = morsCodF + " p"
Case " --.-" : morsCodF = morsCodF + " q"
Case " .-." : morsCodF = morsCodF + " r"
Case " ..." : morsCodF = morsCodF + " s"
Case " -" : morsCodF = morsCodF + " t"
Case " ..-" : morsCodF = morsCodF + " u"
Case " ...-" : morsCodF = morsCodF + " v"
Case " .--" : morsCodF = morsCodF + " w"
Case " -..-" : morsCodF = morsCodF + " x"
Case " -.--" : morsCodF = morsCodF + " y"
Case " --.." : morsCodF = morsCodF + " z"
Case "#" : morsCodF = morsCodF + " "
End Select
Next
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
EE15a()
End Sub
End Class

If you need some letters uppercase, you need provide additional logic (for instance, first letter is always uppercase). The following code creates dictionary with codes and their letters, parses Morse code string with Regex, extracting codes one-by-one and fetching letters based on these codes. I have created two versions - with Regex and Split.
Dim morse = New Dictionary(Of String, String) From
{
{".-", "a"},
{"-...", "b"},
{"-.-.", "c"},
{".", "e"},
{"....", "h"},
{".-..", "l"},
{"---", "o"},
{"#", " "}
}
Dim s = "..../ ./ .-../ .-../ ---/"
'// 1. REGEX
'// Search for '.', '-' and '#' in any combinations followed by '/'
Dim mc = Regex.Matches(s, "[\.\-#]+(?=/)")
'// Fetch each code from dictionary and concatenate them
Dim x = String.Join("", mc.Cast(Of Match).Select(Function(m) morse(m.Value)))
'// 2. SPLIT
'// Dim x = String.Join("", s.Split({"/"}, StringSplitOptions.RemoveEmptyEntries).
'// Select(Function(z) morse(z.Replace("/", "").Trim())))
Console.WriteLine(x)
'// Output: hello

I think you will get more feedback of the code if you add default case for the Select Case switch.
Select Case s
Case " .-" : morsCodF = morsCodF + " a"
Case "#" : morsCodF = morsCodF + " "
Case Else : morsCodF = morsCodF + " WRONG! "
End Select
Check does this line oddel = j - oddel works as expected.
Based on the logic you have oddel should be amount of characters after previously found / character. If so, then calculation oddel = j - oddel doesn't look right.
Because you updating i with current j calculation should be oddel = j - (i -1)
Check For loop.
Because i updated every time with current value of j, code will make one extra loop which will produce "wrong" value.
Other suggestions.
Decoding morse code to the text is simple mapping from one string to another.
In vb.net Dictionary(Of String, String) could be good tool for this.
Do you really need / character? Instead you can use simple space as letter delimeter.
Function FromMorse(code As String) As String
Const DELIMETER As Char = " "c
Static Secret As New Dictionary(Of String, String) From
{
{".-", "a"},
{"-...", "b"},
{"-.-.", "c"},
{"-..", "d"},
{".", "e"},
{"..-.", "f"},
{"--.", "g"},
{"....", "h"},
{"..", "i"},
{".---", "j"},
{"-.-", "k"},
{".-..", "l"},
{"--", "m"},
{"-.", "n"},
{"---", "o"},
{".--.", "p"},
{"--.-", "q"},
{".-.", "r"},
{"...", "s"},
{"-", "t"},
{"..-", "u"},
{"...-", "v"},
{".--", "w"},
{"-..-", "x"},
{"-.--", "y"},
{"--..", "z"},
{"#", " "}
}
Return code.Split(DELIMETER).
Select(Function(c) Secret(c)).
Aggregate(New StringBuilder(), Function(b, c) b.Append(c)).
ToString()
End Function
Usage
Dim code = ".... . .-.. .-.. --- # .-- --- .-. .-.. -.."
Dim decoded = FromMorse(code)
Console.WriteLine(decoded) ' => "hello world"

A Dictionary for fast look-up, String.Split for brevity and a StringBuilder to keep from creating new strings on every iteration.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = GetTextFromMorse("..../ ./ .-../ .-../ ---/")
Debug.Print(s)
End Sub
Private DictCode As New Dictionary(Of String, String) From
{
{".-", "a"},
{"-...", "b"},
{"-.-.", "c"},
{"-..", "d"},
{".", "e"},
{"..-.", "f"},
{"--.", "g"},
{"....", "h"},
{"..", "i"},
{".---", "j"},
{"-.-", "k"},
{".-..", "l"},
{"--", "m"},
{"-.", "n"},
{"---", "o"},
{".--.", "p"},
{"--.-", "q"},
{".-.", "r"},
{"...", "s"},
{"-", "t"},
{"..-", "u"},
{"...-", "v"},
{".--", "w"},
{"-..-", "x"},
{"-.--", "y"},
{"--..", "z"},
{"#", " "}
}
Private Function GetTextFromMorse(input As String) As String
Dim strArray() As String = input.Split({"/"}, StringSplitOptions.RemoveEmptyEntries)
Dim sb As New StringBuilder
For Each s In strArray
sb.Append(DictCode(s.Trim))
Next
Return sb.ToString
End Function

Related

Sending object(json) using vba

Im trying to send json object in Outlook using vba. Here is my code:
Dim Msg As Outlook.MeetingItem
Set Msg = Item
Set recips = Msg.Recipients
Dim regEx As New RegExp
regEx.Pattern = "^\w+\s\w+,\sI351$"
Dim URL As String
URL = "https://webhook.site/55759d1a-7892-4c20-8d15-3b8b7f1bf3b3"
For Each recip In recips
If regEx.Test(recip.AddressEntry) And recip.AddressEntry <> "Application Management Linux1, I351" Then
Dim convertedJson As Object
Set convertedJson = JsonConverter.ParseJson("{""fields"": 123}")
Set xhr = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xhr.Open "POST", URL, False
xhr.setRequestHeader "Content-Type", "application/json"
xhr.Send (convertedJson)
End If
Next
If I send just plane text it works well but i can't send convertedJson. Is it possible to send an object?
UPDATE
I can't even do Debug.Print convertedJson
I was tormented by these libraries in the end I did a very terrible thing
Dim flds, prt, id, smry, descrp, issu, name, lfbrkt, rtbrkt, cma, dbdots, jsTest, issuName As String
flds = "'fields'"
prt = "'project'"
id = "'id'"
smry = "'summary'"
descrp = "'description'"
issu = "'issuetype'"
issuName = "'Improvement'"
name = "'name'"
lfbrkt = "{"
rtbrkt = "}"
cma = ","
dbdots = ":"
jsTest = lfbrkt + flds + dbdots + " " + lfbrkt + vbCrLf + vbTab + prt + dbdots + " " + lfbrkt + vbCrLf + vbTab + vbTab + id + dbdots + " " + "30611" + vbCrLf + vbTab + rtbrkt + cma + vbCrLf + vbTab + smry + dbdots + " " + "'" + CStr(Msg.Subject) + "'" + cma + vbCrLf + vbTab + descrp + dbdots + " " + "'" + CStr(Msg.Body) + "'" + cma + vbCrLf + vbTab + issu + dbdots + " " + lfbrkt + vbCrLf + vbTab + vbTab + name + dbdots + " " + issuName + vbCrLf + vbTab + rtbrkt + vbCrLf + rtbrkt + rtbrkt
And I got this

VB 2010 Conversion from string "" to type 'Double' is not valid

please help me. this is a uni project and I keep getting the error "Conversion from string "" to type 'Double' is not valid." even when I made sure that everything is in the correct type, everything with a value...etc.
I want to insert some new rows in my access database, here is a picture of the table that Im trying to insert into
enter image description here
and this is the code
the error appears at the select statement in the sub w()
Dim c As Integer
Dim b As Double
Dim a, d, z As String
a = "'" + TextBox1.Text + "'"
b = CInt(TextBox2.Text)
c = CInt(TextBox3.Text)
d = "'" + TextBox4.Text + "'"
z = "'" + ComboBox1.SelectedItem + "'"
If ComboBox1.SelectedItem = "الجبيل" Then
w("insert into employees (em_id,em_name,m_id,city,phone,salary,password)" & " values (" + 32111 + "," + a + "," + 12303 + "," + z + "," + c + "," + b + "," + d + ")")
ElseIf ComboBox1.SelectedItem = "جدة" Then
w("insert into employees (em_id,em_name,m_id,city,phone,salary,password)" & " values (" + 32111 + "," + a + "," + 12302 + "," + z + "," + c + "," + b + "," + d + ")")
ElseIf ComboBox1.SelectedItem = "الرياض" Then
w("insert into employees (em_id, em_name,m_id,city,phone,salary,password)" & " values (" + 32111 + "," + a + "," + 12301 + "," + z + "," + c + "," + b + "," + d + ")")
End If
MsgBox("تم إضافة السجل بنجاح")
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
the sub w("") is:
Public Sub w(ByVal s As String)
Dim cum As New OleDbCommand(s, con)
cum.ExecuteNonQuery()
End Sub
problem is that it works on different forms (to diffident tables and stuff), but not in here...
what should I do?

Sending Email within loop in a function

code is building the email but it is only displaying one row when there is six. I got it correct on the text file but I need it to do the same in the email message. I think I got the for next statement in the wrong location. Here is the example of the code that I am having problem with. I do not know how to place the for next statement without interrupting the vbLine
For Each p In query
If p.Contract_No IsNot Nothing Then
ContractNo = p.Contract_No
Else
ContractNo = " "
End If
If p.Vendor_Name IsNot Nothing Then
VenderName = p.Vendor_Name
Else
VenderName = " "
End If
If p.Termination_Date IsNot Nothing Then
TerminationDate = p.Termination_Date
' ReportDateStr = ReportDate.ToString
TerminationDateStr = String.Format("{0:MM/dd/yyyy}", TerminationDate)
Else
TerminationDateStr = " "
End If
If p.Dept_Name IsNot Nothing Then
DeptName = p.Dept_Name
Else
DeptName = " "
End If
If p.Renewal_Option_Desc IsNot Nothing Then
RenewalOption = p.Renewal_Option_Desc
Else
RenewalOption = " "
End If
If p.Contract_Desc IsNot Nothing Then
ContractDesc = p.Contract_Desc
Else
ContractDesc = " "
End If
If p.Contact_Email IsNot Nothing Then
ContactEmail = p.Contact_Email
Else
ContactEmail = "** N/A ** "
End If
' sends email with attachment
EmailMsgBody = "-- TOTAL # OF CONTRACTS WITH FAILSAFE DATE ON " + DateStr + " IS: " + icnt.ToString + vbCrLf +
vbNewLine + " __________________ " +
vbNewLine +
vbNewLine + " *****Contracts**** " +
vbNewLine + " __________________ " +
vbNewLine +
vbNewLine + "Contract#" + " " + "Vender Name" + " " + "Termination Date" + " " + "Dept Name" + " " + "Renewal Option" + " " + "Contract Desc" + " " + "Email Address" +
vbNewLine + "------------" + " " + "-----------------" + " " + "---------------------" + " " + "--------------" + " " + "--------------------" + " " + "-----------------" + " " + "-----------------" +
vbNewLine + ContractNo.PadRight(18) + " " + _
VenderName.PadRight(38) + " " + _
TerminationDateStr.PadRight(26) + " " + _
DeptName.PadRight(27) + " " + _
RenewalOption.PadRight(45) + " " + _
ContractDesc.PadRight(32) + " " + _
ContactEmail.PadRight(11) + " "

VB.Net Iterate through two listboxes

I'm trying to iterate through two listboxes and adding all the items to one list.
Here's my code so far but I can't seem to integrate the second listbox into it.
Dim List As List(Of String) = New List(Of String)
For Each LB1 As String In Listbox1.Items
List.Add(vbTab + vbTab + "ent = maps\mp\_utility::createOneshotEffect(" + """" + LB1.ToString() + """" + ");" + vbCrLf +
vbTab + vbTab + "ent.v[ " + """" + "origin" + """" + " ] = ( " + LB2.ToString() + " );"
Next
As long as LB1 and LB2 both contain the same number of items and both are ordered the same, you could use an indexed loop (instead of a foreach loop):
Dim List As List(Of String) = New List(Of String)
For x as integer = 0 to Listbox1.Items.count - 1
List.Add(vbTab + vbTab + "ent = maps\mp\_utility::createOneshotEffect(""" + _
ListBox1.Items(x).ToString() + """);" + vbCrLf + _
vbTab + vbTab + "ent.v[ ""origin"" ] = ( " + _
ListBox2.Items(x).ToString() + " );" _
)
Next

How To Make A File Be Named From A Texbox in VB

Im trying to get a file to be created and named when a button is pressed. But I need the file name to contain text from a textbox.
Code:
My.Computer.FileSystem.WriteAllText("c:\temp\" + txtUser.Text + ".txt", "[" + TimeOfDay + "]" + "Email: " + txtEmail.Text + vbNewLine + "Username: " + txtUser.Text + vbNewLine + "Password: " + txtPass.Text + vbNewLine + "Secuirty: " + txtSecuirty.Text + vbNewLine + vbNewLine, True)
Simple Code:
My.Computer.FileSystem.WriteAllText("c:\temp\" + txtUser.Text + ".txt", {loads of stuff}, True)
I have loads of if functions, to stop the disallowed characters.
The error I am getting is:
Expression does not produce a value
Try to see if this will work for you.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
My.Computer.FileSystem.WriteAllText("c:\temp\" + txtUser.Text.ToString() + ".txt", "test message", True)
End Sub
Or you can change your code to
Dim strFileText As String = ""
strFileText =
"[" & TimeOfDay.ToString() & "] " & vbCrLf &
"Email: " & txtEmail.Text.ToString() & vbCrLf &
"Username: " & txtUser.Text.ToString() & vbCrLf &
"Password: " & txtPass.Text.ToString() & vbCrLf &
"Security: " & txtSecurity.Text.ToString() & vbCrLf & vbCrLf
My.Computer.FileSystem.WriteAllText("c:\temp\" + txtUser.Text.ToString() + ".txt", strFileText, True)