Get value of a string that is passed as parameter - vb.net

I need to pass in parameters to my sub/function.
When the parameter is passed, the value in the string, I would like to get the value evaluated and sent as:
Dim strParams As String = drRow(0)
' drRow is a row from DB Table. the value in drRow(0) =
' "#FromDate=""" & Now.AddDays(-10).ToShortDateString & """&#ToDate=""" & Now.AddDays(-4).ToShortDateString "
I would like to see this converted to:
Dim strFinal as string
strFinal = ProcessString(strParams)
End Result should be:
strFinal = "#FromDate=10/09/2011&#ToDate=10/15/2011"
Any ideas how I can do this. I am getting the initial string from DB, I need to convert to the final string, I am not able to figure out how to write the "ProcessString" function.
Thanks for looking.

"IF" you can change your parameter statement to something simple like:
#FromDate=;-10;#ToDate=;-4
Then you can do something like this:
Dim strParams As String = "#FromDate=;-10;#ToDate=;-4"
Dim value As String = String.Empty
Dim parts() As String = strParams.Split(";"c)
If parts.Length = 4 Then
Dim fromDays As Integer
Dim toDays As Integer
If Integer.TryParse(parts(1), fromDays) AndAlso Integer.TryParse(parts(3), toDays) Then
value = parts(0) + Now.AddDays(fromDays).ToShortDateString + parts(2) + Now.AddDays(toDays).ToShortDateString
End If
End If
MessageBox.Show("Value = " & value)
If it's anything more complicated than that then you will have to start parsing every part of your string with lots of If and Select statements-- you should probably heed Jim Mischel's advice and try a different approach.

This is the end result of what i used based on suggestions.. Thanks Guys.
Public Function ProcessParameters(ByVal strParams As String) As String
Dim arrParams() As String
'strParams = "#FromDate=-10;&#ToDate=-4;&#CompanyID=1"
arrParams = strParams.Split(";")
Dim arrP() As String
Dim strFinalParams As String = ""
For Each strP As String In arrParams
arrP = strP.Split("=")
If arrP(0).ToString.EndsWith("Date") Then
strFinalParams &= arrP(0) & "=" & Now.AddDays(arrP(1)).ToShortDateString
Else
strFinalParams &= arrP(0) & "=" & arrP(1)
End If
Next
Return strFinalParams
End Function
}

Related

Insert a string at specified indexof position using VB.NET

I'm trying to insert the string " " or a blank space in a specified index on a textbox like so:
textbox = heybrowhatsup
I want to insert an " " on the indexes 4, 8 and 14, to get "hey bro whats up", but my code just won't work.
My code:
Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(15, insStr)
Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr)
strRes = strRes.Insert(7, insStr)
strRes = strRes.Insert(12, insStr)
You must use strRes.Insert for second or more.
Any string manipulation creates a new String object. What you're doing is working perfectly in that it is creating a new String with the specified substring inserted at the specified position. As is always the case, if you want that String displayed in your TextBox then you must assign that String to the Text property of that TextBox.
The Space function is useful for formatting output and clearing data in fixed-length strings.
You can use space function as below.
Dim str As String = "heybrowhatsup"
Dim strRes As String = str.Insert(3, Space(1)).Insert(7, Space(1)).Insert(13, Space(1))
Or
You can do the same with insert function.
Dim str As String = "heybrowhatsup"
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr).Insert(7, insStr).Insert(13, insStr)

Split String into Textboxes

