asp.net textareafor - keep newlines - c#

I have an input form used for a forum, where users can post messages.
I capture the comment content text using Html.TextAreaFor.
However, when the user creates newlines in the text (by pressing Enter), those newlines aren't "retained" when I redisplay the new message in the forum.
Is the only solution to replace \n with </br> on the server when processing the message (and if so - how do I go about doing that in the best way?), or is there an automated way of achieving it straight away?
Thank you!

You can do it in two places, either when you accept the data from the user or when you display it. I'd recommend when you get it from them since it will only have to do it once. Either way, you can replace it like this:
myHtml = myHtml.Replace("\n","<br />");
It's as easy as that.

Related

Why is C#.net removing my newline characters when I do a replace, and how can I stop it?

I have a textarea saving to a database that I'm using to send as the body of an email.
I allow tokens to be used as placeholders for information pertaining to that message.
If I don't touch the placeholders at all the email sends just fine with the line breaks exactly as they are in the textbox (the email is being sent in plain text).
However, when I start using the replace function, the new line characters start disappearing and all the lines get pushed together.
For example.
Body.Replace("%procedure%", CurrentOrder.Description);
Will replace the text %procedure%, but will also remove the newline at the end of the line. Even if the newline isn't directly after the text being replaced.
Any ideas?
edit:
For now, I'm just replacing "\n" with "<br />" and sending the email as HTML. I would rather keep it as plain text as I don't have control over the recipients at all.
EDIT 2: It appears to be an issue with outlook itself, not the email. I just viewed the exact same email in gmail, and the format was correct.
Outlook removes new lines unless the line ends with two spaces.
If you're testing the emails to an account that uses Outlook try adding two spaces before your new lines and see if that fixes it.
If its for HTML I would first of all replace the new lines with BR tags:
String str = str.Replace(Environment.NewLine, "<br/>");
either that, or instead of using a multiline textarea, use a JQuery or AJAX HTML Editor or something.
Maybe you could swap in a place holder (like above, and then swap it out?)

How do I implement a search box in an ASP.NET MVC application?

I need to implement a "Search" box on a C# MVC application that I'm writting.
I've never had to implement a "Search" box before and I've been looking for some best practices and I'm not quite finding what I'm looking for.
I really like how the search works on stackoverflow.
If I type in a few random words, it navigates to the url http://stackoverflow/search?q=few+random+words.
If I type in title:random, it navigates to the url https://stackoverflow.com/search?q=title%3Arandom
What is happening both on the client (when I hit the enter key) and on the server to make the search happen?
I've purposely left out any thoughts I've already had on what is happening because I don't want to bias the answers (or show my ignorance).
EDIT: I'm adding some specifics to this question.
Where and how are the search terms transformed into the querystring parameters? ie few random words transformed into few+random+words,title:random transformed into title%3Arandom
Where and how is few+random+words tranformed into variables used in a query?
Is the query just one big Where clause that keeps appending "and" for each item that lands between the + signs?
I guess you could parse through the strings and do some replaces to achieve 1 and 2 but it sure looks like there is something already available that would automatically convert (and revert) the search strings. I'm trying to be prepared for my user's typing ANYTHING in the search box.
These posts will help you in understanding how it works
https://blog.stackoverflow.com/2008/10/stack-overflow-search-now-51-less-crappy/
https://blog.stackoverflow.com/2009/07/stack-overflow-search-now-61-less-crappy/
https://blog.stackoverflow.com/2011/01/stack-overflow-search-now-81-less-crappy/
Those URL's use what is called a query string. It is a "GET" request that allows the client script (javascript) as well as the back end code retrieve the users "query". In a URL whenever you see a '?' it is the beginning of the query string. This allows somebody to be like:
http://google.com?q=Stuff%20to%20Search%20here
Multiple parameters can be added via &anothercommand=somethingelse
Thus allowing a program or script to invoke a search on google without having to type anything into the box.
You can get access to the query string using the C# "Request.QueryString["parameter"]" where in this case the parameter for those stack overflow URL's would be "q".
After that, you query your database and return the results. Since I'm not sure how good at coding you are, I am not sure if you're trying to ask for the Web site, or the C# SQL side. If I am wrong, apologies.
On the Client:
The way I imagine it is happening on the client is that the script on the textbox when the form is submitted redirects to the url you mentioned and adds in those query parameters into the url string. Don't forget to url encode. This is built into javascript. i.e. space ' ' becomes '%20'
When the form submits, the server code does a check to see if there are any query string parameters of the form "q". If there are, and it is not null, it would query the database, returning that in one of a few ways, most likely through a server control.
1) That is what URL encoding is. It is a list of characters that are not supported in a URL. Thus they need to be changed. There is a standard set such as %20 for space. In javascript, you would redirect to the results page with the query string you want. prior to redirecting, use the information here to encode it. i.e. change ' ' into + or %20 (it really should be %20, I find + is usually the internet explorer way.
)
2) Query string works like a hashtable of key pair values. Using the Request.QueryString, you can select the key "q" and receive the string "few random words". That would then get substituted into your SQL query. This is done on the C# side as a very first check to see if the parameter q exists.
3) you can do your query many different ways. However, searching for "and" etc will give you many different results. What you can do is parse out a list of common words, and then rank results based on the number of results of each word. i.e. in the most simplistic of searches which would be ill advised for LARGE databases "..... Where like '%word% or '%word2%' etc. To get each word, do a string.split.
As much as I hate to do it, I have to answer my own question. What I couldn't understand is how the search words where seemingly automatically transformed into querystring encoded parameters (ie all spaces where replaced with the + sign vs. being replace with %20). I didn't understand how that was being achieved and I like it so I wanted the same abilities.
In the end, what I should have done was copy the html from SO and tried it out on my own MVC site because it turns out that the encoding is built in/automatic. I didn't have to do anything to get the functionality.
Here is the basic HTML for the search box:
<form id="frmsearch" action="~/Catalog/Search" method="get">
<input id="q" name="q" value="#q" style="width:275px;"/>
<input id="submit" name="submit" type="submit" style="font-weight:bold;" value="Search" />
</form>
Now, if you type "few random words" in the text box named "q" and click the submit button, the form action automatically takes you to "~/Catalog/Search?q=few+random+words" without any additional coding.
Now for the best part, in the controller code, the "q" parameter is automatically available as "few random words" without any additional coding as well.
Example:
public ActionResult Search(string q)
{
//q = "few random words" (no need to remove '+' signs)
var model = GetSearchResults(q)
return View(model);
}
The only thing I haven't tested out it how it would handle scripting attacks but I think I'm going to get that for free as well. : )
Hope this helps anyone who stumbles across this answer. Thank you to everyone who submitted answers trying to help. I'm sorry if my question wasn't clear enough.

