I want to have extra characters that will serve as divider my to string - vb.net

Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
For Each word In list
MsgBox(list)
Next
Catch ex As Exception
End Try
End Sub
The value of paramater "value" is this :
7/28/2016 10:19:27 AM#-!-#Alex17282016#-!-#Outgoing#-!-#Alex#-!-#Alex#-!-#Text#-!-#1ST
Then I split the values and change the word Outgoing to Incoming.
Now I want my string to to look like this again
7/28/2016 10:19:27 AM#-!-#Alex17282016#-!-#Incoming#-!-#Alex#-!-#Alex#-!-#Text#-!-#1ST
Sorry for my grammar. I hope you understand my question

Below I have edited your code you already have to make the string the way you want it after changing "Outgoing" to "Incoming":
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Dim newValue as String = ""
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
For Each word In list
newValue = newValue & word
Next
value = newValue
Catch ex As Exception
End Try
End Sub
Or as Mark in the comments stated you could use string.join instead of a loop:
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
Dim newValue As String = String.Join("#-!-#", list)
Catch ex As Exception
End Try
End Sub
Below is code I think would work better, as it does it one line of code and doesn't need to split the string apart and put it back together:
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
value = value.replace("#-!-#Outgoing#-!-#", "#-!-#Incoming#-!-#")
End Sub

Related

Get a specific value from the line in brackets (Visual Studio 2019)

