Classic ASP Convert Latin Characters to Unicode Escape Strings - asp-classic

I need a Classic ASP function that will take a string such as Jämshög and convert it to J\u00e4msh\u00f6gso that all the accented characters become their equivalent unicode escape codes.
I am sending this data in a JSON string to an API that requires all special characters to use unicode escape codes.
I've been searching for what seems like hours to come up with a solution and I haven't managed to come close. Any help would be greatly appreciated.

Take a look at the function from aspjson below. It also handles non-unicode characters that must to be escaped such as quote, tab, line-feed etc. Luckily no dependencies, so works stand-alone too.
Function jsEncode(str)
Dim charmap(127), haystack()
charmap(8) = "\b"
charmap(9) = "\t"
charmap(10) = "\n"
charmap(12) = "\f"
charmap(13) = "\r"
charmap(34) = "\"""
charmap(47) = "\/"
charmap(92) = "\\"
Dim strlen : strlen = Len(str) - 1
ReDim haystack(strlen)
Dim i, charcode
For i = 0 To strlen
haystack(i) = Mid(str, i + 1, 1)
charcode = AscW(haystack(i)) And 65535
If charcode < 127 Then
If Not IsEmpty(charmap(charcode)) Then
haystack(i) = charmap(charcode)
ElseIf charcode < 32 Then
haystack(i) = "\u" & Right("000" & Hex(charcode), 4)
End If
Else
haystack(i) = "\u" & Right("000" & Hex(charcode), 4)
End If
Next
jsEncode = Join(haystack, "")
End Function

Related

Formatting Mac Address in MS Access

