Replacing a new line character with streamwriter remove everything after it. (ASP.NET, Json, C#) - asp.net

I'm having an unexpected problem which I'm hoping one of you can help me with.
I have an ASP.NET Web API with a number of end points, one of which takes user input, received as JSON, and converts it into an order object which is written to a file in .CSV format. The following is a small snippet of the full code as an example.
using (StreamWriter writer = new StreamWriter(file))
{
writer.Write(escape + order.Notes + escape + delim);
writer.Write(escape + order.Reference1 + escape + delim);
writer.Write(escape + order.Reference2 + escape + delim);
writer.WriteLine();
writer.Flush();
}
The problem I am having is that some users are inclined to add line breaks in
certain fields, and this is causing havoc with my order file. In order to remove
these new line characters, I have tried both of the following methods.
writer.Write(escape + product.Notes.Replace("\n", " ") + escape + delim);
writer.Write(escape + product.Notes.Replace(System.Environment.NewLine, " ") + escape + delim);
However, it seems that, rather than just remove the new line character and carry on writing the rest of the fields, when a new line is encountered, nothing else gets written.
Either everything else gets replace with the " " or nothing else is being written at all, but I'm not sure which.
If I remove the .Replace() the whole file is written again but with extra line breaks.
I hope somebody has experienced this one and knows the answer!

Related

How to remove the new line when reading from UNIX process groovy? [duplicate]

I have a string that contains some text followed by a blank line. What's the best way to keep the part with text, but remove the whitespace newline from the end?
Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.
String trimmedString = myString.trim();
String.replaceAll("[\n\r]", "");
This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":
String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")
Remove newlines only from the end of the line:
String.replaceAll("[\n\r]$", "")
Remove newlines only from the beginning of the line:
String.replaceAll("^[\n\r]", "")
tl;dr
String cleanString = dirtyString.strip() ; // Call new `String::string` method.
String::strip…
The old String::trim method has a strange definition of whitespace.
As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.
Example code.
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");
Or you can strip just the leading or just the trailing whitespace.
You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
It is '\t', U+0009 HORIZONTAL TABULATION.
It is '\n', U+000A LINE FEED.
It is '\u000B', U+000B VERTICAL TABULATION.
It is '\f', U+000C FORM FEED.
It is '\r', U+000D CARRIAGE RETURN.
It is '\u001C', U+001C FILE SEPARATOR.
It is '\u001D', U+001D GROUP SEPARATOR.
It is '\u001E', U+001E RECORD SEPARATOR.
It is '\u001F', U+0
If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().
If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:
Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")
Complete Example:
public class RemoveLineBreaks {
public static void main(String[] args) {
var s = "\nHello world\nHello everyone\n";
System.out.println("before: >"+s+"<");
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
System.out.println("after: >"+s+"<");
}
}
It outputs:
before: >
Hello world
Hello everyone
<
after: >Hello world
Hello everyone<
I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.
To remove newlines from the beginning:
// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);
System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");
and end of a string:
// Trim right
String z = "\n\nfrom the end\n\n";
System.out.println("-" + z.split("\\n+$", 2)[0] + "-");
I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.
Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.
Try this
function replaceNewLine(str) {
return str.replace(/[\n\r]/g, "");
}
String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
System.out.println("Original String : [" + trimStartEnd + "]");
System.out.println("-----------------------------");
System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");
Start of a string = ^ ,
End of a string = $ ,
regex combination = | ,
Linebreak = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]
Another elegant solution.
String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");
For anyone else looking for answer to the question when dealing with different linebreaks:
string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", ""); // Java 8
This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
This passes these tests:
// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));
// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));
// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");

ASP.net VB String builder double double quotes [duplicate]

