string replace not working at all - asp.net

I am reading a text file and I need to replace a few areas with new text that I marked with {0}, {1}, {2}, {3}, {4}, {5}, {6}.
So I load in the text, save it to a string variable, and then use String.Replace but it's not working.
For i As Integer = 0 To 6
fileText.Replace("{" & i & "}", DisplayStudentData(i))
Next
And DisplayStudentData looks like this:
Protected Function DisplayStudentData(ByVal itemNumber As Integer) As String
Dim dsItem As String = ""
If itemNumber <> -1 Then
Select Case itemNumber
Case 0
dsItem = "testFirstName"
Case 1
dsItem = "testTitle"
Case 2
dsItem = "testClass"
Case 3
dsItem = "testTeacher"
Case 4
dsItem = "testDept"
Case 5
dsItem = "testEmail"
Case 6
dsItem = "testPhone"
End Select
End If
Return dsItem
End Function
It seems like the above should work, but it doesn't.
Any help would be greatly appreciated.
Thanks!
Ok I figured it out...
I put all the data items into an array, then did this after loading the text file:
fileText = String.Format(fileText, dArr(0), dArr(1), dArr(2), dArr(3), dArr(4), dArr(5), dArr(6))
Is this a good way of doing it?

fileText = fileText.Replace("{" & i & "}", DisplayStudentData(i))
Replace returns a new string. It does not modify the string from which it was called.
You could also do this:
fileText = String.Format(fileText, Enumerable.Range(0,7).Select(Function(i) DisplayStudentData(i)).ToArray())
Why isn't DisplayStudentData just an array in the first place (which would make string.Format() even easier)?

on another note, If you know the string will always stay the same
you could do something like
dim myTestString = "{0} {1} {2} {3} {4} {5} {6}"
dim result as string = string.format(myTeststring, "testFirstName",
"testTitle", "testClass", "testTeacher", "testDept", "testEmail", "testPhone")
you could always make it a property of your studentdata object.

Related

Cannot get the last row of data

In my ASP.NET application, i need to read the CSV file and insert into sql server.
and it was strange that it treat the 1st row (column name) as LineNumber=2.
but i found that my code cannot read the last row of the CSV file.
Dim CSV_content As String = ""
Dim CSVFilePathName As String = Server.MapPath("~/XXX/" & filename)
If File.Exists(CSVFilePathName) = True Then
'Response.Write("exists")
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(CSVFilePathName)
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {","}
afile.HasFieldsEnclosedInQuotes = True
Dim LastName As String = ""
Dim FirstName As String = ""
Dim DisplayName As String = ""
Dim EmailName As String = ""
Dim dc As New dcHRISDataContext
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
'insert into tmp db
If afile.LineNumber > 2 Then
Dim newRecord1 As New XXX
dc.XXX.InsertOnSubmit(newRecord1)
newRecord1.LastName = CurrentRecord(0).Trim
newRecord1.FirstName = CurrentRecord(1).Trim
newRecord1.DisplayName = CurrentRecord(1).Trim
newRecord1.DirEmail = CurrentRecord(3).Trim
newRecord1.GetFileDate = DateTime.Now
newRecord1.GetFileName = filename
dc.SubmitChanges()
End If
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
End If
Wow, this is the dumbest issue that I have seen.
Anyhow, Apparently the last row in the TextFieldParser is -1, and not LastRowWithValuesIndex + 1. So what happens is this.
You read the data of the last line (this is fine)
The reader skips to the next line to prepare the next line to read (this is fine)
You get the afile.LineNumber, now set to the next line. Which is -1
at this point. (this is dumb although understandable, not your fault)
Your if statement wont let you in because hey you are on line -1.
Loop ends, skipping last row in the CSV.
All you have to do is to read the line number of the row before reading the data:
Dim i As Integer = afile.LineNumber
CurrentRecord = afile.ReadFields
If i > 2 Then
etc

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")

remove double linebreaks in string

I am developing a asp.net web application, i have a string (with a value in it from a database), with multiple lines that i put in a TextBox with mulitline type. (textarea)
Now the problem is, that in the string are multiple lines, with much empty space. so i want the remove only the double linebreaks.
example of my textbox:
+++++++++++++++++++++++++++++++++++++++++++++++++++++
{empty}
{empty}
'This is some text in the textbox on line 3
'some text on line 4
{empty}
'some text on line 6
{empty}
{empty}
'some text on line 9
{empty}
+++++++++++++++++++++++++++++++++++++++++++++++++++++
now somehow i want to remove line 1 and 2, and line 7 and 8
thanks in advance
Here is the solution:
'now rebuild your example string
Dim Empty As String = Chr(13) & Chr(10)
Dim Sb As New System.Text.StringBuilder
Sb.Append("+++++++++++++++++++++++++++++++++++++++++++++++++++++")
Sb.Append(Empty)
Sb.Append(Empty)
Sb.Append(Empty & "This is some text in the textbox on line 3")
Sb.Append(Empty & "some text on line 4")
Sb.Append(Empty)
Sb.Append(Empty & "some text on line 6")
Sb.Append(Empty)
Sb.Append(Empty)
Sb.Append(Empty & "some text on line 9")
Sb.Append(Empty)
Sb.Append(Empty)
Sb.Append("+++++++++++++++++++++++++++++++++++++++++++++++++++++")
Dim YourString As String = Sb.ToString
MessageBox.Show(YourString)
'now replace the double empty
Dim result As String
result = YourString.Replace(Empty & Empty & Empty, Empty)
MessageBox.Show(result)
NOTE: This solution has been tested OK with Visual Studio 2010.
This will get rid of all empty lines.
Dim splt() As Char = New Char() {ControlChars.Lf, ControlChars.Cr}
Dim lines() As String = TextBox1.Text.Split(splt, StringSplitOptions.RemoveEmptyEntries)
TextBox1.Lines = lines
This looks like it will get rid of multiple newlines
Dim s As String = TextBox1.Text.Replace(Environment.NewLine, ControlChars.Cr)
Dim lines As New List(Of String)
lines.AddRange(s.Split(New Char() {ControlChars.Cr}))
For x As Integer = lines.Count - 1 To 1 Step -1
If lines(x) = "" AndAlso lines(x - 1) = "" Then
lines.RemoveAt(x)
End If
Next
TextBox1.Lines = lines.ToArray
The way I usually do this is to convert all of the various line breaks into a single one that I can manage, de-dupe and convert back to vbNewLine:
'//Convert all line break types to vbCr/ASCII 13
T = T.Replace(vbNewLine, vbCr).Replace(vbLf, vbCr)
'//Loop until all duplicate returns are removed
Do While T.Contains(vbCr & vbCr)
T = T.Replace(vbCr & vbCr, vbCr)
Loop
'//Check to see if the string has one at the start to remove
If T.StartsWith(vbCr) Then T = T.TrimStart(Chr(13))
'//Convert back to standard windows line breaks
T = T.Replace(vbCr, vbNewLine)
The following code removes double empty lines at the beginning, and also double empty lines anywhere in the textbox.
Dim myText as String = TextBox1.Text
myText = Regex.Replace(myText, "^(\r\n\r\n)(.*)", "$2")
myText = Regex.Replace(myTextt, "(.*\r\n)(\r\n\r\n)(.*)", "$1$3")
TextBox1.Text = myText
In the example given, it would remove lines 1 and 2, and lines 7 and 8.

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