New to MS Access. Had a question regarding formatting of a MAC Address in one of my Access forms. There is a field I have set up using an input mask aa:aa:aa:aa:aa:aa;;a where users can manually enter a 48 bit hexidecimal address. e.x 11:44:5E:33:53:AF.
However sometimes there are missing values that occur in this data entry e.x 0:A:B:11:22:C (happens from time to time) but I would like be able to automatically fill the missing values with leading zeros to be like 00:0A:0B:11:22:0C.
I realize that this may not be possible through just MS Access Input masks, but all of the VBA codes and after updates code building I have been looking at so far have not lead me to the desired format.
Thanks for your time and appreciate any help in this!
I tried Format(fieldname, "00000000") code, but it just fills from the left-hand side instead of between the colons. e.x 00:00:0A:B1:12:2C instead of the desired 00:0A:0B:11:22:0C.
My function FormatMacAddress is for you:
' Formats a MAC address using one of the four de facto formats used widely.
' Thus, the format can and will be defined by the specified delimiter to use.
' The default is no delimiter and uppercase.
' Optionally, the case of the returned string can be specified as lowercase.
'
' Examples:
' None -> "1234567890AB"
' Dot -> "1234.5678.90AB"
' Dash -> "12-34-56-78-90-AB"
' Colon -> "12:34:56:78:90:AB"
'
' Lowercase -> "1234567890ab"
'
' 2019-09-23, Cactus Data ApS, Gustav Brock
'
Public Function FormatMacAddress( _
ByRef Octets() As Byte, _
Optional Delimiter As IpMacAddressDelimiter, _
Optional TextCase As VbStrConv = VbStrConv.vbProperCase) _
As String
Dim LastFrame As Integer
Dim ThisFrame As Integer
Dim FrameLength As Integer
Dim Index As Integer
Dim Symbol As String
Dim MacAddress As String
' Only accept an array with six octets.
If LBound(Octets) = 0 And UBound(Octets) = OctetCount - 1 Then
' Calculate the frame length.
FrameLength = DigitCount / DelimiterFrameCount(Delimiter)
' Format the octets using the specified delimiter.
For Index = LBound(Octets) To UBound(Octets)
ThisFrame = (Index * OctetLength) \ FrameLength
Symbol = ""
If LastFrame < ThisFrame Then
Symbol = DelimiterSymbol(Delimiter)
LastFrame = ThisFrame
End If
MacAddress = MacAddress & Symbol & Right("0" & Hex(Octets(Index)), OctetLength)
Next
End If
If MacAddress <> "" Then
Select Case TextCase
Case VbStrConv.vbLowerCase
MacAddress = StrConv(MacAddress, TextCase)
Case Else
' Leave MacAddress in uppercase.
End Select
End If
FormatMacAddress = MacAddress
End Function
As it requires a Byte() input, you may need the function MacAddressParse as well:
' Parses a string formatted MAC address and returns it as a Byte array.
' Parsing is not case sensitive.
' Will by default only accept the four de facto standard formats used widely.
'
' Examples:
' "1234567890AB" -> 1234567890AB
' "1234.5678.90AB" -> 1234567890AB
' "12-34-56-78-90-AB" -> 1234567890AB
' "12:34:56:78:90:AB" -> 1234567890AB
'
' If argument Exact is False, a wider variation of formats will be accepted:
' "12-34:56-78:90-AB" -> 1234567890AB
' "12 34 56-78 90 AB" -> 1234567890AB
' "56 78 90 AB" -> 0000567890AB
' "1234567890ABDE34A0" -> 1234567890AB
'
' For unparsable values, the neutral MAC address is returned:
' "1K34567890ABDEA0" -> 000000000000
'
' 2019-09-23, Cactus Data ApS, Gustav Brock
'
Public Function MacAddressParse( _
ByVal MacAddress As String, _
Optional Exact As Boolean = True) _
As Byte()
Dim Octets() As Byte
Dim Index As Integer
Dim Expression As String
Dim Match As Boolean
' Delimiters.
Dim Colon As String
Dim Dash As String
Dim Dot As String
Dim Star As String
' Create neutral MAC address.
ReDim Octets(0 To OctetCount - 1)
' Retrieve delimiter symbols.
Colon = DelimiterSymbol(ipMacColon)
Dash = DelimiterSymbol(ipMacDash)
Dot = DelimiterSymbol(ipMacDot)
Star = DelimiterSymbol(ipMacStar)
If Exact = True Then
' Verify exact pattern of the passed MAC address.
Select Case Len(MacAddress)
Case TotalLength1
' One frame of six octets (no delimiter).
Expression = Replace(Space(DigitCount), Space(1), HexPattern)
Match = MacAddress Like Expression
If Match = True Then
' MAC address formatted as: 0123456789AB.
End If
Case TotalLength3
' Three frames of two octets.
Expression = Replace(Replace(Replace(Space(DigitCount / FrameLength3), Space(1), Replace(Replace(Space(FrameLength3), Space(1), HexPattern), "][", "]" & Star & "[")), "][", "]" & Dot & "["), Star, "")
Match = MacAddress Like Expression
If Match = True Then
' MAC address formatted as: 0123.4567.89AB.
MacAddress = Replace(MacAddress, Dot, "")
End If
Case TotalLength6
' Six frames of one octets.
Expression = Replace(Replace(Replace(Space(DigitCount / FrameLength6), Space(1), Replace(Replace(Space(FrameLength6), Space(1), HexPattern), "][", "]" & Star & "[")), "][", "]" & Colon & "["), Star, "")
Match = MacAddress Like Expression
If Match = True Then
' MAC address formatted as: 01:23:45:67:89:AB.
MacAddress = Replace(MacAddress, Colon, "")
Else
Expression = Replace(Expression, Colon, Dash)
Match = MacAddress Like Expression
If Match = True Then
' MAC address formatted as: 01-23-45-67-89-AB.
MacAddress = Replace(MacAddress, Dash, "")
End If
End If
End Select
Else
' Non-standard format.
' Clean MacAddress and try to extract six octets.
MacAddress = Replace(Replace(Replace(Replace(MacAddress, Colon, ""), Dash, ""), Dot, ""), Space(1), "")
Select Case Len(MacAddress)
Case Is > DigitCount
' Pick leading characters.
MacAddress = Left(MacAddress, DigitCount)
Case Is < DigitCount
' Fill with leading zeros.
MacAddress = Right(String(DigitCount, "0") & MacAddress, DigitCount)
End Select
' One frame of six possible octets.
Expression = Replace(Space(DigitCount), Space(1), HexPattern)
Match = MacAddress Like Expression
If Match = True Then
' MAC address formatted as: 0123456789AB.
End If
End If
If Match = True Then
' Fill array Octets.
For Index = LBound(Octets) To UBound(Octets)
Octets(Index) = Val("&H" & Mid(MacAddress, 1 + Index * OctetLength, OctetLength))
Next
End If
MacAddressParse = Octets
End Function
Full code at GitHub: VBA.MacAddress.

Should Generic URL Decoding Functions Handle "+" Chars or Just "%20" etc. Chars?

