After converting c# to vb.net there is an error - vb.net

maybe there is the best solution to the error problem I am facing
thanks
'error End of statement expected
Public Property Name() As String Implements ISearchable.Name = String.Empty
'Character constant must contain exactly one character and Expression expected
txtTotal.Text = $"TOTAL" & vbLf & "{Order.GetTotal(record.SessionId).ToString("C2")}"

As per the answer from #41686d6564standsw.Palestine so perfect
Public Property Name As String = String.Empty Implements ISearchable.Name
txtTotal.Text = $"TOTAL{vbLf}{Order.GetTotal(record.SessionId).ToString("C2")}"
and also As per the answer from #Craig so perfect
txtTotal.Text = $"TOTAL{Order.GetTotal(record.SessionId).ToString("C2")}"

Related

How to solve system.invalidcastexception in vb.net

Well, i have this piece of code. I want to store the contents of a textbox into an array of strings (i prefered to do it with a list of strings) and then to print each element of the array into another textbox. However when i try to compile this code i get this error message:
System.InvalidCastException: 'Conversion from string "" to int is not valid'
FormatException: input string is not in the correct format
Any suggestions?
Public Class NewUser
Dim textUser As String
Dim strUserName As New List(Of String)
Private Sub btnCreateUser_Click(sender As Object, e As EventArgs) Handles btnCreateUser.Click
textUser = txtNewUser.Text
If textUser <> "" Then
strUserName.Add(textUser)
txtNewUser.Clear()
Else
MsgBox("Username or Password is missing. Try again!")
End If
For Each i As String In strUserName
TextBox1.Text = String.Join(",", strUserName(i))
Next i
End Sub
End Class
It's not clear to me at all what you're trying to do here:
For Each i As String In strUserName
TextBox1.Text = String.Join(",", strUserName(i))
Next i
For starters, i is a string and you're trying to use it like an integer as an index of an array. But even if you were to correct it to this:
String.Join(",", i)
That's still trying to join one string. That probably won't compile either, but even if it does it won't logically do anything. Aside from that, you're overwriting TextBox1.Text every time the loop iterates, so at best it's only ever going to equal the last value in the array.
If you're just trying to join the array into that text box, that's one line:
TextBox1.Text = String.Join(",", strUserName)
No loop required.

Multiple string delimiters

