How can I change razor syntax in RazorEngine?
I need to use specific keyword instead of"#" symbol.
For example: $$Model.someField instead of #Model.someField. ("$$" instead of "#").
You can't. Razor is not really designed in a way to do it. Basically (Microsoft.AspNet.)Razor has some specially written parsers which handle "#" in a special manner (by switching parsers). This means the languages (C#, Html in this case) itself need to be compatible with this procedure as well!
If you want to replace "#" with something else you need to rewrite the Razor Parsers. This is possible, but at this point you already implemented the hardest part of Razor yourself...
The real question you should ask yourself (or answer here) is: Why you want to do it? It is not as trivial as one would think, I was at this point before.
As freedomn-m suggested you should use #Html.Raw("#") or ## if you need to output a "#".
matthid
- a RazorEngine contributor
Related
A user is allowed to format their html in a textbox. This then gets sent to the backend where it will be validated. Other users may then see this textbox.
I want to check for any tags in the backend. I know this can be done with a relatively simple regex. I would just do something like <\s*?script\s*?>
My issue though is if someone does something like this:
test
This would pass validation. I could also make the regex check for onClick, but I'm sure there are other ways around this.
My question: Is there a good way to do this? Am I just going to have to rely on regexes and my own research to figure out how else they could run a script?
EDIT
I suppose I could create a whitelist of what they can enter. It's primarily meant for formatting text, so <b>, <i>, <h> etc. This may or may not be an acceptable solution though, I need to look and see what the actual use case is. I'm hoping there's a different solution to this.
Really you should use white-list validation (i.e. allow only specific examples that you know are safe) rather than trying to detect and remove potentially hazardous input.
One really nice way to do this is to use Markdown rather than just allowing HTML input.
There are OWASP Guidelines for HTML injection.
A simple for removing all HTML tags from content
public string Strip(string text)
{
return Regex.Replace(text, #”<(.|\n)*?>”, string.Empty);
}
Basically a dup of this question using php, but I need it for C#.
I need to be able to replace any & that is not currently not any HTML entity (e.g. &) before outputting to screen. I was thinking a regex, but I'm not sure if .Net has something built in that will do this.
You can use HttpUtility.HtmlEncode.
Whithing the context of a page or UserControl, you can use Server.HtmlEncode.
Better AntiXss.HtmlEncode, prevents XSS.
You could always HTML Decode the string (which would turn any HTML symbols into their display equivalents), replace any &'s, and then Encode the string again (which turns the symbols back into what they were originally). You might need to watch for side effects though.
I am playing around with the System.ComponentModel.DataAnnotations namespace, with a view to getting some validation going on my ASP.NET MVC application.
I have already hit an issue with the RegularExpression annotation.
Because these annotations are attributes they require constant expressions.
OK, I can use a class filled with regex string constants.
The problem with that is I don't want to pollute my regex with escape characters required for the C# parser. My preference is to store the regex in a resources file.
The problem is I cant use those string resources in my data annotations, because they are not constants!
Is there any solution to this?
If not, this seems a significant limitation of using attributes for validation.
In C# there is only one escape code you need (double-quote)... if you use verbatim string literals:
#"like \this\ note \slash here does nothing only quote "" needs doubling
you can even use newline";
I always write regex with #"..." strings - avoids many headaches.
Apparently in .NET 4 there are overrides for the DataAnnotations attribubtes that take a Func< string> in their constructor described as "The function that enables access to validation resources."
You could create a custom validation attribute like this as a proxy which would load the regular expressions from your resource file.
I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it?
For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2.
Edit for clarification. The reason I need this is to allow me to simplify the parsing component of my application. The application is an Assmebly language teaching tool which allows students to write, compile, and execute assembly like programs.
Currently I have a tokenizer class which converts input strings into Tokens using regex's. This works very well. For example:
The tokenizer would produce the following tokens given the following input = "INP :x:":
Token.OPCODE, Token.WHITESPACE, Token.LABEL, Token.EOL
These tokens are then analysed to ensure they conform to a syntax for a given statement. Currently this is done using IF statements and is proving cumbersome. The upside of this approach is that I can provide detailed error messages. I.E
if(token[2] != Token.LABEL) { throw new SyntaxError("Expected label");}
I want to use a regular expression to define a syntax instead of the annoying IF statements. But in doing so I lose the ability to return detailed error reports. I therefore would at least like to inform the user of WHERE the error occurred.
I agree with Colin Younger, I don't think it is possible with the existing Regex class. However, I think it is doable if you are willing to sweat a little:
Get the Regex class source code
(e.g.
http://www.codeplex.com/NetMassDownloader
to download the .Net source).
Change the code to have a readonly
property with the failure index.
Make sure your code uses that Regex
rather than Microsoft's.
I guess such an index would only have meaning in some simple case, like in your example.
If you'll take a regex like "ab*c*z" (where by * I mean any character) and a string "abbbcbbcdd", what should be the index, you are talking about?
It will depend on the algorithm used for mathcing...
Could fail on "abbbc..." or on "abbbcbbc..."
I don't believe it's possible, but I am intrigued why you would want it.
In order to do that you would need either callbacks embedded in the regex (which AFAIK C# doesn't support) or preferably hooks into the regex engine. Even then, it's not clear what result you would want if backtracking was involved.
It is not possible to be able to tell where a regex fails. as a result you need to take a different approach. You need to compare strings. Use a regex to remove all the things that could vary and compare it with the string that you know it does not change.
I run into the same problem came up to your answer and had to work out my own solution. Here it is:
https://stackoverflow.com/a/11730035/637142
hope it helps
PHP has a great function called htmlspecialcharacters() where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's almost a one stop shop for sanitizing input. Very nice right?
Well is there an equivalent in any of the .NET libraries?
If not, can anyone link to any code samples or libraries that do this well?
Try this.
var encodedHtml = HttpContext.Current.Server.HtmlEncode(...);
System.Web.HttpUtility.HtmlEncode(string)
Don't know if there's an exact replacement, but there is a method HtmlUtility.HtmlEncode that replaces special characters with their HTML equivalents. A close cousin is HtmlUtility.UrlEncode for rendering URL's. You could also use validator controls like RegularExpressionValidator, RangeValidator, and System.Text.RegularExpression.Regex to make sure you're getting what you want.
Actually, you might want to try this method:
HttpUtility.HtmlAttributeEncode()
Why? Citing the HtmlAttributeEncode page at MSDN docs:
The HtmlAttributeEncode method converts only quotation marks ("), ampersands (&), and left angle brackets (<) to equivalent character entities. It is considerably faster than the HtmlEncode method.
In an addition to the given answers:
When using Razor view engine (which is the default view engine in ASP.NET), using the '#' character to display values will automatically encode the displayed value. This means that you don't have to use encoding.
On the other hand, when you don't want the text being encoded, you have to specify that explicitly (by using #Html.Raw). Which is, in my opinion, a good thing from a security point of view.