I have this URL:
http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>
How to get parts of this into Textboxes?
ie:
Textbox1 = number after ?age=
Textbox2 = number after &Team=
Textbox3 = number after &userID=
If you want to output to a TextBox and can guarantee a set amount of parameters this is quite simple:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
TextBox1.Text = url.Split("?"c)(1).Split("&"c)(0).Split("="c)(1)
TextBox2.Text = url.Split("?"c)(1).Split("&"c)(1).Split("="c)(1)
TextBox3.Text = url.Split("?"c)(1).Split("&"c)(2).Split("="c)(1)
The code looks a little unreadable but it does the job. Note the increase in number on the second Split. This is the output:
Now what I would do is further checking to ensure the parameters are there and that they have values:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
Dim parameters As String = Nothing
If url.Contains("?") Then
parameters = url.Split("?"c)(1)
End If
Dim age As Integer = 0
Dim team As Integer = 0
Dim userId As Integer = 0
If parameters IsNot Nothing Then
For Each parameter In parameters.Split("&"c)
If parameter.Contains("=") Then
If parameter.ToLower().StartsWith("age") Then
Integer.TryParse(parameter.Split("="c)(1), age)
ElseIf parameter.ToLower().StartsWith("team") Then
Integer.TryParse(parameter.Split("="c)(1), team)
ElseIf parameter.ToLower().StartsWith("userid") Then
Integer.TryParse(parameter.Split("="c)(1), userId)
End If
End If
Next
End If
TextBox1.Text = age.ToString()
TextBox2.Text = team.ToString()
TextBox3.Text = userId.ToString()
The output is the same as above but I have done further checking. I'm sure even more checking could be put in place but I think this will give you a good start.
What I like to do is store both the name and the value of the parameter using a Dictionary which can come in handy so thought I would show you this approach:
Dim url As String = "http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>"
Dim urlParameters As New Dictionary(Of String, String)
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Dim kp() As String = param.Split("="c)
urlParameters.Add(kp(0), kp(1))
Next
End If
'ouput
For Each parameter In urlParameters
Debug.WriteLine("Key: " & parameter.Key & " Value:" & parameter.Value)
Next
This is a screenshot of the output:
If you only want to look at the value of the parameter and output that then you could simply do this instead of adding to a Dictionary:
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Debug.WriteLine(param.Split("="c)(1))
Next
End If
In this case the output will be:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=100&userID=1109"
Dim temp As String = url.Substring(url.IndexOf("?")+1)
Dim args() As String
args = temp.Split("&")
Dim pair() As String
For Each arg As String In args
pair = arg.Split("=")
console.WriteLine(pair(0))
console.WriteLine(pair(1)) ' <--- value after =
Next

Splitting a full name string to separate variables (first, middle and last) without using the split function

So I was given the task to bifurcate a string with a full name and then print out the first and last name separately. For instance, input: Steve Robertson, output: First name: Steve Last name: Robertson.
I succeeded, it was fairly easy. But I'm having having trouble in dividing a full name string to first, last and middle. Here's what I've done so far.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim temp1 As String = ""
Dim integer1 As Integer = 1
Console.WriteLine("Enter the string you want to bifurcate: ")
string1 = Console.ReadLine()
While integer1 <> 0
integer1 = InStr(string1, " ")
Console.WriteLine(string1)
string2 = Left(string1, integer1)
Console.WriteLine(string2)
string3 = Mid(string1, integer1 + 1)
Console.WriteLine(string3)
string4 = Mid(string1, integer1 + 1)
Console.WriteLine(string4)
string1 = string4
End While
Console.WriteLine("First name is: " & string2)
Console.WriteLine("Second name is: " & string3)
Console.WriteLine("Third name is: " & string4)
Console.ReadKey()
End Sub
Keep in mind that I'm only printing almost every single variable to see what their value is during the iteration. I can only use the len() function and whatever is already in the code.
EDIT:
So I fiddled around and finally got the thing, without the loop, but I was wondering if there was a cleaner/right way to do this without repeating the variables and also not needing to create any new ones either.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim integer1 As Integer
Console.WriteLine("Enter the string you want to split: ")
string1 = Console.ReadLine()
integer1 = InStr(string1, " ")
string2 = Left(string1, integer1)
string3 = Mid(string1, integer1 + 1)
integer1 = InStr(string3, " ")
string4 = Left(string3, integer1)
string3 = Mid(string3, integer1 + 1)
Console.WriteLine("The first name is: " & string2)
Console.WriteLine("The middle name is: " & string4)
Console.WriteLine("The last name is: " & string3)
Console.ReadKey()
End Sub
Here is one way to do it. Loop through the characters from the input of the user. Continue to do so concatenating them together and throw them into a List(Of String) that way the can be easily written out at the end... This account's for multiple spaces as well if there's more than one in between names. Also I put some comment's into the code so it can be easier to understand.
Note: This is only one way to do it... (there are other ways)
CODE TRIED AND TESTED
Dim nList As New List(Of String)
Dim uStr As String = String.Empty
Console.WriteLine("Enter the string you want to bifurcate: ")
uStr = Console.ReadLine()
If Not String.IsNullOrEmpty(uStr) Then 'Make sure something was entered...
Dim tStr As String = String.Empty
'Loop through user's input...
Do Until uStr = String.Empty
For Each c As Char In uStr
If Not Char.IsWhiteSpace(c) Then 'If it's a space we can add to the current string...
tStr &= c.ToString
Else
'We can assume its another section of the name...
Exit For
End If
Next
'If its a space, remove it from current string...
If String.IsNullOrEmpty(tStr) Then uStr = uStr.Remove(0, tStr.Length + 1) : Continue Do
'Add the string to the list, could be first name, middle or lastname?
If nList.Count = 0 Then
nList.Add("First Name: " & tStr)
ElseIf nList.Count = 1 Then
nList.Add("Middle Name: " & tStr)
ElseIf nList.Count = 2 Then
nList.Add("Last Name: " & tStr)
End If
'Now we can remove what we got from the users input...
uStr = uStr.Remove(0, tStr.Length)
tStr = String.Empty
Loop
End If
'Finally write out the values...
Console.WriteLine(String.Join(Environment.NewLine, nList.ToArray))
Console.ReadLine()
Screenshot Of Program
Maybe something like this
Dim fullName = "Juan Perez"
Dim name = fullName.Substring(0, fullName.IndexOf(" "))
Dim lastName = fullName.Substring(fullName.IndexOf(" ") + 1)
How to separate full name string
I would suggest that you design extension methods that will return First and Last Name
Module Module1
<Extension()>
Public Function returnFirst(ByVal fullName As String) As String
Return fullName.Substring(0, fullName.IndexOf(" "))
End Function
<Extension()>
Public Function returnLast(ByVal fullName As String) As String
Return fullName.Substring(fullName.IndexOf(" ") + 1)
End Function
End Module
'call it
'import module1
Dim Name as string = 'FirstName LastName'
MessageBox.Show(NAME.returnFirst)
MessageBox.Show(NAME.returnLast)

