Decode mail encoded-words =?utf-8?B?xxxx?=, =?utf-8?Q?xxxx?= - vb.net

Is there a way to decode email subjects that are encoded? I know the dirty way of doing it is to get the string character between =?utf-8?B? xxx ?= and decoding that. But I have a program where I can get encoded strings like
=?utf-8?Bxxxx?= =?UTF-8?B?xxxx?= ...
Right now I'm doing something like this
If codedString.ToUpper().StartsWith("=?UTF-8?B?") Then
Dim temp As String = codedString.SubString(10)
Dim data = Convert.FromBase64String(temp)
Dim decodedString = ASCIIEncoding.ASCII.GetString(data)
'do something with decodedString
End If
But this doesn't work when the same string has multiple =?utf-8?B? encode like above. Also I can get strings with =?utf-8?Q encoding and =?windows-1252. Is there a way to tackle all of these encoding? I'm using Visual Studios 2017

I've never had trouble using this function to decode a email field value:
It finds matching utf-8 strings for types B or Q, and if type B, runs FromBase64String.
I'm sure you can manipulate for windows-1252.
Private Function DecodeEmailField(byVal strString as String) as String
DecodeEmailField = strString.toString()
Dim strMatch
Dim arrEncodeTypes = New String() {"B","Q"}
Dim strEncodeType as String
For Each strEncodeType in arrEncodeTypes
Dim objRegexB as RegEx = new RegEx("(?:\=\?utf\-8\?" & strEncodeType & "\?)(?:.+?)(?:\?=\s)", _
RegexOptions.Multiline or RegexOptions.IgnoreCase)
if (objRegexB.IsMatch(DecodeEmailField)) then
Dim thisMatch as Match = objRegexB.Match(DecodeEmailField)
For Each strMatch in thisMatch.Groups
Dim strMatchHold as String = strMatch.toString().Substring(("=?utf-8?" & strEncodeType & "?").length)
strMatchHold = strMatchHold.SubString(0,(strMatchHold.Length)-("?= ".Length))
If strEncodeType = "B" Then
Dim data() As Byte = System.Convert.FromBase64String(strMatchHold)
strMatchHold = System.Text.UTF8Encoding.UTF8.GetString(data)
End If
DecodeEmailField = Replace(DecodeEmailField,strMatch.toString(),strMatchHold)
Next
End If
Next
End Function

Related

VB.net need help parsing a substring

I have a value I am capturing from an Http Request
Dim someValue As String = Request.Params("search")
Here is the value of my string:
?MyId1=VALUE1&MyId2=VALUE2&MyBoolen=True
I am trying to capture VALUE2. I tried the below code, but haven't had any success.
If Not String.IsNullOrEmpty(someValue) Then
Dim x = someValue.Substring(someValue.IndexOf("&"c) + 1)
If Not String.IsNullOrEmpty(someValue) Then
Dim y = x.Substring(someValue.IndexOf("="c) + 1)
End If
End If
How can I do this?
It looks like you're overthinking this. The Request object will let you look up the MyId2 value directly:
Dim MyId2 As String = Request.QueryString("MyId2")
It's also possible this is a nested query string, where what you actually have is something more like this:
/?search=%3FMyId1%3DVALUE1%26MyId2%3DVALUE2%26MyBoolen%3DTrue
This would give you the original string after the runtime URL Decodes the search element. In that case, you should look at the HttpUtility.ParseQueryString() method, rather than trying to do this yourself:
Dim search As String = Request.Params("search")
Dim searchValues As NameValueCollection = HttpUtility.ParseQueryString(search)
Dim MyId2 As String = searchValues("MyId2")
Which could even be written as a one-liner if we really wanted:
Dim MyId2 As String = HttpUtility.ParseQueryString(Request.Params("search"))("MyId2")
But if you really wanted to parse this by hand, one of the nice things about this is everything should be URL-encoded. This means you don't have worry about stray & or = characters as part of the data, and a simple Split() call should be safe:
Dim MyId2 As String = ""
Dim items = someValue.Substring(1).Split("&"c)
For Each item As String In Items
Dim parts = item.Split("="c)
If parts(0) = "MyId2" Then
MyId2 = parts(1)
Exit For
End If
Next
Or
Dim parts() As String = someValue.Substring(1).Split("&"c).
Select(Function(s) s.Split("="c)).
FirstOrDefault(Function(p) p(0) = "MyId2")
Dim MyId2 As String = If(parts IsNot Nothing, parts(1), "")

Secret message encrypt/decrypt ÅÄÖ