I'm a total beginner in the VB language and I have a string in the format:
Smith, Alex (asmith#gmail.com)
I'm attempting to isolate "asmith" from this string. I'm assuming that we would have to split at the "(" and then at the "#" and obtain the 1st index?
Any help is appreciated.
I'm assuming that we would have to split at the "(" and then at the "#" and obtain the 1st index?
Your approach is correct. A literal translation of your algorithm to VB.NET would be:
Dim firstPartOfMailAddress = text.Split("("c)(1).Split("#"c)(0)
Explanation:
"("c is a character literal. Split expects a character, not a string (that would be "(").
Arrays are zero-based in VB.NET and indexed using the (...) operator. Thus, you take the second part (1) of the first split and the first part (0) of the second split.
Notes:
This code does not include any error handling and will fail horribly if the text does not contain the character (.
An alternative would be to extract the value using a regular expression, but if your are new to the language, splitting is a much easier option.
Here is an option for you:
Dim input = "Smith, Alex (asmith#gmail.com)"
Dim output= input.Split("("c, "#"c)(1)
use class :
Imports System.Globalization
Imports System.Text.RegularExpressions
Public Class RegexUtilities
Dim invalid As Boolean = False
Public Function IsValidEmail(strIn As String) As Boolean
invalid = False
If String.IsNullOrEmpty(strIn) Then Return False
' Use IdnMapping class to convert Unicode domain names.
Try
strIn = Regex.Replace(strIn, "(#)(.+)$", AddressOf Me.DomainMapper,
RegexOptions.None, TimeSpan.FromMilliseconds(200))
Catch e As RegexMatchTimeoutException
Return False
End Try
If invalid Then Return False
' Return true if strIn is in valid e-mail format.
Try
Return Regex.IsMatch(strIn,
"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250))
Catch e As RegexMatchTimeoutException
Return False
End Try
End Function
Private Function DomainMapper(match As Match) As String
' IdnMapping class with default property values.
Dim idn As New IdnMapping()
Dim domainName As String = match.Groups(2).Value
Try
domainName = idn.GetAscii(domainName)
Catch e As ArgumentException
invalid = True
End Try
Return match.Groups(1).Value + domainName
End Function
End Class
and use code in form and customzition :
Dim util As New RegexUtilities()
Dim emailAddresses() As String = {"david.jones#proseware.com", "d.j#server1.proseware.com",
"jones#ms1.proseware.com", "j.#server1.proseware.com",
"j#proseware.com9", "js#internal#proseware.com",
"j_9#[129.126.118.1]", "j..s#proseware.com",
"js*#proseware.com", "js#proseware..com",
"js#proseware.com9", "j.s#server1.proseware.com",
"""j\""s\""""#proseware.com", "js#contoso.中国"}
For Each emailAddress As String In emailAddresses
If util.IsValidEmail(emailAddress) Then
Console.WriteLine("Valid: {0}", emailAddress)
Else
Console.WriteLine("Invalid: {0}", emailAddress)
End If
Next

How to harness auto-completion of strings?

I'm writing an application in which I have to pass strings as parameters. Like these:
GetValue("InternetGatewayDevice.DeviceInfo.Description")
GetValue("InternetGatewayDevice.DeviceInfo.HardwareVersion")
CheckValue("InternetGatewayDevice.DeviceInfo.Manufacturer")
ScrambleValue("InternetGatewayDevice.DeviceInfo.ModelName")
DeleteValue("InternetGatewayDevice.DeviceInfo.ProcessStatus.Process.1")
The full list is about 10500 entries, and i tought that i'd be really lost in searching if i misspell something.
So I am trying to declare a namespace for every string segment (separated by ".") and declare the last as a simple class that widens to a String of its FullName (except the base app namespace):
Class xconv
Public Shared Widening Operator CType(ByVal d As xconv) As String
Dim a As String = d.GetType.FullName
Dim b As New List(Of String)(Strings.Split(a, "."))
Dim c As String = Strings.Join(b.Skip(1).ToArray, ".")
Return c
End Operator
End Class
So I'd have these declarations:
Namespace InternetGatewayDevice
Namespace DeviceInfo
Class Description
Inherits xconv
End Class
End Namespace
End Namespace
This way IntelliSense is more than happy to autocomplete that string for me.
Now I'd have to do this for every possible string, so I opted (in order to retain my sanity) to make a method that does that:
Sub Create_Autocomlete_List()
Dim pathlist As New List(Of String)(IO.File.ReadAllLines("D:\list.txt"))
Dim def_list As New List(Of String)
Dim thedoc As String = ""
For Each kl As String In pathlist
Dim locdoc As String = ""
Dim el() As String = Strings.Split(kl, ".")
Dim elc As Integer = el.Length - 1
Dim elz As Integer = -1
Dim cdoc As String
For Each ol As String In el
elz += 1
If elz = elc Then
locdoc += "Class " + ol + vbCrLf + _
"Inherits xconv" + vbCrLf + _
"End Class"
Else
locdoc += "Namespace " + ol + vbCrLf
cdoc += vbCrLf + "End Namespace"
End If
Next
locdoc += cdoc
thedoc += locdoc + vbCrLf + vbCrLf
Next
IO.File.WriteAllText("D:\start_list_dot_net.txt", thedoc)
End Sub
The real problem is that this is HORRIBLY SLOW and memory-intense (now i dot a OutOfMemory Exception), and I have no idea on how Intellisense would perform with the (not available in the near future) output of the Create_Autocomlete_List() sub.
I believe that it would be very slow.
So the real questions are: Am I doing this right? Is there any better way to map a list of strings to auto-completable strings? Is there any "standard" way to do this?
What would you do in this case?
I don't know how Visual Studio is going to perform with thousands of classes, but your Create_Autocomlete_List method can be optimized to minimize memory usage by not storing everything in memory as you build the source code. This should also speed things up considerably.
It can also be simplified, since nested namespaces can be declared on one line, e.g. Namespace First.Second.Third.
Sub Create_Autocomlete_List()
Using output As StreamWriter = IO.File.CreateText("D:\start_list_dot_net.txt")
For Each line As String In IO.File.ReadLines("D:\list.txt")
Dim lastDotPos As Integer = line.LastIndexOf("."c)
Dim nsName As String = line.Substring(0, lastDotPos)
Dim clsName As String = line.Substring(lastDotPos + 1)
output.Write("Namespace ")
output.WriteLine(nsName)
output.Write(" Class ")
output.WriteLine(clsName)
output.WriteLine(" Inherits xconv")
output.WriteLine(" End Class")
output.WriteLine("End Namespace")
output.WriteLine()
Next
End Using
End Sub
Note the use of File.ReadLines instead of File.ReadAllLines, which returns an IEnumerable instead of an array. Also note that the output is written directly to the file, instead of being built in memory.
Note Based on your sample data, you may run into issues where the last node is not a valid class name. e.g. InternetGatewayDevice.DeviceInfo.ProcessStatus.Process.1 - 1 is not a valid class name in VB.NET. You will need to devise some mechanism to deal with this - maybe some unique prefix that you could strip in your widening operator.
I'm also not sure how usable the resulting classes will be, since presumably you would need to pass an instance to the methods:
GetValue(New InternetGatewayDevice.DeviceInfo.Description())
It seems like it would be nicer to have Shared strings on a class:
Namespace InternetGatewayDevice
Class DeviceInfo
Public Shared Description As String = "Description"
Public Shared HardwareVersion As String = "HardwareVersion"
' etc.
End Class
End Namespace
So you could just reference those strings:
GetValue(InternetGatewayDevice.DeviceInfo.Description)
However, I think that would be a lot harder to generate without creating name clashes due to the various levels of nesting.

Converting Fixed length statement from VB6 to VB.Net

We perform a protocol based data sending to device where the device requires a formatted data packets.
the sample packet data is XXFSXXXFSXXXXXXXFSXXXXXX. The X mentioned is the max length size of each string. if data is less than string max length it should be filled with NULL character like ..11FS123FS1234XXXX (the remaining X will be filled with NULL).
I am just trying to convert one of VB6 function to VB.Net and below is the converted statement where i am facing issue
Option Strict Off
Option Explicit On
Imports Microsoft.VisualBasic.Compatibility.VB6
Imports System
Imports System.Runtime.InteropServices
Module FunctionCmd_Msg
Public FunCommand_Msg As Fun_CommandMessage = Fun_CommandMessage.CreateInstance()
'Function Command Message
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _ _
Public Structure Fun_CommandMessage
<VBFixedString(1)> Public one As String
<VBFixedString(1)> Public two As String
<VBFixedString(3)> Public three As String
Dim five As String
<VBFixedString(8)> Public four As String
Public Shared Function CreateInstance() As Fun_CommandMessage
Dim result As New Fun_CommandMessage
result.one = String.Empty
result.two = String.Empty
result.three = String.Empty
result.four = String.Empty
result.five = String.Empty
End Function
End Structure
End Module
assuming:
one = "1"
two = "1"
three = "123"
four = "5678"
five = "testing"
FS = character (field separator)
on concatenating the strings i need a fixed length string such like this:
one & two & FS & three & FS & five & FS & four
output: since four is a fixed length string of 8 length remaining 4 characters should be filled with null as below
11 FS 123 FS testing FS 5678XXXX
Fixed-length strings simply make no sense in .NET any more. Microsoft tried to provide a similar class for easier upgrade but the truth is that you should change your code depending on usage:
What did the fixed-length string do in your VB6 code? Was it for no good reason? Then use a normal String in .NET.
Was it for interop with a C API? Then use marshalling to set a size for an array in the C API call.
Just forget about the fixed length, and use regular vb.net strings. They will return fine to whatever calls that code, including interop.
So, just pad your strings, and you off to the races.
In fact, build a Msg class that does the dirty work for you.
This looks quite nice to me:
NOTE how I set this up that you ONLY define the length of the string in ONE place. (so I use len(m_string) to determine the length from THEN on in the code.
Also, for debug and this example, in place of vbcharNull (which you should use), I used X for testing.
Now, in your code?
Just use this:
Dim Msg As New MyMsg
With Msg
.one = "A"
.two = "B"
.three = "C"
.four = "D"
.Five = "E"
End With
Debug.WriteLine(Msg.Msg("*") & vbCrLf)
Debug.WriteLine("total lenght = " & Len(Msg.Msg("X").ToString))
Output:
A*B*CXX*EXXXXXXX*DXXXXXXX
total lenght = 25
I note in your code that you have FIVE before FOUR - but if that is what you want, then no problem
Note that the class ALWAYS maintains the lengths for you.
So just paste this code into your module or even a new separate class.
Public Class MyMsg
'Dim cPad As Char = vbNullChar
Dim cPad As Char = "X"
Private m_one As String = New String(cPad, 1)
Private m_two As String = New String(cPad, 1)
Private m_three As String = New String(cPad, 3)
Private m_four As String = New String(cPad, 8)
Private m_five As String = New String(cPad, 8)
Public Property one As String
Get
Return m_one
End Get
Set(value As String)
m_one = MyPad(value, m_one)
End Set
End Property
Public Property two As String
Get
Return m_two
End Get
Set(value As String)
m_two = MyPad(value, m_two)
End Set
End Property
Public Property three As String
Get
Return m_three
End Get
Set(value As String)
m_three = MyPad(value, m_three)
End Set
End Property
Public Property four As String
Get
Return m_four
End Get
Set(value As String)
m_four = MyPad(value, m_four)
End Set
End Property
Public Property Five As String
Get
Return m_five
End Get
Set(value As String)
m_five = MyPad(value, m_five)
End Set
End Property
Public Function Msg(FS As String) As String
Return m_one & FS & m_two & FS & m_three & FS & m_five & FS & m_four
End Function
Private Function MyPad(str As String, strV As String) As String
Return Strings.Left(str & New String(Me.cPad, Len(strV)), Len(strV))
End Function
End Class
As noted, change the commented out line of "X" for the char back to vbCharNull.
And of course you STILL get to choose the delimiter. I used
Msg.Msg("*")
so I used a "*", but you can use space, or anything you want.

How to query the current URL to see if it contains a certain string

What I want to do is take the full contents of the address bar and see if everything after the site path (i.e. everything after the question mark), contains a certain string, and if it does then return a path using the site URL and that string.
An example and some code to make things understandable:
If I'm on www.example.com/?blah=image I want the code to look for the string image (after the question mark to prevent sites with image in the name to screw things up) and if it exists return www.example.com/images/ (with that current domain being looked up and not manually written as this will be used on mutliple sites)
Below is what I have written so far.
Public ReadOnly Property StorageRoot() As String
Get
Dim currentabsolute As String = System.Web.HttpContext.Current.Request.Url.AbsolutePath
Dim currentdomain As String = CurrentDomain
If currentabsolute.Contains("Media") Then
Return System.AppDomain.CurrentDomain.BaseDirectory & "\media\"
ElseIf currentabsolute.Contains("Docs") Then
Return System.AppDomain.CurrentDomain.BaseDirectory & "\docs\"
ElseIf currentabsolute.Contains("Image") Then
Return System.AppDomain.CurrentDomain.BaseDirectory & "\images\"
End If
End Get
End Property
I know CurrentDomain won't return anything and System.Web.HttpContext.Current.Request.Url.AbsolutePath doesn't seem to return what I am looking for so those are part of what I am hoping to get help with.
Any help will be appreciated and if you need any more clarification just ask.
Edit: Updated code
You're looking for the Request.QueryString member. To read the value of a specific query string parameter, try something along the lines of:
If Request.QueryString("Media") IsNot Nothing Then
Return currentdomain + "/media/"
ElseIf ...
If a query string does not contain the key in question, accessing that index will return nothing; otherwise it will return the value of that parameter. For instance, you could test to see if the string was constructed as ?Media=MyMedia with If Request.QueryString("Media") = "MyMedia".
If you want the raw query string itself, you could parse the Request.RawUrl member for everything after the question mark with something like:
Dim queryString As String = Request.RawUrl.SubString(Request.RawUrl.IndexOf("?"c) + 1)
Try this and let me know how it does for you:
Imports System.Web
...
Public ReadOnly Property StorageRoot() As String
Get
Dim requestUrl As Uri = HttpContext.Current.Request.Url
Dim newUrl As New UriBuilder(requestUrl.Scheme, requestUrl.Host, requestUrl.Port, HttpContext.Current.Request.ApplicationPath)
Dim currentQuery As String = requestUrl.Query
If String.IsNullOrEmpty(currentQuery)
' What to do if there is no query string?
Else If currentQuery.Contains("Media", StringComparer.InvariantCultureIgnoreCase) Then
newUrl.Path = newUrl.Path + "/media/"
ElseIf currentQuery.Contains("Docs", StringComparer.InvariantCultureIgnoreCase) Then
newUrl.Path = newUrl.Path + "/docs/"
ElseIf currentQuery.Contains("Image", StringComparer.InvariantCultureIgnoreCase) Then
newUrl.Path = newUrl.Path + "/images/"
End If
Return newUrl.ToString()
End Get
End Property