convert double quote string to string array in vb.net

How can I convert below string,
"[""1"",""2"",""3""]"
To this,
["1","2","3"]
I have try this without success:
Replace(string, """", "")
In vb.net - you should try like this,
Dim stringVar As String = "[""1"",""2"",""3""]"
stringVar.Replace("""", "")
Also check this to use Replace function.
If I understood correctly you can try something like this :
Dim s As String = "[""1"",""2"",""3""]"
Dim collection As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(s, "\d+")
Dim svals As String = ""
For Each m As System.Text.RegularExpressions.Match In collection
If svals = String.Empty Then
svals = m.Value
Else
svals = svals & "," & m.Value
End If
Next
Dim rr() As String
rr = svals.Split(",") ' Result as array of string
Demo

Substring and return list of comma separated characters

Domain\X_User|X_User,Domain\Y_User|Y_User,
I'm using a SSRS report and I'm receiving the above value, I want to write visual basic function in the report ( Custom code) to split the above string and return the following value:
X_User,Y_User
I tried to write this code inside a custom code of the report body:
Public Function SubString_Owner(X As String) As String
Dim OwnerArray() As String = Split(X, ",")
Dim Names As String
Dim i As Integer = 0
While i <= OwnerArray.Length - 1
Dim NamesArr As String() = Split(OwnerArray(0), "|")
Names = NamesArr(1) + ","
i += 1
End While
Return Names
End Function
The problem is when trying to split OwnerArray(i), it gives an error but when using a fixed value, like zero, it builds fine. Can anyone figure out why this is?
Here is a more generic solution that will work with any number of items:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s))
Dim usersWithoutDomains As IEnumerable(Of String) = domainsAndUsers.Select(Function(s) s.Remove(0, s.IndexOf("\") + 1))
Dim users As IEnumerable(Of String) = usersWithoutDomains.Select(Function(s) s.Remove(s.IndexOf("|")))
Dim result As String = users.Aggregate(Function(s, d) s & "," & d)
Or if you want it as a single-line function, here:
Function Foo(sourceString As String) As String
Return sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s)).Select(Function(s) s.Remove(0, s.IndexOf("\") + 1)).Select(Function(s) s.Remove(s.IndexOf("|"))).Aggregate(Function(s, d) s & "," & d)
End Function
EDIT:
You may have to add Imports System.Linq to the top. Not sure if SSRS can use LINQ or not. If not, then here is a similar solution without LINQ:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c)
Dim usersWithoutDomains As String = String.Empty
For Each domainUser As String In domainsAndUsers
usersWithoutDomains &= domainUser.Remove(0, domainUser.IndexOf("\") + 1) & ","
Next
Dim strTest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User"
MsgBox(strTest.Split("|")(0).Split("\")(1) & " " & strTest.Split("|")(1).Split("\")(1))
Here's a simple way that will work with variable data as long as the pattern you've shown is strongly followed:
Imports System.Linq
Dim strtest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
'This splits the string according to "|" and ",". Now any string without _
a "\" is the user and Join adds them together with `,` as a delimiter
Dim result As String = Join((From s In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Where Not s.Contains("\")
Select s).ToArray, ",")
Just in case LINQ is unavailable to you here's a different way to the same results without LINQ:
Dim result As String = ""
For Each s As String In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
If Not s.Contains("\") Then
result += s & ","
End If
Next
result = result.TrimEnd(",".ToCharArray)