multiline textbox to string

I have a multiline textbox that I wish to convert to a string,
I found this
string textBoxValue = textBox1.Text.Replace(Environment.NewLine,"TOKEN");
But dont understand TOKEN what is TOKEN? whitespace or /n newline ?
If this is the incorrect answer then Please let me know of the correct way of doing this
Thanks
In the code snippet you gave, "TOKEN" is any value you wish to insert, such as an HTML <br /> tag, more Environment.NewLines for formatting, or just some random delimiter that will later allow you to split the text on it.
A very simple example:
string text = textBox1.Text.Replace(Environment.NewLine, "^"); // a random token
string[] lines = test.Split( '^' );
If you are handling input from a textbox available on the web, you also need to take into account XSS (http://en.wikipedia.org/wiki/Cross-site_scripting). Also, in a real scenario I would split on a more complex token and make sure to handle multiple carriage returns in the input value.
EDIT: now that I see your actual requirements, this code may do what you need:
// replace newlines with a single whitespace
string text = textBox1.Text.Replace(Environment.NewLine, " ");
EDIT #2:
further I need to enter this data into
SQLite and rewrite his whole
application, The company does not wish
to have information from the previos
application inputted to the new
database, there are hyperlinks etc
inbedded in the content , so if there
is a way I can make the text box only
accept RAW data this would be the
best.
Regular Expressions are the way to go for something like this, unless the data is structured enough to load into an XML or HTML DOM and process. You can build regular expressions in a variety of tools (do a Google search for a free online tester and you will find many). Once you have determined the expressions you need, you can use the Regex object in C# to match, replace, etc.
http://msdn.microsoft.com/en-us/library/ms228595(VS.80).aspx
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(v=VS.100).aspx
As it stands, "TOKEN" is just a meangingless string, unless it is elsewhere in your code? You can replace "TOKEN" with any text you like.
Edit:
Okay, so you say you're removing NewLine's from your client's text. So you would do it like this. Paste their text into a textBox called textBox2, then use the following:
textBox2.Text = textBox2.Text.Replace(Environment.NewLine, string.Empty);

Stop Auto-hyperlink in Outlook, Gmail etc

My web application sends emails to users. The email contains a link for further user action. Our security standards require that the link in the email cannot be clickable. However, the email clients recognize https:// in the email and auto-link the URL.
Any idea on how to stop the email clients to auto-link. I am thinking if I skip the https://, it may stop the auto-linking. But, if I have to keep the https:// is there any way to avoid auto-linking.
The link in the email is dynamically constructed in the c# code.
I know this thread is old, but I just had this issue myself, and wasn't thrilled by the gif image fix. If you're working with HTML emails, a slightly nicer solution is to break up the link text with a non-rendering tag that tricks the parser. I'm a fan of a simple non-existant <z>:
https<z>://securesite.</z>com
It even works in Stack Overflow posts: https://securesite.com.
Hope this helps someone.
I too wish to disable this, as I believe this is a "valid" use as to not wanting auto-linking (one reason is the designer wants it that way, and they are currently paying the bills).
In email sent that has no images, the header has the domain name in it:
EXTRANET.EXAMPLE.COM
I even put inline styles to make sure it stays white on a black background:
<span style="font-size: 1.5em;padding: 0.5em 0;text-transform: uppercase; font-weight:bold;color:#FFFFFF;text-decoration:none;">EXTRANET.EXAMPLE.COM</span>
Gmail makes this a link, adds an underline and also turns it bright blue instead of the intended white.
At first I tried replacing the dots with . which made it look fine, but didn't fool the Gmail parser.
So, I added a spanned space which work just fine (i.e. it fools Gmail's parser):
<span style="font-size: 1.5em;padding: 0.5em 0;text-transform: uppercase; font-weight:bold;color:#FFFFFF;text-decoration:none;">EXTRANET<span style="font-size:0.1em"> </span>.<span style="font-size:0.1em"> </span>EXAMPLE<span style="font-size:0.1em"> </span>.<span style="font-size:0.1em"> </span>COM</span>
Just create a plain <span> tag around the colon (<span>:</span>) or something like that :)
Replace the actual text with a small GIF image that looks like text.
Email parsers will not recognize text within an image.
My application has a similar security requirement. The solution we used was to add an underscore to the beginning of the URL (_http://).
Sorry to dredge up an old question, but I just tried the answer suggested by pieman72, and found that it didn't work within Outlooks 2007–2013. However, wrapping the individual elements of the URL within table cells did fool the Outlook parser:
Visit <table><tr><td>www.</td><td>website</td><td>.com</td></tr></table> for more information.
I ran a sample message through the Email On Acid test suite and found that it eluded the parser on all the major e-mail clients which automatically convert URLs (Outlook, iOS, Android 2.2, etc.) I did not run any deliverability tests.
#raugfer suggests in another answer: wrap the email/URL with an anchor.
<a name="myname">test#email.com</a>
Quoting from that answer:
Since the text is already wrapped in a hyperlink, Gmail gives up and
leave it alone. :)
(Note: also worked for Apple mail client.)
Necroing the question, I know, but it's relevant... I'd like to present a reasonable scenario where Gmail's auto-linking (at least - haven't tested other clients) doesn't make sense.
A client has an application form on their site, where visitors fill out some personal information and submit it. The system then sends a notification email to the client, presenting the information the visitor supplied.
I'm wanting to enhance the email sent to the client by adding a <textarea> at the bottom, with the fields the visitor filled out presented in CSV format so that the client can simply copy it all and paste it into a spreadsheet.
Gmail, however, fails to recognize that the URLs and email addresses are inside a <textarea> tag, and "helpfully" adds the ... link code around the URL/email - inside the <textarea>. This results in the raw HTML link code showing up in the <textarea>.
This is what i did:
Replace all instances of "." with <span style=""color:transparent; font-size:0px;"">[{</span>.<span style=""color:transparent; font-size:0px;"">}]</span>
Replace all instances of "#" with <span style=""color:transparent; font-size:0px;"">[{</span>#<span style=""color:transparent; font-size:0px;"">}]</span>
These characters stopped it parsing links and email addresses, but aren't visible to the user. The negative is that when you copy and paste an email for example, you end up with: "test1{[{.}]}domain{[{.}]}com"
.

Removing <div>'s from text file?

Ive made a small program in C#.net which doesnt really serve much of a purpose, its tells you the chance of your DOOM based on todays news lol. It takes an RSS on load from the BBC website and will then look for key words which either increment of decrease the percentage chance of DOOM.
Crazy little project which maybe one day the classes will come uin handy to use again for something more important.
I recieve the RSS in an xml format but it contains alot of div tags and formatting characters which i dont really want to be in the database of keywords,
What is the best way of removing these unwanted characters and div's?
Thanks,
Ash
If you want to remove the DIV tags WITH content as well:
string start = "<div>";
string end = "</div>";
string txt = Regex.Replace(htmlString, Regex.Escape(start) + "(?<data>[^" + Regex.Escape(end) + "]*)" + Regex.Escape(end), string.Empty);
Input: <xml><div>junk</div>XXX<div>junk2</div></xml>
Output: <xml>XXX</xml>
IMHO the easiest way is to use regular expressions. Something like:
string txt = Regex.Replace(htmlString, #"<(.|\n)*?>", string.Empty);
Depending on which tags and characters you want to remove you will modify the regex, of course. You will find a lot of material on this and other methods if you do a web search for 'strip html C#'.
SO question Render or convert Html to ‘formatted’ Text (.NET) might help you, too.
Stripping HTML tags from a given string is a common requirement and you can probably find many resources online that do it for you.
The accepted method, however, is to use a Regular expression based Search and Replace. This article provides a good sample along with benchmarks. Another point worth mentioning is that you would require separate Regex based lookups for the different kinds of unwanted characters you are seeing. (Perhaps showing us an example of the HTML you receive would help)
Note that your requirements may vary based on which tags you want to remove. In your question, you only mention DIV tags. If that is the only tag you need to replace, a simple string search and replace should suffice.
A regular expression such as this:
<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>
Would highlight all HTML tags.
Use this to remove them form your data.

Categories

Resources