I am wondering if a generic URL Decoding function should handle the "+" character (space) in addition to all of the e.g. "%20" etc. encodings?
There is no specific use case as of yet.
Is there any spec that would be appropriate to reference here?
I am doing it in VBScript (but that is not relevant to my question I believe) and I have two versions, one which would handle the "+" by replacing it with a "" (space) ...
Public Function decode(s)
s = replace(s, "+", " ")
For i = 1 To Len(s)
If Mid(s, i, 1) = "%" Then
decode = decode & Chr("&H" & Mid(s, i+1, 2))
i = i + 2
Else
decode = decode & Mid(s, i, 1)
End If
Next
End Function
...and one which does not:
Public Function decode(s)
For i = 1 To Len(s)
If Mid(s, i, 1) = "%" Then
decode = decode & Chr("&H" & Mid(s, i+1, 2))
i = i + 2
Else
decode = decode & Mid(s, i, 1)
End If
Next
End Function
If it's supposed to be generic: no. The role of "+" is very specific to HTML forms and has nothing to do with generic URI handling.

ASP grab two parameters from referral url

Hi I am using a code to get the referral URL as you can see below:
sRef = encode(Request.ServerVariables("HTTP_REFERER"))
The code above is getting the following URL:
http://www.rzammit.com/pages/linux-form.asp?adv=101&loc=349&websync=233344-4555665-454&ptu=454545
From that url I want to grab ONLY the ADV and LOC (Request.querystring doesnt work because this is a script which is run when the form is submitted)
So to cut the story short, by using the referral URL, i want to get out the values for the adv and loc parameters.
Any help please on how I can do this?
Below is the code I am currently using but I have a problem. The parameters which are after the loc, is showing as well. I want something dynamic. Also the values of the adv and loc can be longer.
<%
sRef = Request.ServerVariables("HTTP_REFERER")
a=instr(sRef, "adv")+4
b=instr(sRef, "&loc")
response.write(mid(sRef ,a,b-a))
response.write("<br>")
response.write(mid(sRef ,b+5))
%>
Here is something to get you started; it uses regular expressions to get all URL variables for you. You can use the split() function to split them on the "=" sign and get a simple array, or put them in a dictionary or whatever.
Dim fieldcontent : fieldcontent = "http://www.rzammit.com/pages/linux-form.asp?adv=101&loc=349&websync=233344-4555665-454&ptu=454545"
Dim regEx, Matches, Item
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Global = True
regEx.MultiLine = False
regEx.Pattern = "(\?|&)([a-zA-Z0-9]+)=([^&])"
Set Matches = regEx.Execute(fieldcontent)
For Each Item in Matches
response.write(Item.Value & "<br/>")
Next
Set regEx = Nothing
substring everything after the ?.
Split on "&"
Iterate the array to find "adv=" and "loc="
Below is the code:
Dim fieldcontent
fieldcontent = "http://www.rzammit.com/pages/linux-form.asp?adv=101&loc=349&websync=233344-4555665-454&ptu=454545"
fieldcontent = mid(fieldcontent,instr(fieldcontent,"?")+1)
Dim params
params = Split(fieldcontent,"&")
for i = 0 to ubound(params) + 1
if instr(params(i),"adv=")>0 then
advvalue = mid(params(i),len("adv=")+1)
end if
if instr(params(i),"loc=")>0 then
locvalue = mid(params(i),5)
end if
next
You can use the following generic function:
function getQueryStringValueFromUrl(url, key)
dim queryString, queryArray, i, value
' check if a querystring is present
if not inStr(url, "?") > 0 then
getQueryStringValueFromUrl = empty
end if
' extract the querystring part from the url
queryString = mid(url, inStr(url, "?") + 1)
' split the querystring into key/value pairs
queryArray = split(queryString, "&")
' see if the key is present in the pairs
for i = 0 to uBound(queryArray)
if inStr(queryArray(i), key) = 1 then
value = mid(queryArray(i), len(key) + 2)
end if
next
' return the value or empty if not found
getQueryStringValueFromUrl = value
end function
In your case:
dim url
url = "http://www.rzammit.com/pages/linux-form.asp?adv=101&loc=349&websync=233344-4555665-454&ptu=454545"
response.write "ADV = " & getQueryStringValueFromUrl(url, "adv") & "<br />"
response.write "LOC = " & getQueryStringValueFromUrl(url, "loc")

ASP.Net String Split not working