I need to add this encryptdecrypt code ÄÖÅ characters, but i don't know how?
Here's my code:
Public Function EncryptDecryptString(ByVal inputString As String, Optional ByVal decrypt As Boolean = False) As String
Dim sourceChars As String = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim resultChars As String = "36N8lkXruq94jMZInPpshR xHc2mTQb7eYai5vGWDzFdoC0wKSBt1EOgVALJfUy"
Dim result As String
If decrypt Then
result = New String(inputString.Select(Function(c) sourceChars(resultChars.IndexOf(c))).ToArray())
Else
result = New String(inputString.Select(Function(c) resultChars(sourceChars.IndexOf(c))).ToArray())
End If
Return result
End Function
You current code will work (as well as it does for English characters) if you simply add the Swedish characters to both sourceChars and resultChars like this.
Dim sourceChars As String = " ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÅabcdefghijklmnopqrstuvwxyz0123456789äöå"
Dim resultChars As String = "äöå36N8lkXruq94jMZInPpshR xHc2mTQb7eYai5ÄÖÅvGWDzFdoC0wKSBt1EOgVALJfUy"
However, your code will fail if the input string contains any character that you are not expecting (for example a tab character or newline). Here is a version of the function that doesn't throw an exception on an unexpected character, but simply uses it without encrypting that character (for serious encryption, it would be better to get an exception).
Public Function EncryptDecryptString(ByVal inputString As String, Optional ByVal decrypt As Boolean = False) As String
Dim sourceChars As String = " ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÅabcdefghijklmnopqrstuvwxyz0123456789äöå"
Dim resultChars As String = "äöå36N8lkXruq94jMZInPpshR xHc2mTQb7eYai5ÄÖÅvGWDzFdoC0wKSBt1EOgVALJfUy"
Dim result() As Char = inputString
Dim inChars As String = If(decrypt, resultChars, sourceChars)
Dim outChars As String = If(decrypt, sourceChars, resultChars)
For i As Integer = 0 To inputString.Length - 1
Dim pos As Integer = inChars.IndexOf(inputString(i))
If pos >= 0 Then result(i) = outChars(pos)
Next
Return result
End Function

how to get the fix substring from dynamic string content?