Everytime I add CharW(34) to a string it adds two "" symbols
Example:
text = "Hello," + Char(34) + "World" + Char(34)
Result of text
"Hello,""World"""
How can I just add one " symbol?
e.g Ideal result would be:
"Hello,"World""
I have also tried:
text = "Hello,""World"""
But I still get the double " Symbols
Furthermore. Adding a CharW(39), which is a ' symbol only produces one?
e.g
text = "Hello," + Char(39) + "World" + Char(39)
Result
"Hello,'World'"
Why is this only behaving abnormally for double quotes? and how can I add just ONE rather than two?
Assuming you meant the old Chr function rather than Char (which is a type).It does not add two quotation mark characters. It only adds one. If you output the string to the screen or a file, you would see that it only adds one. The Visual Studio debugger, however, displays the VB-string-literal representation of the value rather than the raw string value itself. Since the way to escape a double-quote character in a string is to put two in a row, that's the way it displays it. For instance, your code:
text = "Hello," + Chr(34) + "World" + Chr(34)
Can also be written more simply as:
text = "Hello,""World"""
So, the debugger is just displaying it in that VB syntax, just as in C#, the debugger would display the value as "Hello, \"World\"".
The text doesn't really have double quotes in it. The debugger is quoting the text so that it appears as it would in your source code. If you were to do this same thing in C#, embedded new lines are displayed using it's source code formatting.
Instead of using the debugger's output, you can add a statement in your source to display the value in the debug window.
Diagnostics.Debug.WriteLine(text)
This should only show the single set of quotes.
Well it's Very eazy
just use this : ControlChars.Quote
"Hello, " & ControlChars.Quote & "World" & ControlChars.Quote

CSV file (with special characters) upload encoding issue

I am trying to upload a CSV file that has special characters using ServletFileUpload of apache common. But the special characters present in the CSV are being stored as junk characters in the database. The special characters I have are Trademark, registered etc. Following is the code snippet.
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream, "UTF-8") + " detected.");
}
}
I have tried reading it using BufferendReader, used request.setCharacterEncoding("UTF-8"), tried upload.setHeaderEncoding("UTF-8") and also checked with IOUtils.copy() method, but none of them worked.
Please advice how to get rid of this issue and where it needs to be addressed? Is there anything I need to do beyond servlet code?
Thanks
What database are using? What character set is database using? Characters can be malformed in the database rather than in Java code.

how to pass parameter inside Strigbuilder class object?

I am using
string strurl = "Reports/ReportFilter.aspx";
and bind a tag as
AnchorLeftMenuLinks.Append(" href='javascript:OpenDialogue(" + strurl + ");' ");
but it return error as "undefined object AuditReports" as runtime it become like
href="javascript:OpenDialogue(Reports/ReportFilter.aspx);"
but when i add single quotes manually in firebug like
href="javascript:OpenDialogue('Reports/ReportFilter.aspx');"
it works fine.
can anyone suggest me that how to add single quotes in code.Yhankx in advance.
Try this
AnchorLeftMenuLinks.Append(" href='javascript:OpenDialogue(\"" + strurl + "\");' ");
Try:
var javascript = string.Format("href='javascript:OpenDialouge('{0}');'", strurl);
AnchorLeftMenuLinks.Append(javascript);
or:
AnchorLeftMenuLinks.AppendFormat("href='javascript:OpenDialouge('{0}');'", strurl);
Reason behind it was Javascript String because In JavaScript, a string is started and stopped with either single or double quotes. This means that the string was being chopped to: javascript:OpenDialogue( and your function's syntax was being incorrect and thus it was not working.
Thus it was mandatory to place a backslash (\)before each double quote in strurl. This turns each double quote into a string literal.
There are some other special characters also which needed to be placed using \
\' - single quote
\" - Double Quote
\\ - BackSlash
\n - new Line
\t - tab

Webmatrix - formatting MSSQL database query

I am trying to format the output of a query in a WebMatrix 2 CSHTML file. This is the code I am using:
#foreach(var row in db.Query(selectQueryString))
{
#row.Firstname; + " " + #row.lastname; + " " + #row.Entry;
}
I am getting this error:
"CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement"
The first issue is that the semicolons could be confusing to Razor, and they are only confusing matters. So change the line in the brackets to
<text>#row.Firstname #row.lastname #row.Entry</text>
And see if that works. The < text > tags tells Razor to output this directly as HTML and not use it as code. You don't need the + " " because once you're putting out HTML, the spaces come automatically.

Resources