vb.net string concat adds vbCrlf literal to the string - asp.net

I am trying to build a string that includes a newline character and is getting the weirdest result. This string is going to be stored in a SQL database to be later used as part of an email. My code is the following:
Dim strBody As String = "Andy," & Environment.NewLine
When I inspect the value of strBody during a debugging session, it is the following:
"Andy," & vbCrlf
I am obviously expecting is to be more like:
"Andy,"
Knowing that what is after the , is a hidden character.
Ultimately, the problem is... when I include strBody as part of my SQL insert statement, it literally shows up as the following within my SQL insert statement:
'Andy," & vbCrLf & "'
I was using this code yesterday and it worked fine. I am using similar code within another function of the same asp.net project and it works fine. I have tried using + instead of &, I have tried to use vbCrLf instead of Environment.NewLine, I have tried using stringbuilder, I have tried using string.concat. All with the same results where the & vbCrLf is included in strBody.
Is there a setting that I accidentally changed?
I know this is a weird one... Any help is greatly appreciated.

This is only Visual Studio showing you that there is new line character (vbCrLf or Environment.NewLine). If you use that string anywhere, it will be stored correctly.

I believe you will need to use some combination of Char(10) and Char(13):
Dim strBody As String = "'Andy,'" & " + CHAR(13)+CHAR(10) + "
There is a discussion about these and other methods on this thread.

You can do like this if you just need to insert Environment.NewLine inside database.
Dim a As String = """ & Environment.NewLine & """
Dim strBody As String = String.Format("Andy,{0}", a)
'"Andy," & Environment.NewLine & ""

Related

string with 's not getting inserted with insert statement