I am developing VB.NET windows app. in VS 2010.
I want to get the substring
$CostCenterId|4^10
from the below string .
PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$
The position of current string ($CostCenterId|4^10) in the sequence may be change.
but it will always between the two $ sign.
I have written the below code, but confused abt what to write next ?
Public Sub GetSubstringData()
dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
sDiscription.Substring(CostIndex,
End Sub
Have a look into the Split function of a string. This allows you to split a string into substrings based on a specified delimiting character.
You can then do this:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Debug.WriteLine("$" + sfullString.Split("$"c)(3))
Result: $CostCenterId|4^10
You will probably want to do some error checking to make sure the string actually contains the data you expect though.
However looking at the data, what you have is a string containing key-value pairs so you would be better to have a property to hold the CostCenterId and extract the data like this:
Public Property CostCenterId As String
Public Sub Decode(ByVal code As String)
For Each pair As String In code.Split("$"c)
If pair.Length > 0 AndAlso pair.Contains("|") Then
Dim key As String = pair.Split("|"c)(0)
Dim value As String = pair.Split("|"c)(1)
Select Case key
Case "CostCenterId"
Me.CostCenterId = value
End Select
End If
Next
End Sub
Then call it like this:
Decode("PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$")
Why not split() the string by $ into an array, and then look for the element which contains CostCenterId
This should work:
Dim token = "$CostCenterId"
Dim costIndexStart As Integer = sfullString.IndexOf(token)
Dim costIndexEnd As Integer = sfullString.IndexOf("$", costIndexStart + token.Length)
Dim cost As String = sfullString.Substring(costIndexStart, costIndexEnd - costIndexStart + 1)
Result: "$CostCenterId|4^10$"
If you want to omit the dollar-signs:
Substring(costIndexStart + 1, costIndexEnd - costIndexStart - 1)
Try something like this:
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
auxNum = sDiscription.IndexOf("$"c, CostIndex) - CostIndex
sResult = sDiscription.SubString(CostIndex, auxNum)
Your string,
Dim xString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Substring process,
xString = xString.Substring(xString.IndexOf("$CostCenter"), xString.IndexOf("$", xString.IndexOf("$CostCenter") + 1) - xString.IndexOf("$CostCenter"))
Try this Code:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian" _
& "Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim sp() As String = {"$"}
Dim ar() As String = sfullString.Split(sp, StringSplitOptions.RemoveEmptyEntries)
Array.Sort(ar)
MsgBox("$" & ar(0))

Split string after the = sign

I can't seem to work out how to get a value from my string using VB.net
If I have a string in my textbox that says:
WWW-Authenticate: Digest realm="MyServer",qop="auth",algorithm="MD5",maxbuf=1000,nonce="3b010c090c0a0000c0a80157c7007f03c5",opaque="4e6573732041636365737320436f6e74"
How can I get each of the values after the = in the string.
I have tried using
Dim s = "WWW-Authenticate: Digest realm='MyServer',qop='auth',algorithm='MD5',maxbuf=1000,nonce='3b010c090c0a0000c0a80157c7007f03c5',opaque='4e6573732041636365737320436f6e74'"
Dim pattern = "="
Dim matches = Regex.Matches(s, pattern)
Dim values = matches.OfType(Of Match).Select(Function(m) m.Value)
For Each v In values
MsgBox(v)
Next
But it only returns the = in the messagebox.
I want to be able to get just the part after the = sign.
Anyone able to help?
I have tried using the following but it still includes the realm= qop= etc.. in the string. (but includes it at the end of the next item.
Dim s = "WWW-Authenticate: Digest realm='Ness Access Control',qop='auth',algorithm='MD5',maxbuf=1000,nonce='3b010c090c0a0000c0a80157c7007f03c5',opaque='4e6573732041636365737320436f6e74'"
Dim result_array As Array = Split(s, "=", 6)
For Each v In result_array
MsgBox(v)
Next
Regular Expressions!
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim s As String = "WWW-Authenticate: Digest realm='MyServer',qop='auth',algorithm='MD5',maxbuf=1000,nonce='3b010c090c0a0000c0a80157c7007f03c5',opaque='4e6573732041636365737320436f6e74'"
'Regular Expression, matches word before equals, and word after equals
Dim r As New Regex("(\w+)\='([^']+)'")
'All the matches!
Dim matches As MatchCollection = r.Matches(s)
For Each m As Match In matches
'm.Groups(1) = realm, qop, algorithm...
'm.Groups(2) = MyServer, auth, MD5...
Console.WriteLine(m.Groups(2))
Next
Console.ReadLine()
End Sub
End Module
And if you want everything in a nice key-value dictionary:
Dim dict As New Dictionary(Of String, String)
For Each m As Match In matches
'm.Groups(1) = realm, qop, algorithm...
'm.Groups(2) = MyServer, auth, MD5...
dict(m.Groups(1).ToString()) = dict(m.Groups(2).ToString())
Next
A case for a specific string extension.
How to transform a specific formatted string in a Dictionary with keys and values
Public Module StringModuleExtensions
<Extension()>
Public Function ToStringDictionary(ByVal str as String, _
ByVal OuterSeparator as Char, _
ByVal NameValueSeparator as Char) _
As Dictionary(of String, String)
Dim dicText = New Dictionary(Of String, String)()
if Not String.IsNullOrEmpty(str) then
Dim arrStrings() = str.TrimEnd(OuterSeparator).Split(OuterSeparator)
For Each s in arrStrings
Dim posSep = s.IndexOf(NameValueSeparator)
Dim name = s.Substring(0, posSep)
Dim value = s.Substring(posSep + 1)
dicText.Add(name, value)
Next
End If
return dicText
End Function
End Module
Call with
Dim test = "WWW-Authenticate: Digest realm=""MyServer"",qop=""auth"",algorithm=""MD5"", maxbuf=1000,nonce=""3b010c090c0a0000c0a80157c7007f03c5"",opaque=""4e6573732041636365737320436f6e74"""
Dim dict = test.ToStringDictionary(","c, "="c)
For Each s in dict.Keys
Console.WriteLine(dict(s))
Next
(probably you need to remove the WWW-Authenticate line before.
You are looking for the split() function.
Dim logArray() As String
logArray = Split(s, "=")
For count = 0 To logArr.Length - 1
MsgBox(logArray(count))
Next

How i can get selected parts from string?

How i get string like
'EJ0004','EK0001','EA0001'
from string like
{Emaster.Emp_Code}='EJ0004' OR {Emaster.Emp_Code}='EK0001' OR {Emaster.Emp_Code}='EA0001'
in VB.NET?
You can use a regular expression.
Example:
Sub Main
Dim s = "{Emaster.Emp_Code}='EJ0004' OR {Emaster.Emp_Code}='EK0001' OR {Emaster.Emp_Code}='EA0001'"
Dim pattern = "('\w*')"
Dim matches = Regex.Matches(s, pattern)
Dim values = matches.OfType(Of Match).Select(Function(m) m.Value)
For Each v in values
Console.WriteLine(v)
Next
Console.WriteLine(String.Join(",", values))
End Sub
Output:
'EJ0004'
'EK0001'
'EA0001'
'EJ0004','EK0001','EA0001'
there are many ways you could do this, here i offer one simple way:
dim yourString as string = 'This is the variable which holds your initial string
dim newString as string = yourString.replace("{Emaster.Emp_Code}=", "").replace(" OR ",",")
Now newString will hold 'EA0001' Or whatever.
If you want it without the '' then do
dim newString as string = yourString.replace("{Emaster.Emp_Code}=", "").replace("'","").replace(" OR ",",")