Android Question Help breaking down a routine in a code module

tsteward

Well-Known Member
Licensed User
Longtime User
Okay firstly no laughing at my coding but help will be appreciated.
In my app (started 16 years ago I think so it has evolved and had to be backward compatible) I have my own markup. User loads a vehicle from the database, contents are html with references to other parts of the database embeded which I process when data is loaded, and display in a webviewer.

I am having issues tracking down a bug and feel i would stand a better chance of finding said bug if I could break it down into smaller chunks.

In my mind, I feel I would need to wait for each part to complete before moving on to the next. But you can't use wait for in Code Modules

How would you suggest I break this up?
(I hope this makes sense)
B4X:
Sub CreateNotes(note As String) As String
    If note = Null Then Return ""
    
    Dim location As Int
    Dim temp2, temp3, keyname, image, tmpHold As String 'keyrows
    Dim xui As XUI
    location = note.IndexOf("<body>")
    note = note.Replace("%7Bdir%7D","{dir}")
    
    
    #if b4i
    Do While note.Contains("<iframe") ' remove imbeded youtube for iphone
         Dim startkey As Int = note.IndexOf("<iframe")
        If startkey > -1 Then
            Dim endkey As Int = note.IndexOf2("</iframe>", startkey)
            If endkey > startkey Then
                note = note.SubString2(0, startkey) & note.SubString(endkey + 9)
            End If
        End If
    Loop
    #end if
        
        
    Do While note.Contains("{=")
        Dim nresult() As String = splitNote("{=", "=}", note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{=" & nresult(1) & "=}", "[Error: Invalid Tag =]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. =")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{=" & nresult(1) & "=}", "[Error: No Markdown Content]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        Dim rsOEM As ResultSet = Main.sql1.ExecQuery2($"SELECT * FROM OEMKeyRemote WHERE PartNum =?"$, Array As String(nresult(1)))
        Dim OEMData As StringBuilder
        OEMData.Initialize

        If rsOEM.NextRow Then ' Check if any rows were returned (important!)
            OEMData.Append($"<b>${B4XPages.MainPage.loc.Localize("OEM Key/Remote")}</b><br><UL>"$)
            ' Use a Map for cleaner data handling
            Dim data As Map = CreateMap()
            data.Put("OEM Part#", rsOEM.GetString("PartNum"))
            data.Put("Frequency", rsOEM.GetString("Frequency"))
            data.Put("FCCID", rsOEM.GetString("FCCID"))
            data.Put("Transponder", rsOEM.GetString("Transponder"))
            data.Put("Battery", rsOEM.GetString("Battery"))
            data.Put("Other", rsOEM.GetString("Other"))
            data.Put("Image", rsOEM.GetString("Image"))
            
            For Each key As String In data.Keys
                Dim value As String = data.Get(key)
                If value <> Null And value.Length > 0 Then
                    If key = "Other" Then ' Special case for "Other"
                        OEMData.Append(value)
                    Else If key = "Image" Then
                        If value.Contains("{") Then
                            OEMData.Append(value).Append("<br>")
                        Else
                            OEMData.Append($"{*oem/${value},200*}<br>"$)
                        End If
                    Else
                        OEMData.Append($"<li>${B4XPages.MainPage.loc.Localize(key)}: ${value}</li>"$) ' More concise list item creation
                    End If
                End If
            Next
            OEMData.Append("</ul>")
        Else
            OEMData.Append($"OEM Data Not Found for PartNum: ${nresult(1)}"$) ' Informative message
        
        End If 'End if rsOEM.NextRow
        rsOEM.Close
        note = nresult(0) & OEMData.ToString & nresult(2) ' Update note only ONCE per {=} replacement
    Loop

    Do While note.Contains("{%") ' Insert Remote Data
        Dim nresult() As String = splitNote("{%", "%}", note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{%" & nresult(1) & "%}", "[Error: Invalid Tag %]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. %")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{%" & nresult(1) & "%}", "[Error: No Markdown Content %]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim partBefore As String = nresult(0)
        Dim partKey As String = nresult(1)
        Dim partAfter As String = nresult(2)
        Dim rsRemote As ResultSet = Main.sql1.ExecQuery2($"SELECT * FROM Remote WHERE RemoteID =?"$, Array As String(partKey))
        Dim remDetails As StringBuilder ' Use StringBuilder!
        remDetails.Initialize
        If rsRemote.NextRow Then
            Dim details As String = rsRemote.GetString("Details")
            If details <> Null And details.Length > 0 Then
                remDetails.Append(CreateNotes(details)) ' Append to StringBuilder
            Else
                
            End If
        Else
            remDetails.Append($"Remote Data Not Found for remote: ${partKey}"$)
        End If
        rsRemote.Close
        note = partBefore & remDetails.ToString & partAfter ' Update note once
    Loop
        

    Do While note.Contains("{:") ' Insert OBP Data
        Dim nresult() As String = splitNote("{:",":}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{:" & nresult(1) & ":}", "[Error: Invalid Tag :]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. :")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{:" & nresult(1) & ":}", "[Error: No Markdown Content :]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim rsOBP As ResultSet = Main.sql1.ExecQuery2($"SELECT * FROM OBP WHERE OBPID = ?"$, Array As String(nresult(1)))
        If rsOBP.NextRow Then
            Dim obpDetails As String = rsOBP.GetString("Details")
            obpDetails = CreateNotes(obpDetails)
        Else
            obpDetails = $"OBP Procedure Not Found ref: ${nresult(1)}"$
        End If
        note = nresult(0) & obpDetails & nresult(2)
        rsOBP.Close
    Loop
        
    Do While note.Contains("{+") ' XHorse data
        Dim nresult() As String = splitNote("{+","+}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{+" & nresult(1) & "+}", "[Error: Invalid Tag +]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. +")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{+" & nresult(1) & "+}", "[Error: No Markdown Content +]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        note = note.Replace("{+" & nresult(1) & "+}", "") ' replace as note using yet
    Loop
        
    Do While note.Contains("{;")
        Dim parts() As String = splitNote("{;", ";}",note)
        If parts.Length <> 3 Then
            Log("Error: Invalid tag format in note.")
            note = note.Replace("{;" & parts(1) & ";}", "[Error: Invalid Tag ;]")
            Continue ' Skip to the next tag
        End If
        If parts(1).Length = 0 Then
            note = note.Replace("{;" & parts(1) & ";}", "[Error: No MarkdownContent ;]")
            Continue ' Skip to the next tag
        End If

        Dim partBefore As String = parts(0)
        Dim partKey As String = parts(1)
        Dim partAfter As String = parts(2)

        Dim chipData1 As StringBuilder
        chipData1.Initialize

        Dim rsRemote As ResultSet = Main.sql1.ExecQuery2($"SELECT * FROM KeyDiy WHERE ID = ?"$, Array As String(partKey))
        If rsRemote.NextRow Then ' Only process if a row is found
            chipData1.Append("<table style='text-align: left; width: 100%;' border='1' cellpadding='2' cellspacing='2'>")
            chipData1.Append("<tbody>")
            Dim partNo As String = rsRemote.GetString("partNo")
            If partNo <> Null Then
                chipData1.Append("<tr><th style='vertical-align: top;'>Part#</th><td style='vertical-align: top;'>").Append(partNo).Append("</td>")
            Else
                chipData1.Append("<tr><th style='vertical-align: top;'>Part#</th><td style='vertical-align: top;'>[Not Available]</td>") ' Or handle it differently
            End If
            Dim outsideView As String = rsRemote.GetString("outside_view")
            If outsideView <> Null Then
                chipData1.Append("<td colspan='1' rowspan='5'><img style='width: 180px;' alt='' src='").Append(outsideView).Append("'></td></tr>")
            Else
                chipData1.Append("<td colspan='1' rowspan='5'>[Image Not Available]</td></tr>") ' Or handle it differently
            End If
            Dim frequency As String = rsRemote.GetString("frequency")
            If frequency <> Null Then
                chipData1.Append("<tr><th style='vertical-align: top;'>Freq.</th><td style='vertical-align: top; text-align: center;'>").Append(frequency).Append("</td></tr>")
            Else
                chipData1.Append("<tr><th style='vertical-align: top;'>Freq.</th><td style='vertical-align: top;'>[Not Available]</td></tr>") ' Or handle it differently
            End If
            Dim modulation As String = rsRemote.GetString("modulation")
            If modulation <> Null Then
                chipData1.Append("<tr><th style='vertical-align: top;'>Modulation</th><td style='vertical-align: top; text-align: center;'>").Append(modulation).Append("</td></tr>")
            Else
                chipData1.Append("<tr><th style='vertical-align: top;'>Modulation</th><td style='vertical-align: top;'>[Not Available]</td></tr>")
            End If
            Dim fccid As String = rsRemote.GetString("fccid")
            If fccid <> Null Then
                chipData1.Append("<tr><th style='vertical-align: top;'>FCC</th><td style='vertical-align: top; text-align: center;'>").Append(fccid).Append("</td></tr>")
            Else
                chipData1.Append("<tr><th style='vertical-align: top;'>FCC</th><td style='vertical-align: top;'>[Not Available]</td></tr>")
            End If
            Dim SubKeyType As String = rsRemote.GetString("SubKeyType")
            If SubKeyType <> Null Then
                chipData1.Append("<tr><th style='vertical-align: top;'>Use Remote</th><td style='vertical-align: top; text-align: center;'>").Append(SubKeyType).Append("</td></tr>")
            Else
                chipData1.Append("<tr><th style='vertical-align: top;'>Use Remote</th><td style='vertical-align: top;'>[Not Available]</td></tr>")
            End If
            Dim codeHelp As String = rsRemote.GetString("codeHelp")
            If codeHelp <> Null Then
                chipData1.Append("<tr><th style='vertical-align: top;'>KD Help</th><td colspan='2' style='vertical-align: top;'>").Append(codeHelp).Append("</td></tr>")
            Else
                chipData1.Append("<tr><th style='vertical-align: top;'>KD Help</th><td style='vertical-align: top;'>[Not Available]</td></tr>")
            End If
            chipData1.Append("</tbody></table><br>")
        Else
            chipData1.Append($"KeyDiy Data Not Found for ID: ${partKey}"$) ' Informative message
        End If
        rsRemote.Close

        note = partBefore & chipData1.ToString & partAfter
    Loop
        
    Do While note.Contains("{^^") ' Insert image variable size
        Dim nresult() As String = splitNote("{^^","^^}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{^^" & nresult(1) & "^^}", "[Error: Invalid Tag ^^]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. ^^")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{^^" & nresult(1) & "^^}", "[Error: No Markdown Content ^^]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim imlist As List
        imlist.Initialize
        For Each mystrings As String In Regex.split(",",nresult(1))
            imlist.Add(mystrings)
        Next
        keyname = imlist.Get(0)
        keyname = keyname.ToLowerCase
        If File.Exists(File.DirAssets,keyname) Then
            If imlist.Size > 1 Then
                If imlist.Get(1) = "0" Then
                    note = nresult(0) & $"<div style="text-align: center;"><img src="{dir}/${keyname}"></div><br>"$ & nresult(2)
                Else
                    note = nresult(0) & $"<div style="text-align: center;"><img style="width: 100%; max-width: ${imlist.Get(1)}px;" src="{dir}/${keyname}"></div><br>"$ & nresult(2)
                End If
            Else
                note = nresult(0) & $"<div style="text-align: center;"><img src="{dir}/${keyname}"></div><br>"$ & nresult(2)
            End If
        Else
            note = nresult(0) & nresult(2)
        End If
    Loop
        
    Do While note.Contains("{^") ' Insert image variable size
        Dim nresult() As String = splitNote("{^","^}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{^" & nresult(1) & "^}", "[Error: Invalid Tag ^]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. ^")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{^" & nresult(1) & "^}", "[Error: No Markdown Content ^]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim imlist As List
        imlist.Initialize
        For Each mystrings As String In Regex.split(",",nresult(1))
            imlist.Add(mystrings)
        Next
        keyname = imlist.Get(0)
        keyname = keyname.ToLowerCase
        If imlist.Size > 1 Then
            If imlist.Get(1) = "0" Then
                note = nresult(0) & $"<img src="{dir}/${keyname}"><br>"$ & nresult(2)
            Else
                note = nresult(0) & $"<img style="width: 100%; max-width: ${imlist.Get(1)}px;" src="{dir}/${keyname}"><br>"$ & nresult(2)
            End If
        Else
            note = nresult(0) & $"<img src="{dir}/${keyname}"><br>"$ & nresult(2)
        End If
        
    Loop
    
    Do While note.Contains("{@")
        Dim nresult() As String = splitNote("{@", "@}", note)
        If nresult.Length <> 3 Then
            Log("Error: Invalid tag format in note")
            note = note.Replace("{@" & nresult(1) & "@}", "[Error: Invalid Tag @]")
            Continue ' Skip to the next tag
        End If

        If nresult(1).Length = 0 Then
            Log("Warning: No markdown content found between delimiters. @")
            note = note.Replace("{@" & nresult(1) & "@}", "[Error: No Markdown Content @]")
            Continue
        End If

        Dim chipData As StringBuilder
        chipData.Initialize

        Dim rsChips As ResultSet = Main.sql1.ExecQuery2($"SELECT * FROM Chips WHERE LID =?"$, Array As String(nresult(1)))
        Dim rowFound As Boolean = False
        chipData.Append("<h4 style='margin-top: -0px;'>CHIP</h4>") ' Consider CSS for styling
        chipData.Append("<table style='text-align: left;' border='1' cellpadding='2' cellspacing='2'>")
        chipData.Append("<tbody>")
        chipData.Append("<tr>")
        chipData.Append("<th style='vertical-align: top;'>Type</th>") ' Consider CSS
        chipData.Append("<th style='vertical-align: top;'>Orig</th>")
        chipData.Append("<th style='vertical-align: top;'>Silca</th>")
        chipData.Append("<th style='vertical-align: top;'>JMA</th>")
        chipData.Append("<th style='vertical-align: top;'>Reusable</th>")
        chipData.Append("<th style='vertical-align: top;'>Cloneable</th>")
        chipData.Append("</tr>")

        Do While rsChips.NextRow ' Handle multiple rows
            rowFound = True
            chipData.Append("<tr>")
            Dim brandmodel As String = rsChips.GetString("BrandModel")
            If brandmodel <> Null Then
                chipData.Append($"<td style='vertical-align: top;'>${brandmodel}</td>"$)
            Else
                chipData.Append($"<td style='vertical-align: top;'>[Not Available]</td>"$)
            End If
            Dim LID As String = rsChips.GetString("LID")
            Dim chipID As String = rsChips.GetString("ChipID")
            If LID <> Null Then
                If chipID <> Null Then
                    chipData.Append($"<td style='vertical-align: top; text-align: center;'><a href='http://gotoChip/${LID}:Dunno'>${rsChips.GetString("ChipID")}</a></td>"$)
                Else
                    chipData.Append($"<td style='vertical-align: top; text-align: center;'>[Not Available]</td>"$)
                End If
            Else
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>[Not Available]</td>"$)
            End If
            Dim Silca As String = rsChips.GetString("Silca")
            If Silca <> Null Then
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>${Silca}</td>"$)
            Else
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>[Not Available]</td>"$)
            End If
            Dim JMA As String = rsChips.GetString("JMA")
            If JMA <> Null Then
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>${JMA}</td>"$)
            Else
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>[Not Available]</td>"$)
            End If
            Dim Reuseable As String = rsChips.GetString("Reuseable")
            If Reuseable <> Null Then
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>${Reuseable}</td>"$)
            Else
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>[Not Available]</td>"$)
            End If
            Dim Cloneable As String = rsChips.GetString("Cloneable")
            If Cloneable <> Null Then
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>${Cloneable}</td>"$)
            Else
                chipData.Append($"<td style='vertical-align: top; text-align: center;'>[Not Available]</td>"$)
            End If
            chipData.Append("</tr>")

            Dim makeWith As String = rsChips.GetString("MakeWith")
            If makeWith <> Null And makeWith.Length > 0 Then
                chipData.Append($"Can Make chip with: ${makeWith}<br>"$)
            End If

            Dim comments As String = rsChips.GetString("Comments")
            If comments <> Null And comments.Length > 0 Then
                chipData.Append(CreateNotes(comments)).Append("<br>")
            End If

            If makeWith.Length < 1 And comments.Length < 1 Then
                chipData.Append("<br>")
            End If
        Loop ' End of inner Do While loop
        chipData.Append("</tbody></table>")
            
        If rowFound Then
            note = nresult(0) & CreateNotes(chipData.ToString) & nresult(2) ' Use StringBuilder.ToString *once*
        Else
            note = nresult(0) & $"Chip Data Not Found ${nresult(1)}" & nresult(2)"$ ' Include part 3
        End If

        rsChips.Close
    Loop

    Do While note.Contains("{(") ' Online images imgae,link,size
        Dim nresult() As String = splitNote("{(","(}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{(" & nresult(1) & "(}", "[Error: Invalid Tag (]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. (")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{(" & nresult(1) & "(}", "[Error: No Markdown Content (]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim imlist As List
        imlist.Initialize
        For Each mystrings As String In Regex.split(",",nresult(1))
            imlist.Add(mystrings)
        Next
        '<img style="width: 576px; height: 768px;" alt="Online Image" src="https://dl.dropboxusercontent.com/u/8952255/LARA/Immos/null.jpg">

        image = imlist.Get(0)
        If image.StartsWith("http") = False Then
            image = svr & "LaraImages/" & image
        End If
        If B4XPages.MainPage.Options1.Get("OnlineData") = True Then
            If imlist.Size > 1 Then
                If imlist.Get(1) = "0" Then
                    note = nresult(0) & "<a href='" & imlist.Get(1) & "'><img alt='Online Image' src='" & image & "'></a><br>" & nresult(2)
                Else
                    note = nresult(0) & "<a href='" & imlist.Get(1) & "'><img style='width: 100%; max-width: " & imlist.Get(1) & "px;' alt='Online Image' src='" & image & "'></a><br>" & nresult(2)
                End If
            Else
                note = nresult(0) & "<a href='" & imlist.Get(1) & "'><img alt='Online Image' src='" & image & "'></a><br>" & nresult(2)
            End If
        Else
            note = nresult(0) & "<img alt='Online Data Switched Off' src='{dir}/offline-to-online.png'><br><strong><span style='color: #ff0000;'>Online Image data OFF see settings.</span></strong><br><br>" & nresult(2)
        End If
        'note = temp2
        'End If
    Loop
        
    Do While note.Contains("{)") ' Transponder page reference
        Dim nresult() As String = splitNote("{)",")}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{)" & nresult(1) & ")}", "[Error: Invalid Tag )]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. )")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{)" & nresult(1) & ")}", "[Error: No Markdown Content )]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        'temp2 = note.SubString2(0,startkey) & getTransponder(temp3) & note.SubString(endkey+2)
        note = nresult(0) & getTransponder(nresult(1)) & nresult(2)
    Loop
        
    Do While note.Contains("{*") ' Online images from locksdownunder.com/laraimage/
        Dim nresult() As String = splitNote("{*","*}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{*" & nresult(1) & "*}", "[Error: Invalid Tag *]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. *")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{*" & nresult(1) & "*}", "[Error: No Markdown Content *]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim imlist As List
        imlist.Initialize
        For Each mystrings As String In Regex.split(",",nresult(1))
            imlist.Add(mystrings)
        Next
        image = imlist.Get(0)
        If File.Exists(B4XPages.MainPage.DBFileDir,image) = True Then
            If imlist.Size > 1 Then
                If imlist.Get(1) = "0" Then
                    note = nresult(0) & $"<img src='"$ & B4XPages.MainPage.DBFileDir & "/" & image & "'><br>" & nresult(2)
                Else
                    note = nresult(0) & $"<img style='width: 100%; max-width: "$ & imlist.Get(1) & "px;' src='" & B4XPages.MainPage.DBFileDir & "/" & image & "'><br>" & nresult(2)
                End If
            Else
                note = nresult(0) & $"<img src='"$ & B4XPages.MainPage.DBFileDir & "/" & image & "'><br>" & nresult(2)
            End If
        Else
            If image.StartsWith("http") = False Then
                image = svr & "LaraImages/" & image
            End If
            If B4XPages.MainPage.Options1.Get("OnlineData") = True Then
                If imlist.Get(1) = "0" Then
                    note = nresult(0) & $"<img alt='Online Image' src='"$ & image & "'>" & nresult(2)
                Else
                    note = nresult(0) & $"<img style='width: 100%; max-width: "$ & imlist.Get(1) & "px;' alt='Online Image' src='" & image & "'>" & nresult(2)
                End If
            Else
                note = nresult(0) & "<img alt='Online Data Switched Off' src='{dir}/offline-to-online.png'><br><strong><span style='color: #ff0000;'>Online Image data OFF see settings.</span></strong><br><br>" & nresult(2)
            End If
        End If
    Loop
        
    Do While note.Contains("{$") ' Online images from user uploaded images dir
        Dim nresult() As String = splitNote("{$","$}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{$" & nresult(1) & "$}", "[Error: Invalid Tag $]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. $")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{$" & nresult(1) & "$}", "[Error: No Markdown Content $]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim imlist As List
        imlist.Initialize
        For Each mystrings As String In Regex.split(",",nresult(1))
            imlist.Add(mystrings)
        Next
        image = imlist.Get(0)
        If image.StartsWith("http") = False Then
            image = svr & "LaraImages/uploads/" & image
        End If
        If B4XPages.MainPage.Options1.Get("OnlineData") = True Then
            If imlist.Size > 1 Then
                If imlist.Get(1) = "0" Then
                    note = nresult(0) & $"<img alt='Online Image' src='"$ & image & "'><br>" & nresult(2)
                Else
                    note = nresult(0) & $"<img style='width: 100%; max-width: "$ & imlist.Get(1) & "px;' alt='Online Image' src='" & image & "'><br>" & nresult(2)
                End If
            Else
                note = nresult(0) & $"<img alt='Online Image' src='"$ & image & "'><br>" & nresult(2)
            End If
        Else
            note = nresult(0) & "<img alt='Online Data Switched Off' src='{dir}/offline-to-online.png'><br><strong><span style='color: #ff0000;'>Online Image data OFF see settings.</span></strong><br><br>" & nresult(2)
        End If
    Loop
        
    Do While note.Contains("{!") ' Key name in users chosen brand
        Dim nresult() As String = splitNote("{!","!}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{!" & nresult(1) & "!}", "[Error: Invalid Tag !]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. !")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{!" & nresult(1) & "!}", "[Error: No Markdown Content !]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim rsKeyInfo As ResultSet = Main.sql1.ExecQuery2($"SELECT * FROM KeyInfo WHERE KeyInfoID = ?"$, Array As String(nresult(1)))
        Do While rsKeyInfo.NextRow
            Dim KeyInfoData As String = rsKeyInfo.GetString("KeyInfoData")
            If KeyInfoData <> Null Then
                note = nresult(0) & KeyInfoData & nresult(2)
            Else
                note = nresult(0) & nresult(2)
            End If
        Loop
        rsKeyInfo.Close
    Loop
        
    Do While note.Contains("{dir}")' replace with URI directory for local images in html
        location = note.IndexOf("{dir}")
        If location > -1 Then
            Dim nname As String
            Dim StartString,EndString As Int
            StartString = location+6
            EndString = note.IndexOf2(".",StartString) + 4
            If EndString > StartString Then
                If EndString < note.Length Then
                    nname = note.SubString2(StartString,EndString)
                    If File.Exists(File.DirAssets,nname) Then
                        If xui.IsB4A Then
                            Dim fileURI As String = xui.FileUri(File.DirAssets, nname)
                        Else
                            Dim fileURI As String = File.Combine(File.DirAssets,nname)
                        End If
                        'Log(fileURI & note.SubString(note.IndexOf2(".",location)+4))
                        temp2 = note.SubString2(0,location) & fileURI & note.SubString(note.IndexOf2(".",location)+4)
                    Else
                        temp2 = note.SubString2(0,location) & "" & note.SubString(note.IndexOf2(".",location)+4)
                    End If
                    'Log(temp2)
                    note = temp2
                End If
            End If
        End If
        
    Loop
    
    Do While note.Contains("{~") 'shows keyblank in chosen brand
        Dim nresult() As String = splitNote("{~","~}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{~" & nresult(1) & "~}", "[Error: Invalid Tag ~]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. ~")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{~" & nresult(1) & "~}", "[Error: No Markdown Content ~]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
'        location = note.IndexOf("{~")
'        If location > -1 Then
'            startkey = location
'            endkey = note.IndexOf2("~}", startkey)
'            temp3 = note.SubString2(startkey+2,endkey)
'            temp2 = note.SubString2(0,startkey) & GetBlank(temp3, False) & note.SubString(endkey+2)
        note = nresult(0) & GetBlank(nresult(1),False) & nresult(2)
'        End If
    Loop
        
        
    
    
    Do While note.Contains("{#") ' Insert Key Shell Data
        Dim nresult() As String = splitNote("{#","#}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{#" & nresult(1) & "#}", "[Error: Invalid Tag #]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. #")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{#" & nresult(1) & "#}", "[Error: No Markdown Content #]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim shellID As String = nresult(1)
        temp3 = nresult(0) & nresult(2)' note.SubString2(0,startkey) & note.SubString(endkey+2)
        note = temp3
        Dim rsRemote As ResultSet = Main.sql1.ExecQuery2($"SELECT * FROM KeyShells WHERE ID = '?'"$, Array As String(shellID))
        Do While rsRemote.NextRow
            Dim temp4 As String = $"
                <table style='text-align: left;' border='1' cellpadding='2' cellspacing='2'><tbody>
                <tr>
                <th style='vertical-align: top; text-align: center;'>Silca<br></th>
                <th style='vertical-align: top; text-align: center;'>JMA<br></th>
                <th style='vertical-align: top; text-align: center;'>R/King<br></th>
                <th style='vertical-align: top; text-align: center;'>Keyway<br></th>
                <th style='vertical-align: top; text-align: center;'>Brand<br></th>
                </tr>
                "$
            temp4 = temp4 & "<tr><td style='vertical-align: top;'>" & rsRemote.GetString("Silca") & "</td>"
            temp4 = temp4 & "<td style='vertical-align: top;'>" & rsRemote.GetString("JMA") & "</td>"
            temp4 = temp4 & "<td style='vertical-align: top;'>" & rsRemote.GetString("RKing") & "</td>"
            temp4 = temp4 & "<td style='vertical-align: top;'>" & rsRemote.GetString("Keyway") & "</td>"
            temp4 = temp4 & "<td style='vertical-align: top;'>" & rsRemote.GetString("Brand") & "</td></tr>"
            temp4 = temp4 & "</tbody></table>"
            temp3 = rsRemote.GetString("Comments")
            If temp3 <> Null Then
                temp3 = temp3 & temp4
            End If
            note = note & CreateNotes(temp3)
        Loop
        rsRemote.Close
    Loop
        
    'Hide users name
    Do While note.Contains("{`")
        Dim nresult() As String = splitNote("{`","`}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{`" & nresult(1) & "`}", "[Error: Invalid Tag `]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. `")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{`" & nresult(1) & "`}", "[Error: No Markdown Content `]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
'        startkey = note.IndexOf("{`")
'        endkey = note.IndexOf2("`}",startkey)
'        If endkey > note.Length-2 Then
'            note = note.SubString2(0,startkey-1)
'        Else
'            note = note.SubString2(0,startkey-1) & note.SubString2(endkey+2,note.Length)
'        End If
        note = nresult(0) & nresult(2)
    Loop
        
    ' get key and code series
    Do While note.Contains("{-")
        Dim nresult() As String = splitNote("{-","-}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{-" & nresult(1) & "-}", "[Error: Invalid Tag -]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. -")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{-" & nresult(1) & "-}", "[Error: No Markdown Content -]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim keyID, tabID As String
        Dim keytabledata As String = ""
        tabID = ""
        keyID = nresult(1)
        If keyID.Contains(",") Then
            tabID = keyID.SubString(keyID.IndexOf(",")+1)
            keyID = keyID.SubString2(0,keyID.IndexOf(","))
        End If
        keytabledata = GetBlanks(keyID)
        keytabledata = keytabledata & GetCodeSeries(keyID,tabID,0)
        keytabledata = keytabledata &  getDecoders(keyID)
        note = nresult(0) & keytabledata & nresult(2) 'note & endnote
        keytabledata = ""
    Loop
        
    ' get code series only
    Do While note.Contains("{_")
        Dim nresult() As String = splitNote("{_","_}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{_" & nresult(1) & "_}", "[Error: Invalid Tag _]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. -")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{_" & nresult(1) & "_}", "[Error: No Markdown Content _]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        
        Dim keyID, tabID As String
        Dim codetabledata As String = ""
        tabID = ""
        keyID = nresult(1)
        codetabledata = GetBlanks(keyID)
        codetabledata = codetabledata & GetCodeSeries(keyID,tabID,B4XPages.MainPage.currentToolIC)
        note = nresult(0) & codetabledata & nresult(2) 'note & endnote
        codetabledata = ""
    Loop
        
    Do While note.Contains("{") 'we do this due to legacy note from the early days
        Dim nresult() As String = splitNote("{","}",note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace("{" & nresult(1) & "}", "[Error: Invalid Tag {}]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. {")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace("{" & nresult(1) & "}", "[Error: No Markdown Content {}]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If
        tmpHold = GetBlanks(nresult(1))
        note = nresult(0) & tmpHold & nresult(2)
    Loop
    
    Return note
End Sub
 

emexes

Expert
Licensed User
I feel I would need to wait for each part to complete before moving on to the next.

When you say "need to wait for each part to complete" are you talking about using Wait For statements?

It looks like most of the code is replacing tags with data pulled from various database tables or similar:

B4X:
{=     FROM OEMKeyRemote WHERE PartNum =?
{%     FROM Remote WHERE RemoteID =?
{:     FROM OBP WHERE OBPID = ?
{+     XHorse
{;     FROM KeyDiy WHERE ID = ?
{^     image
{@     FROM Chips WHERE LID =?
{(     images
{)     transponders
{*     images
{$     uploaded images
{!     FROM KeyInfo WHERE KeyInfoID = ?
{~     'shows keyblank in chosen brand        
{#     FROM KeyShells WHERE ID = '?'
{`     no idea
{-     keytabledata
{_     codetabledata
{      legacy tags?  tmpHold

{dir}  ' replace with URI directory for local images in html

and I'm feeling like you could have one routine that does the tag finding and looping, and it calls a switcher routine that hands out the key --> replacement task to the Sub that handles that particular tag type.
 
Upvote 0

tsteward

Well-Known Member
Licensed User
Longtime User
When you say "need to wait for each part to complete" are you talking about using Wait For statements?
That is what I was thinking yes.
It looks like most of the code is replacing tags with data pulled from various database tables or similar:
Correct
B4X:
{=     FROM OEMKeyRemote WHERE PartNum =?
{%     FROM Remote WHERE RemoteID =?
{:     FROM OBP WHERE OBPID = ?
{+     XHorse
{;     FROM KeyDiy WHERE ID = ?
{^     image
{@     FROM Chips WHERE LID =?
{(     images
{)     transponders
{*     images
{$     uploaded images
{!     FROM KeyInfo WHERE KeyInfoID = ?
{~     'shows keyblank in chosen brand       
{#     FROM KeyShells WHERE ID = '?'
{`     no idea
{-     keytabledata
{_     codetabledata
{      legacy tags?  tmpHold

{dir}  ' replace with URI directory for local images in html

and I'm feeling like you could have one routine that does the tag finding and looping, and it calls a switcher routine that hands out the key --> replacement task to the Sub that handles that particular tag type.
I'm not sure what you mean but my brain is ready for bed.
I wanted to break it up to help with debugging. Crashlytics gives me something like undeclared Boolean I have too much code to try & find the error.

Open to any better ideas
 
Upvote 0

emexes

Expert
Licensed User
talking about using Wait For statements?
That is what I was thinking yes.

Why, if they're not needed currently in the one big sub?

It looks you can just split it up into a master Sub that calls the individual tag-type Subs one by one, updating the note along the way, eg:

B4X:
Sub CreateNotes(note As String) As String
    If note = Null Then Return ""
   
    'initialization and preparatory stuff
   
    note = HandleTag96(note)    ' {`abc`}
    note = HandleTag33(note)    ' {!abc!}
    note = HandleTag48(note)    ' {@abc@}
    note = HandleTag35(note)    ' {#abc#}
    note = HandleTag36(note)    ' {$abc$}
    note = HandleTag37(note)    ' {%abc%}
    note = HandleTag94(note)    ' {^abc^}
    note = HandleTag42(note)    ' {*abc*}
    'etc

    'finalization and cleanup stuff
   
    Return note
End Sub

although I think there might be an even better way, which reduces all the tag-finding and substitution process down to just one Sub, but... given that you've already goot all the stuff duplicated, and that you can implement most of the above by putting:

B4X:
    Return note
End Sub

Sub HandleTypeNN(note As String) As String

between each of your existing tag type sections, then I'd say go with that first, in order to find the undeclared Boolean bug or whatever, and do the code niceifying after the immediate bushfire is under control.
 
Upvote 0

emexes

Expert
Licensed User
The epiphanic even-better way was to have simple individual Subs, one for each tag type, that convert the tag key into the replacement text, eg:

B4X:
Sub TagSubstitute33(TagKey As String) As String    'for {! TagKey !}
    Dim ReplaceTagWith As String = "??? NOT FOUND ???"

    Dim rsKeyInfo As ResultSet = Main.sql1.ExecQuery2($"SELECT * FROM KeyInfo WHERE KeyInfoID = ?"$, Array As String(TagKey))
    If rsKeyInfo.NextRow
        Dim KeyInfoData As String = rsKeyInfo.GetString("KeyInfoData")
        If KeyInfoData <> Null Then
            ReplaceTagWith = KeyInfoData    'would usually just return this here, if didn't still need to close query
        End If
    End If
    rsKeyInfo.Close

    Return ReplaceTagWith
End Sub

and then a switcher Sub to handle all tag types, using a selecting number rather than the Sub name eg:

B4X:
Sub TagSubstitute(TagType As Int, TagKey As String) As String
    Select TagType
        Case 96: Return TagSubstitute96(TagKey As String)
        Case 33: Return TagSubstitute33(TagKey As String)
        Case 48: Return TagSubstitute48(TagKey As String)
        Case 35: Return TagSubstitute35(TagKey As String)
        Case 36: Return TagSubstitute36(TagKey As String)
        Case 37: Return TagSubstitute37(TagKey As String)
        Case 94: Return TagSubstitute94(TagKey As String)
        Case 42: Return TagSubstitute42(TagKey As String)
        'etc
    End Select

    Return "??? TAG TYPE " & TagType & "???"
End Sub

and then you can have just one Sub that can do the replacements for any tag type eg:

B4X:
Sub HandleTag(TagType As Int, note As String) As String
    Dim TagTypeChar As String = ""
    If TagType <> 0 Then
        TagTypeChar = Chr(TagType)
    End If

    Dim TagLeft As String = "{" & TagTypeChar
    Dim TagRight As String = TagTypeChar & "}"
    ''' Log(TagType & Tab & TagLeft & Tab & TagRight)

    Do While note.Contains(TagLeft)    ' And note.Contains(TagRight) ???
        Dim nresult() As String = splitNote(TagLeft, TagRight, note)
        If nresult.Length <> 3 Then 'Handle errors
            Log("error: Invalid tag format in note")
            note = note.Replace(TagLeft & nresult(1) & TagRight, "[Error: Invalid Tag %]") ' Or some other error handling
            Continue ' Skip to the next tag
        End If
        If nresult(1).Length = 0 Then  ' Check if the markdown part is empty
            Log("Warning: No markdown content found between delimiters. %")
            ' Handle the case where there's no markdown.  For example:
            note = note.Replace(TagLeft & nresult(1) & TagRight, "[Error: No Markdown Content %]") ' Or leave it as is
            Continue ' Skip to the next tag
        End If

        Dim partBefore As String = nresult(0)
        Dim partKey As String = nresult(1)    ' .Trim ?
        Dim partAfter As String = nresult(2)

        note = partBefore & TagSubstitute(TagType, partKey) & partAfter ' Update note once
    Loop

    Return note
End Sub

and then call that One-Sub-To-Handle-Them-All for each of the tag types eg:

B4X:
Sub HandleAllTags(note As String) As String
    Dim TagTypes As String = "=%:+;^@()*$!~#`-_" & Chr(0)    'TagType 0 is just bare braces, no type character, should be done last

    For I = 0 to TagTypes.Length - 1
        Dim TagType As Int = Asc(TagTypes.CharAt(I))
        note = HandleTag(TagType, note)
    Next

    Return note
End Sub

I think that'll do it. I'm just praying that none of the TagSubstituteNN Subs are relying on intermediate results from a previous substitution.
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
Oh, and if the final note contains any "??? " and " ???" then that would indicate an error and you could log the before- and after- notes to a last-error text file that could be returned to you by the user clicking a button on your help screen (or even automatically, but my recollection is that Google's not very keen on background phone-home stuff).

Probaby should have used a less-likely-to-occur-naturally marker like ?`? error message ?`? rather than ??? error message ???. And wrap it in a Sub to avoid accidental inconsistencies eg:
B4X:
Sub EasyToFindErrorMessage(Message As String) As String
    Return ("?`? " & Message.Trim).Trim & " ?`?"
End Sub
 
Last edited:
Upvote 0

William Lancee

Well-Known Member
Licensed User
Longtime User
F.Y.I. The code you have does not accommodate tags with embedded other tags, unless they come in the expected order.
Early tags can be embedded in later tags, since you have replaced them already.
But what if a tag has a another tag embedded that is handled later?

There are two ways to deal with this:
1. do recursive parsing - elegant, succinct, but not intuitive
2. suspend handling tags that have tags and have a larger loop that looks for unhandled tags

Either technique will require a rewrite of your code.
Therefore the suggestions by @emexes are highly recommended.
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
1. do recursive parsing - elegant, succinct, but not intuitive

or Poor Man's Recursion: keep calling HandleAllTags until note stops changing, or even do it directly, eg:

B4X:
Sub HandleAllTags(note As String) As String
    Dim TagTypes As String = "=%:+;^@()*$!~#`-_" & Chr(0)    'TagType 0 is just bare braces, no type character, should be done last

    Do While True
        Dim oldnote As String = note
        
        For I = 0 to TagTypes.Length - 1
            Dim TagType As Int = Asc(TagTypes.CharAt(I))
            note = HandleTag(TagType, note)
        Next

        If note = oldnote Then Exit    'if nothing changed then there are no more tags to replace
    Loop
    
    Return note
End Sub
 
Upvote 0

emexes

Expert
Licensed User
ever consider changing to a less-cryptic tag style like {type=value} ?

eg for part number KC1234/B then you could have:

{part=KC1234/B}

instead of having to remember what each punctuation character means with:

{!KC1234/B!}
 
Upvote 0

MrKim

Well-Known Member
Licensed User
Longtime User
One of the things I do is just log statements Log(1), Log(2), etc. see what number you are on when the code breaks. This is especially helpful when the code doesn't break when you step through it.
If you are doing a loop and it is happening sometime during the loop then increment a counter (Log(X)): X=X+1) or even better log some key part of your data if you think it is a data issue.
 
Upvote 0

tsteward

Well-Known Member
Licensed User
Longtime User
One of the things I do is just log statements Log(1), Log(2), etc. see what number you are on when the code breaks. This is especially helpful when the code doesn't break when you step through it.
If you are doing a loop and it is happening sometime during the loop then increment a counter (Log(X)): X=X+1) or even better log some key part of your data if you think it is a data issue.
Thank you but this doesn't help in released app running on clients device.
 
Upvote 0

MrKim

Well-Known Member
Licensed User
Longtime User
Thank you but this doesn't help in released app running on clients device.
You didn't mention that that that was you situation in your first post. Display the info on a screen instead and ask the user to make a note of it if they have problems. You could add a debug switch to turn that on and off if you like. Or if you have a failure turn on the display, ask the user to try again and make a note of the results.
You could also save the results in a variable and if there is a failure copy it to the clipboard and ask the user to paste it in an email to you.
Good luck! It is always a challenge debugging bad data issues.
 
Upvote 0
Top