Here's my code
Dim RefsUpdate As String() = Session("Refs").Split("-"C)
Dim PaymentsPassedUpdate As String() = Session("PaymentsPassed").Split("-"C)
Dim x as Integer
For x = 1 to RefsUpdate.Length - 1
Dim LogData2 As sterm.markdata = New sterm.markdata()
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''"+ RefsUpdate(x) +"'' AND bookno = ''"+ Session("number") +"'' ') SET alpaid = '"+PaymentsPassedUpdate(x) +"', paidfl = 'Y', amountdue = '0' ")
Dim drSetUpdatePaymentFlags As DataSet = Data.Blah(queryUpdatePaymentFlags)
Next
I don't get any errors for this but it doesn't seem to working as it should
I'm passing a bookingref like this AA123456 - BB123456 - CC123456 - etc and payment like this 50000 - 10000 - 30000 -
I basically need to update the db with the ref AA123456 so the alpaid field has 50000 in it.
Can't seem to get it to work
Any ideas?
Thanks
Jamie
I'm not sure what isn't working, but I can tell you that you are not going to process the last entry in your arrays. You are going from 1 to Length - 1, which is one short of the last index. Therefore, unless your input strings end with "-", you will miss the last one.
Your indexing problem mentioned by Mark is only one item, but it will cause an issue. I'd say looking at the base your problem stems from not having trimmed the strings. Your data base probably doesn't have spaces leading or trailing your data so you'll need to do something like:
Dim refsUpdateString as string = RefsUpdate(x).Trim()
Dim paymentsPassedUpdateString as string = PaymentsPassedUpdate(x).Trim()
...
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''" & refsUpdateString & "'' AND bookno = ''" & Session("number") & "'' ') SET alpaid = '" & paymentsPassedUpdateString & "', paidfl = 'Y', amountdue = '0' ")
Also, I would recommend keeping with the VB way of concatenation and use the & character to do it.

How do I find out if the first character of a string is a number in VB.NET?

How do I check to see if the first character of a string is a number in VB.NET?
I know that the Java way of doing it is:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
But I'm unsure as to how to go about it for VB.NET.
Thanks in advance for any help.
Here's a scratch program that gives you the answer, essentially the "IsNumeric" function:
Sub Main()
Dim sValue As String = "1Abc"
Dim sValueAsArray = sValue.ToCharArray()
If IsNumeric(sValueAsArray(0)) Then
Console.WriteLine("First character is numeric")
Else
Console.WriteLine("First character is not numeric")
End If
Console.ReadLine()
End Sub
Public Function StartsWithDigit(ByVal s As String) As Boolean
Return (Not String.IsNullOrEmpty(s)) AndAlso Char.IsDigit(s(0))
End Function
Public Function StartsWithDigit(ByVal s As String) As Boolean
Return s Like "#*"
End Function
If I were you I will use
Dim bIsNumeric = IsNumeric(sValue.Substring(0,1))
and not
Dim sValueAsArray = sValue.ToCharArray()
It does not matter what you use, both will yield the same result,
but having said that; Dim sValueAsArray = sValue.ToCharArray() will use more memory & Dim bIsNumeric = IsNumeric(sValue.Substring(0,1)) will use less resources. though both of them are negligible
It is more of a suggestion of programming practice than anything else.
Char.IsNumber(c)
More details here: https://msdn.microsoft.com/en-us/library/yk2b3t2y(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
The VB.Net code that is equivalent to your Java code can be done using following lines
Dim c = sText(0)
bIsDigit = (c >= "0" AndAlso c <= "9")
where
Dim bIsDigit As Boolean
Dim sText as String = "2 aeroplanes" 'example for test
But, there exist also other solutions
bIsDigit = Char.IsDigit(c)
bIsDigit = Char.IsNumber(c)
bIsDigit = Information.IsNumeric(c)
and when sText is an empty string, you can also use one of following lines
Dim c = Mid(sText, 1, 1)
Dim c = (sText & "-")(0)
Dim c = Strings.Left(sText, 1)
Dim c As Char = sText
But, for me, the best solution is
bIsDigit = Char.IsDigit(Mid(sText, 1, 1))
or
bIsDigit = Char.IsDigit(sText(0))
if you are sure that sText is not empty.
And the shorter (but tricky) solution is
bIsDigit = Char.IsDigit(sText)
In this last line, first character of sText is implicitely converted to Char.

Resources