I am trying to insert a question in database with field in table as nvarchar(max) (sql server 2008 r2)
Code is as follows:
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
Response.Write("<script type='text/javascript' language='javascript'>alert('Question Added Sucessfully!!!')</script>")
BindGrid()
End Sub
when i insert any string with :
what's your name?
then it gives me error:
Incorrect syntax near 's'. Unclosed quotation mark after the character string ')'.
If i simply supply string as:
What is your name?
Then it does not gives me error.
Please help me.
You should be using parameterised queries if possible since simple string insertion directly into a query will, as you have seen, possibly corrupt the query.
In other words, if the text box contains Paddy O'Rourke, your query becomes:
open close what the ?
| | |
insert into QuestionMaster values('Paddy O'Rourke') ...
and you can see the fact that the embedded ' is corrupting the query.
It will also, as you have yet to realise, allow people to perform SQL injection attacks on your database since you're not sanitising the input.
If, for some reason, your shop disallows parameterised queries (as it appears from one of your comments), find another place to work. No, just kidding, but in the presence of such a bone-headed policy, you'll need to sanitise the input yourself.
But that's fraught with danger, I would first try to change such a policy, laying out in no uncertain terms the risks involved.
Well, you should rather make use of Parameterized queries.
This will also avoid SQL Injection.
There may be a chance that your data may contain some special characters like single quotation mark which make your statement fail.
So better to use parameterized query: Parameterized queries do proper substitution of arguments prior to running the SQL query.
SqlCommand insertNewAreaPath = new SqlCommand(
"insert into QuestionMaster (Question, ClientID, KioskID) VALUES(#Question, #ClientID, #KioskID)", con);
insertNewAreaPath.Parameters.Add("#Question", txtQuestion.Text);
insertNewAreaPath.Parameters.Add("#ClientID", ViewState("ClientID"));
insertNewAreaPath.Parameters.Add("#KioskID", ViewState("KioskID"));
insertNewAreaPath.ExecuteNonQuery();
ELSE: use .Replace("'", "''")
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text.Replace("'", "''") & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
You could escape single quote by replacing single quote (') with two single quotes ('') in the txtQuestion.Text.
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text.Replace("'", "''") & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
Response.Write("<script type='text/javascript' language='javascript'>alert('Question Added Sucessfully!!!')</script>")
BindGrid()
End Sub
Replace ' with '' and it will work fine.
Try this
what''s your name?
//declare this variable
String sql="insert into QuestionMaster values('" & txtQuestion.Text & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')";
debug it and you will find where it appears problem.

Return same result even no signal quotation mark in string using RowFilter

I understand I should put the single quotation mark between the string for RowFilter like that
dim TOS as string="04"
rowFilter.RowFilter = "(TOScode= " & "'" & TOS & "')"
I just wonder why the following code still work without single quotation mark.
rowFilter.RowFilter = "(TOScode = " & TOS & ") "
The TOScode field is varchar(2) type in SQL. English is not my native language; please excuse typing errors.
Try this
rowFilter.RowFilter = String.Format("(TOScode = '{0}')", TOS)
OR simply as
rowFilter.RowFilter = String.Format("TOScode = '{0}'", TOS)

convert an empty string (from textbox) to null using ASP.NET

if I don't enter anything in one of the textbox , ASP.NET can't tell an empty textbox and treat it at null... So anyone please help me how to detect an empty textbox and set that to null
i know that this code is ganna work well
If MUSIC_TITLE.Text.Trim() = "" Then
MUSIC_TITLE.Text = Nothing
End If
but i can't use be couse i have a lot of forms in my application so i need somthing or any function exist in the ASP.NET that can handel this
and thats for the insert in a requet the sql server
"insert into Reunion values(" & Convert.ToInt32(ID_Reunion.Text) & ",'" & d.ToString("MM/dd/yyyy") & "'," & Convert.ToInt32(ID_Membre.Text) & ",'" & Type_Reunion.Text & "','" & Session("Nom_GIAC") & "')"
and tnks
This sounds like you're trying to directly store the textbox values in your database.
Please don't do this. If you haven't already, learn about the high risk security threat of SQL Injection and parameterize your INSERTS and UPDATES.
Before setting the parameters, you can convert empty strings to Nothing if required.
Dim musicTitle as String = _
If(String.IsNullOrWhiteSpace(MUSIC_TITLE.Text), Nothing, MUSIC_TITLE.Text)
In your insert sp should be like:
create procedure Insert(#test varchar(50)=NULL)
as
begin
update foo set testCol=#test
end
In c#, use below code, when calling the sp and adding the parameters:
if(txt.Text!=String.Empty)
{
cmd.Parameters.Add("#test",SqlDBType.Varchar,20).Value=txt.Text;
}

Reading CSV in Recordset?

Let me start off by saying that I am very greatful to have a place to go to when I need help with some code and I'm even more thankful when I see people trying to help out, so for everyone here Thank you for looking at my question/problem even if you don't have an answer.
With that said, on with my question/problem:
I have been trying to get this to work but I cannot seem to find the syntax error!! :-(
Can anyone please help me...
Here is the code:
dim strPathtoCSVFolder,strPathtoCSVFile,strPathtoCSVFileTWO
strPathtoCSVFolder="D:\classic_asp\test\" & Request.QueryString("XTNO") & "\Data\"
strPathtoCSVFile="Unit_" & Request.QueryString("XTNO") & "_Year_" & Request.QueryString("year") & "_Q_" & Request.QueryString("q") & "_MERGE_DataCsv.csv"
strPathtoCSVFileTWO="Unit_" & Request.QueryString("XTNO") & "_Year_" & Request.QueryString("year") & "_Q_" & Request.QueryString("q") & "_MERGE_DataCsv_SORTED.csv"
Set Conn = CreateObject("ADODB.Connection")
Set RS = CreateObject("ADODB.Recordset")
Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPathtoCSVFolder & ";Extended Properties=""text;HDR=YES;FMT=Delimited"""
dim strDirInfoX
strDirInfoX="SELECT STATE, SUM(GALLONS) as Total FROM " & strPathtoCSVFile & " GROUP BY STATE "
'''''' response.write strDirInfoX
dim strTxttoMem
dim strsource
strsource="RS.Open " & strDirInfoX & " , Conn, 1, 3, &H0001"
RS.Open strsource
'response.write strsource
redim FieldNames(rs.fields.count)
redim FieldTypes(rs.fields.count)
For i = 0 To (rs.Fields.Count - 1)
FieldNames(i) = cstr(trim(rs.Fields.Item(i).Name))
FieldTypes(i) = cstr(trim(rs.Fields.Item(i).Type))
Next
RS.Close
RS.Open strDirInfoX, Conn, 3, 3, &H0001
Do Until RS.EOF
'''' for i=0 to ubound(FieldNames)-1
''' response.write(FieldNames(i) & " = " & RS.Fields.Item(FieldNames(i)) & "<br>")
strTxttoMem=strTxttoMem & RS("STATE") & RS("total")
'' next
RS.MoveNext
Loop
RS.Close
Conn.Close
dim fs,tfile
set fs=Server.CreateObject("Scripting.FileSystemObject")
set tfile=fs.CreateTextFile(strPathtoCSVFolder & strPathtoCSVFileTWO)
tfile.WriteLine(strTxttoMem)
tfile.close
set tfile=nothing
set fs=nothing
Thank you so much for any help...
Well, without running your code, I spotted an error in this part:
dim strsource
strsource="RS.Open " & strDirInfoX & " , Conn, 1, 3, &H0001"
RS.Open strsource
or to shorten it, you are doing this:
RS.Open "RS.Open " & strDirInfoX & " , Conn, 1, 3, &H0001"
change it to RS.Open strDirInfoX, Conn, 1, 3, &H0001 and that part will run better.
This is almost impossible to answer, there could be multiple errors and much depends on what is declared before, eg an option explicit makes a huge difference (and is advisable).
Since debugging in the browser is difficult at best, you copy this code - that comes from an asp file i guess - and put it in a vbs script, replace the response.write with wscript.echo and run the code.
Then you get an error at some line, correct it and so on, afterward replace the echos's by response.write's and you'r done.
I also recommend useing Firefox and the Firebug plugin to do your testing, you will get more debugging info there, at least use the developer view in Chrome or IE
Success..
Been some time working on VBScript but shouldnt tfile.close be tfile.Close?
Did you try reading the file as a text file rather than connecting to it with an ADODB connection? Since it is a CSV file, you might be able to read it as a plain text file. You can split the content with comma and loop and get what you want.
If you want to access it using ADODB connection, try saving the file with an xlsx extention(Either copy the contents through code or save it manually. The same code might work).
Shamelessly adding a link to my blog on ADO
http://www.blogger.com/blogger.g?blogID=3033014869583885023#editor/target=post;postID=8274119342550879092

How to Validate a textbox+dropdowns in vb for a asp.net form

Previous question which links onto this and has any addition code ref should I forget to link any, I have set it up to email me should someone submit this form and an error occur and right now should that occur for most integer or datetime fields if they fail to validate then it will show me which fields in the email failed and what was input into them.
Problem I'm having now is to validate the drop downs and the textboxs in a similar way to what I with integer and datetime fields so I can display those also in the email in case they error.
present integer and datetime validation
Catch ex As Exception
lblInformation.Text = ("<h4>Unable to save data in database</h4>" + vbNewLine + "The error was '" + ex.Message + "'" + vbNewLine + vbNewLine + vbNewLine + "The SQL Command which falied was:" + vbNewLine + "<strong>" + mySQL + "</strong>" + vbNewLine).Replace(vbNewLine, "<br />" + vbNewLine)
Dim dtb As DateTime
If Not DateTime.TryParse(DateOfBirth, dtb) Then
strEMessageBody.Append("<strong>Date Of Birth:</strong> " & DateOfBirthYear.SelectedItem.Value & "-" & DateOfBirthMonth.SelectedItem.Value & "-" & DateOfBirthDay.SelectedItem.Value & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
Dim iao As Integer
If Not Integer.TryParse(AnyOther, iao) Then
strEMessageBody.Append("<strong>Any Other:</strong> " & rblAnyOther.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
then below the final validation I have the Dim for the email setting but that I sorted out in the other question.
The problem is much earlier in the page I have
Sub Upload_Click(ByVal source As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
Dim Name As String
Which prevents me just using there names as shown above where I would instead call them something else but that doesn't work with strings so my main issue is having some bit of code to check if the strings are valid and for the dropdowns which would either work but always show the data in the email or would hiccup in the code,
Dim imd As Integer
If Not Integer.TryParse(dept, imd) Then
strEMessageBody.Append("<strong>Department:</strong> " & dept.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
below was how it had been setup to record the department
Department = dept.SelectedItem.Value
Department = Replace(Department, "'", "''")
Summary:- Need vb code to validate if strings and dropdowns are valid and the use of try/catch block is another possible solution but I wasn't able to figure out how to implement validation for that either.
Log your values into your database. Setup a logging table called "tblLog" or something else. Record the value of ex.Message or possibly even InnerException (if it exists).
Going hand in hand with Matt's answer, there is a tool that can help you with automatically logging errors to a DB.
It's called ELMAH.
EDIT
Here are 2 validations that you might want to use:
Dim s As String = "some user input in here"
If [String].IsNullOrEmpty(s) Then
' Watch out, string is null or it is an empty string
End If
Dim cb As New ComboBox()
If cb.SelectedItem Is Nothing Then
' Watch out, combo has no item selected
End If
NOTE ComboBox is a WinForm control in this example, but the idea is the same for the ASP.NET counterpart
Since everybodies given up trying to find a solution then I'm just gona close this topic with this post as the answer.

Resources