I would like to ask for your help regarding my problem. I want to create a module for my program where it would read .txt file, find a specific value and insert it to the text box.
As an example I have a text file called system.txt which contains single line text. The text is something like this:
[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]
What i want to do is to get only the last name value "xxx_xxx" which every time can be different and insert it to my form's text box
Im totally new in programming, was looking for the other examples but couldnt find anything what would fit exactly to my situation.
Here is what i could write so far but i dont have any idea if there is any logic in my code:
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(C:\test\test_1\db\update\network\system.txt)
For i = 1 To 3
If line.Contains("Last Name=" & i) Then
field.Add(line.Substring(line.IndexOf("=") + 2))
End If
Next
Next
End Sub
Im
You can get this down to a function with a single line of code:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Return File.ReadLines(fileName).Where(Function(line) RegEx.IsMatch(line, "[[[]Last Name=(?<LastName>[^]]+)]").Select(Function(line) RegEx.Match(line, exp).Groups("LastName").Value)
End Function
But for readability/maintainability and to avoid repeating the expression evaluation on each line I'd spread it out a bit:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Dim exp As New RegEx("[[[]Last Name=(?<LastName>[^]]+)]")
Return File.ReadLines(fileName).
Select(Function(line) exp.Match(line)).
Where(Function(m) m.Success).
Select(Function(m) m.Groups("LastName").Value)
End Function
See a simple example of the expression here:
https://dotnetfiddle.net/gJf3su
Dim strval As String = " [Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim strline() As String = strval.Split(New String() {"[", "]"}, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(s) Not String.IsNullOrWhiteSpace(s)) _
.ToArray()
Dim lastnameArray() = strline(1).Split("=")
Dim lastname = lastnameArray(1).ToString()
Using your sample data...
I read the file and trim off the first and last bracket symbol. The small c following the the 2 strings tell the compiler that this is a Char. The braces enclosed an array of Char which is what the Trim method expects.
Next we split the file text into an array of strings with the .Split method. We need to use the overload that accepts a String. Although the docs show Split(String, StringSplitOptions), I could only get it to work with a string array with a single element. Split(String(), StringSplitOptions)
Then I looped through the string array called splits, checking for and element that starts with "Last Name=". As soon as we find it we return a substring that starts at position 10 (starts at zero).
If no match is found, an empty string is returned.
Private Function readcrnFile() As String
Dim LineInput = File.ReadAllText("system.txt").Trim({"["c, "]"c})
Dim splits = LineInput.Split({"]["}, StringSplitOptions.None)
For Each s In splits
If s.StartsWith("Last Name=") Then
Return s.Substring(10)
End If
Next
Return ""
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = readcrnFile()
End Sub
You can easily split that line in an array of strings using as separators the [ and ] brackets and removing any empty string from the result.
Dim input As String = "[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim parts = input.Split(New Char() {"["c, "]"c}, StringSplitOptions.RemoveEmptyEntries)
At this point you have an array of strings and you can loop over it to find the entry that starts with the last name key, when you find it you can split at the = character and get the second element of the array
For Each p As String In parts
If p.StartsWith("Last Name") Then
Dim data = p.Split("="c)
field.Add(data(1))
Exit For
End If
Next
Of course, if you are sure that the second entry in each line is the Last Name entry then you can remove the loop and go directly for the entry
Dim data = parts(1).Split("="c)
A more sophisticated way to remove the for each loop with a single line is using some of the IEnumerable extensions available in the Linq namespace.
So, for example, the loop above could be replaced with
field.Add((parts.FirstOrDefault(Function(x) x.StartsWith("Last Name"))).Split("="c)(1))
As you can see, it is a lot more obscure and probably not a good way to do it anyway because there is no check on the eventuality that if the Last Name key is missing in the input string
You should first know the difference between ReadAllLines() and ReadLines().
Then, here's an example using only two simple string manipulation functions, String.IndexOf() and String.Substring():
Sub Main(args As String())
Dim entryMarker As String = "[Last Name="
Dim closingMarker As String = "]"
Dim FileName As String = "C:\test\test_1\db\update\network\system.txt"
Dim value As String = readcrnFile(entryMarker, closingMarker, FileName)
If Not IsNothing(value) Then
Console.WriteLine("value = " & value)
Else
Console.WriteLine("Entry not found")
End If
Console.Write("Press Enter to Quit...")
Console.ReadKey()
End Sub
Private Function readcrnFile(ByVal entry As String, ByVal closingMarker As String, ByVal fileName As String) As String
Dim entryIndex As Integer
Dim closingIndex As Integer
For Each line In File.ReadLines(fileName)
entryIndex = line.IndexOf(entry) ' see if the marker is in our line
If entryIndex <> -1 Then
closingIndex = line.IndexOf(closingMarker, entryIndex + entry.Length) ' find first "]" AFTER our entry marker
If closingIndex <> -1 Then
' calculate the starting position and length of the value after the entry marker
Dim startAt As Integer = entryIndex + entry.Length
Dim length As Integer = closingIndex - startAt
Return line.Substring(startAt, length)
End If
End If
Next
Return Nothing
End Function

Searching Multiple strings with 1st criteria, then searching those returned values with a different criteria and so on

so..
I have a txt file with hundreds of sentences or strings.
I also have 4 comboboxes with options that a user can select from and
each combobox is part of a different selection criteria. They may or may not use all the comboboxes.
When a user selects an option from any combobox I use a For..Next statement to run through the txt file and pick out all the strings that contain or match whatever the user selected. It then displays those strings for the user to see, so that if they wanted to they could further narrow down the search from that point by using the 3 remaining comboboxes making it easier to find what they want.
I can achieve this by using lots of IF statements within the for loop but is that the only way?
No, there are other ways. You can leverage LINQ to get rid of some of those if statements:
Private _lstLinesInFile As List(Of String) = New List(Of String)
Private Function AddClause(ByVal qryTarget As IEnumerable(Of String), ByVal strToken As String) As IEnumerable(Of String)
If Not String.IsNullOrWhiteSpace(strToken) Then
qryTarget = qryTarget.Where(Function(ByVal strLine As String) strLine.Contains(strToken))
End If
Return qryTarget
End Function
Public Sub YourEventHandler()
'Start Mock
Dim strComboBox1Value As String = "Test"
Dim strComboBox2Value As String = "Stack"
Dim strComboBox3Value As String = String.Empty
Dim strComboBox4Value As String = Nothing
'End Mock
If _lstLinesInFile.Count = 0 Then
'Only load from the file once.
_lstLinesInFile = IO.File.ReadAllLines("C:\Temp\Test.txt").ToList()
End If
Dim qryTarget As IEnumerable(Of String) = (From strTarget In _lstLinesInFile)
'Assumes you don't have to match tokens that are split by line breaks.
qryTarget = AddClause(qryTarget, strComboBox1Value)
qryTarget = AddClause(qryTarget, strComboBox2Value)
qryTarget = AddClause(qryTarget, strComboBox3Value)
qryTarget = AddClause(qryTarget, strComboBox4Value)
Dim lstResults As List(Of String) = qryTarget.ToList()
End Sub
Keep in mind this is case sensitive so you may want to throw in some .ToLower() calls in there:
qryTarget = qryTarget.Where(Function(ByVal strLine As String) strLine.ToLower().Contains(strToken.ToLower()))
I think a compound If statement is the simplest:
Dim strLines() As String = IO.File.ReadAllText(strFilename).Split(vbCrLf)
Dim strSearchTerm1 As String = "Foo"
Dim strSearchTerm2 As String = "Bar"
Dim strSearchTerm3 As String = "Two"
Dim strSearchTerm4 As String = ""
Dim lstOutput As New List(Of String)
For Each s As String In strLines
If s.Contains(strSearchTerm1) AndAlso
s.Contains(strSearchTerm2) AndAlso
s.Contains(strSearchTerm3) AndAlso
s.Contains(strSearchTerm4) Then
lstOutput.Add(s)
End If
Next

read specific values from text file

I have the following visual basic code, which is part of a custom class. I want a simple and effective way(use little computer resources) to assign the "value1" value(100) to "_field1","value2" value(8) to "_field2" etc. Any nice ideas? thanks
Private Sub readcrnFile()
'read files and assing values to the properties
Dim sr As New IO.StreamReader(_fileName)
_field1 = sr.ReadToEnd()
_field2 = sr.ReadToEnd()
_field3 = sr.ReadToEnd()
sr.Close()
End Sub
where _fileName is a full path to a text file which looks like this:
value1: 100
value2: 8
value3: 80
Private Sub readcrnFile()
Dim lines = File.ReadLines(_fileName)
For Each line In lines
Dim val = line.Split(":")(1).Trim
'do something with val?
Next
End Sub
Returning a dictionary is trivial:
Private Sub readcrnFile()
Dim dict = File.ReadLines(_fileName).Select(Function(line) line.Split(":")).ToDictionary(Function(parts) parts(0).Trim, Function(parts) parts(1).Trim)
Debug.WriteLine(dict("value1")) 'will print 100
End Sub
Change your _field1, _field2 and _field3 variables to a List(Of String) (i.e. named field) and access to each field using its index (field(0), field(1), field(2)).
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(_filename)
For i = 1 To 3
If line.Contains("value" & i) Then
field.Add(line.Substring(line.IndexOf(":") + 2))
End If
Next
Next
End Sub

String Manipulation with no delimiter

I have a string where I need to replace every character in that string with another value. That string has no delimiter. Is it possible to step through that string and replace every value with a set of predetermined values? I would like to keep it to one function as it is going to live within SSRS
Dim stringToChange As String = "123456ALWRYA"
I would then have to step through the string and replace all off the current values with new ones.
i.e. A=001, B=002, 1=101, 2=102, etc.
Is this possible if the string does not have a delimiter?
Thanks in advance!
SSRS Custom code has a pretty limited dialect, but this worked for me.
Add the following to the report Custom Code:
Function SingleReplace (SingleChar As String) As String
Select Case SingleChar
Case "A"
SingleReplace = "001"
Case "B"
SingleReplace = "002"
Case Else
SingleReplace = SingleChar
End Select
End Function
Function CustomReplace (BaseString As String) As String
Dim NewString As New System.Text.StringBuilder
For Each SingleChar As Char in BaseString
NewString.Append(SingleReplace(SingleChar))
Next
Return NewString.ToString()
End Function
Call this in a report expression with:
=Code.CustomReplace(Fields!MyString.Value)
Works for me in a simple report/table:
This is basically what Styxxy suggested...with a Dictionary for the looking up the values:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim stringToChange As String = "123456ALWRYA"
Debug.Print(stringToChange)
Dim changedString = ConvertString(stringToChange)
Debug.Print(changedString)
End Sub
Private Function ConvertString(ByVal inStr As String) As String
Static dict As New Dictionary(Of Char, String)
If dict.Count = 0 Then
dict.Add("A"c, "001")
dict.Add("B"c, "002")
dict.Add("1"c, "101")
dict.Add("2"c, "102")
' ... etc ...
End If
Dim sb As New System.Text.StringBuilder
For Each c As Char In inStr.ToUpper
If dict.ContainsKey(c) Then
sb.Append(dict(c))
Else
' ... possibly throw an exception? ...
sb.Append(c)
End If
Next
Return sb.ToString
End Function

request.querystring in vb.net

I have this url that i need to decode:
http://gistest:54321/default.aspx?data=%7B%22id%22:%2269403%22,%22longitude%22:%22-143.406417%22,%22latitude%22:%2232.785834%22,%22timestamp%22:%2223-10%2010:12%22%7D
This code changes every time
I use this code:
<%Response.Write(Request.QueryString.Item("data") )%><br/>
<%Response.Write(Request.QueryString.Item("id") )%><br/>
<%Response.Write(Request.QueryString.Item("longitude") )%><br/>
<%Response.Write(Request.QueryString.Item("latitude") )%><br/>
<%Response.Write(Request.QueryString.Item("timestamp") )%><br/>
But i only get this as output, maybe there is an option where to check if data is not null, and then i request.querystring the other parts in data:
{"id"="69403","longitude"="-143.406417","latitude"="32.785834","timestamp"="23-10 10:12"}
This is from
<%Response.Write(Request.QueryString.Item("data") )%>
I really hope I understood the problem correctly. I am assuming you require the values of each key within the query string key called Data? To do so I used the code below:
Dim values() As String = Server.UrlDecode(Request.QueryString("data")).Replace("{", "").Replace("}", "").Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries)
For Each value As String In values
Dim keyValue() As String = value.Split(New Char() {":"}, StringSplitOptions.RemoveEmptyEntries)
Response.Write(keyValue(0).Replace("""", "") & " : " & keyValue(1).Replace("""", "") & "<br/>")
Next
In a nutshell, I decode the QueryString("data"), replace the braces and split the string into an array by using the comma as the first split character. We then end up with an array containing values in the following format "id":"649403".
Thereafter I iterate through the values and split one final time for each value based on the semi-colon (:) character.
With this method you can build and manipulate the data dynamically.
Code Edit
I replaced all references of ":" with "=" to ensure that the time stamp will be correctly retrieved and then split the key values based on =. You can use a select case to assign variables to values if necessary. (Obviously make sure your variable is not declared within the select as it will not be in the right scope for later use!)
If Request.QueryString("data") IsNot Nothing Then
Dim values() As String = Request.QueryString("data").Replace("{", "").Replace("}", "").Replace(""":""", """=""").Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries)
For Each value As String In values
Dim keyValue() As String = value.Split(New Char() {"="}, StringSplitOptions.RemoveEmptyEntries)
Response.Write(keyValue(0).Replace("""", "") & " : " & keyValue(1).Replace("""", "") & "<br/>")
Select Case keyValue(0).ToLower()
Case "id"
Dim id As String = keyValue(1)
End Select
Next
End If
Reflection Edit
Create an instance of your object then retrieve all its properties (Dim properties() As PropertyInfo = myObj.GetType().GetProperties()). Iterate through the properties and set the value where the name is equal to the key. Don't forget to import the System.Reflection library.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim data As String = "%7B%22id%22:%2269403%22,%22longitude%22:%22-143.406417%22,%22latitude%22:%2232.785834%22,%22timestamp%22:%2223-10%2010:12%22%7D"
If data IsNot Nothing Then
Dim myObj As New MyObject
Dim properties() As PropertyInfo = myObj.GetType().GetProperties()
Dim values() As String = Server.UrlDecode(data).Replace("{", "").Replace("}", "").Replace(""":""", """=""").Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries)
For Each value As String In values
Dim keyValue() As String = value.Split(New Char() {"="}, StringSplitOptions.RemoveEmptyEntries)
For Each prop As PropertyInfo In properties
If prop.Name.ToLower = keyValue(0).ToLower.Replace("""", "") Then
prop.SetValue(myObj, keyValue(1), Nothing)
End If
Next
Next
myObj.Save()
End If
End Sub
Public Class MyObject
Private _ID As String
Private _Longitude As String
Private _Latitude As String
Private _Timestamp As String
Public Property ID As String
Get
Return _ID
End Get
Set(value As String)
_ID = value
End Set
End Property
Public Property Longitude As String
Get
Return _Longitude
End Get
Set(value As String)
_Longitude = value
End Set
End Property
Public Property Latitude As String
Get
Return _Latitude
End Get
Set(value As String)
_Latitude = value
End Set
End Property
Public Property Timestamp As String
Get
Return _Timestamp
End Get
Set(value As String)
_Timestamp = value
End Set
End Property
Public Sub Save()
'Save logic here
End Sub
End Class
I think the problem you are running into is that there only is one querystring parameter in the URL you posted, and that is data. The rest of the information is encoded in the data querystring value. The value stored in data almost looks like a JSON/Javascript object, except with an = in between the property names and values instead of a :.
So, basically you won't be able to use Request.QueryString to get the values of id, longitude, latitude, etc. I think your options are to either write some code to parse the value of data yourself or replace the = with : and use a JSON parser for .NET (i.e., the JavascriptSerializer class or JSON.net).
Personally, I would write a method in the codebehind that would return a Dictionary(Of String, Object). In that method just I would just change every "=" to a ":" and then use the JavaScriptSerializer provided with .NET to parse the string. I don't have an ASP.NET instance handy right now, but the following sample I threw together in LinqPad should illustrate the idea:
Sub Main
Dim url = "http://gistest:54321/default.aspx?data=%7B%22id%22=%2269403%22,%22longitude%22=%22-143.406417%22,%22latitude%22=%2232.785834%22,%22timestamp%22=%2223-10%2010:12%22%7D"
Dim uri = New Uri(url)
Dim data = System.Web.HttpUtility.ParseQueryString(uri.Query)("data")
Dim o = ParseData(data)
Console.WriteLine(o("id"))
Console.WriteLine(o("longitude"))
Console.WriteLine(o("latitude"))
Console.WriteLine(o("timestamp"))
End Sub
Function ParseData(data As String) As Dictionary(Of String, Object)
Dim js = new System.Web.Script.Serialization.JavaScriptSerializer()
Dim o = js.DeserializeObject(data.Replace("""=""", """:"""))
ParseData = DirectCast(o, Dictionary(Of String, Object))
End Function
One thing to note about this approach is that I am expecting the url to be in the same format as what you posted. You may need to modify this method to make it more robust to handle different inputs.
If you drop the ParseData function into your codebehind, then something like the following code in your front page should give you the output you are looking for (again, sorry I don't have an ASP.NET instance to test with right now):
<%
Dim o = ParseData(Request.QueryString.Item("data"))
Response.Write(o("id"))
Response.Write("<br />")
Response.Write(o("longitude"))
Response.Write("<br />")
Response.Write(o("latitude"))
Response.Write("<br />")
Response.Write(o("timestamp"))
Response.Write("<br />")
%>