razor string manipulation - asp.net

I have a razor string
#postername.Substring(0, #postername.IndexOf("#"))
If the username has email I get the username before # sign but if the username doesn't have email I want to have that whole word, how to do ?
if(#postername.Contains("#")){
#postername.Substring(0, #postername.IndexOf("#"))
}else{
#postername
}
but didn't work, pls help

If you must do this at View level, build the logic into a variable first:
#{
string posternameShort = postername;
if(postername.Contains("#")){
posternameShort = postername.Substring(0, postername.IndexOf("#"))
}
}
Then call the new variable:
#posternameShort

To further clarify this, Razor functions (what appears in the code block between { and }) fully support C# code. Additionally, Visual Basic code is supported as well.
This is powerful. Any string manipulation that would occur in C# or Visual Basic, is also available to use in Razor code.
More info on this available here and here.
Curt's response outlines a basic way to do this, but I thought it would be good to explain the "why" behind the "how," especially since I've been looking into how to manipulate strings with Razor myself.

Related

Email Address Validation. Is this Valid?

I am using the asp.net validation control to validate email addresses. There was an issue with an email address because it has the following characters. "-." For example the email address w.-a.wsdf.com will not validate due to the ".-" in it. I was looking around for email standards that forbid this but could not find any. Should I change the asp.net regex to a custom one to allow this or is this not a valid email address?
The regex i am using now is : \w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
You'll get loads of answers for this. This one has always served me well:
/\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
Originally found it in Michael Hartl's Rails book
^[a-zA-Z][\w\.-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$
Regular expressions are great but, as my comments showed in other answers, validating email addresses with them is not an easy task at all.
Based on my experience, I would suggest to either:
stick to the simplest email validation regex, ^.+#.+$ and send a confirmation email with an activation link;
or
avoid using regular expressions at all and use a library like my EmailVerify for .NET, which exposes a custom, fine tuned finite state machine for validating email addresses according to (all of) the related IETF standards plus disposable, DNS, SMTP, mailbox tests.
Obviously you can mix the two alternatives and perhaps avoid using regular expressions but send a confirmation link anyway.
Disclaimer: I am the tech lead of EmailVerify for .NET, a Microsoft .NET component for validating email addresses.
The regex below forbids w.-a.wsdf.com
using System.Text.RegularExpressions;
public static bool IsValidEmail(string email)
{
return Regex.IsMatch(email, #"\A[a-z0-9]+([-._][a-z0-9]+)*#([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
&& Regex.IsMatch(email, #"^(?=.{1,64}#.{4,64}$)(?=.{6,100}$).*");
}
See validate email address using regular expression in C#.
Take a text input in html and a button input like this
Now when the button is clicked then the JavaScript function SubmitFunction() will be called. Now write the bellow code in this function.
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
*its works *

Escaping all POST/GET parameters in ASP/ASP.net

I am a PHP developer trying to solve a problem in ASP/ASP.net (.aspx). We have a very old application that is having many security issues (on multiple pages, everywhere, big mess).
To solve this problem, I was thinking on adding some code to the top of every page to escape any POST/GET request before getting it processed by the application.
If it was PHP, I would prepend a PHP file (using .htaccess - auto_preppend) and basically do:
foreach($_POST as $myval => $anything)
{
$_POST[$myval] = htmlspecialchars($_POST[$myval]);
.. other escaping ..
}
Is there such a thing in ASP? Just want to escape any user input before passing to that mess of code that nobody wants to touch :(
Is this ASP or ASP.NET? Different beasts entirely. If you're using .NET you could use something like:
in VB
For Each item In Request.Form.Keys
newVal = Server.HtmlEncode(Request.Form(item))
Next
or C#
foreach (var item in Request.Form.Keys) {
var newVal = Server.HtmlEncode(Request.Form(item));
}
From an individual control perspective, this might help: Prevent special characters in a TextBox
If you are wanting to protect your entire form from script-injection attacks then take a look at RequestValidation: http://www.asp.net/learn/whitepapers/request-validation

A Minor, but annoying niggle - Why does ASP.Net set SQL Server Guids to lowercase?

I'm doing some client-side stuff with Javascript/JQuery with .Net controls which expose their GUID/UniqueIdentifier IDs on the front end to allow them to be manipulated. During debugging something is driving me crazy: The GUIDs in the db are stored in uppercase, however by the time they make it to the front end they're in lowercase.
This means I can't quickly copy and paste IDs into the browser's console to execute JS on the fly when devving/debugging. I have found a just-about-workable way of doing this but I was wondering if anyone knew why this behaviour is the case and whether there is any way of forcing GUIDs to stay uppercase.
According to MSDN docs the Guid.ToString() method will produce lowercase string.
As to why it does that - apparently RFC 4122 states it should be this way.
The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input.
Also check this question on SO - net-guid-uppercase-string-format.
So the best thing you can do is to call ToUpper() on your GUID strings, and add extension method as showed in the other answer.
If you're using an Eval template, then I'd see if you can do this via an Extension method.
something like
public static string ToUpperString(this Guid guid, string format = "")
{
string output = guid.ToString(format);
return output.ToUpper();
}
And then in your Eval block,
myGuid.ToUpperString("B")
Or however you need it to look.
I'm on my Mac at the moment so I can't test that, but it should work if you've got the right .Net version.

Are there any anti-XSS libraries for ASP.Net?

I was reading some questions trying to find a good solution to preventing XSS in user provided URLs(which get turned into a link). I've found one for PHP but I can't seem to find anything for .Net.
To be clear, all I want is a library which will make user-provided text safe(including unicode gotchas?) and make user-provided URLs safe(used in a or img tags)
I noticed that StackOverflow has very good XSS protection, but sadly that part of their Markdown implementation seems to be missing from MarkdownSharp. (and I use MarkdownSharp for a lot of my content)
Microsoft has the Anti-Cross Site Scripting Library; you could start by taking a look at it and determining if it fits your needs. They also have some guidance on how to avoid XSS attacks that you could follow if you determine the tool they offer is not really what you need.
There's a few things to consider here. Firstly, you've got ASP.NET Request Validation which will catch many of the common XSS patterns. Don't rely exclusively on this, but it's a nice little value add.
Next up you want to validate the input against a white-list and in this case, your white-list is all about conforming to the expected structure of a URL. Try using Uri.IsWellFormedUriString for compliance against RFC 2396 and RFC 273:
var sourceUri = UriTextBox.Text;
if (!Uri.IsWellFormedUriString(sourceUri, UriKind.Absolute))
{
// Not a valid URI - bail out here
}
AntiXSS has Encoder.UrlEncode which is great for encoding string to be appended to a URL, i.e. in a query string. Problem is that you want to take the original string and not escape characters such as the forward slashes otherwise http://troyhunt.com ends up as http%3a%2f%2ftroyhunt.com and you've got a problem.
As the context you're encoding for is an HTML attribute (it's the "href" attribute you're setting), you want to use Encoder.HtmlAttributeEncode:
MyHyperlink.NavigateUrl = Encoder.HtmlAttributeEncode(sourceUri);
What this means is that a string like http://troyhunt.com/<script> will get escaped to http://troyhunt.com/<script> - but of course Request Validation would catch that one first anyway.
Also take a look at the OWASP Top 10 Unvalidated Redirects and Forwards.
i think you can do it yourself by creating an array of the charecters and another array with the code,
if you found characters from the array replace it with the code, this will help you ! [but definitely not 100%]
character array
<
>
...
Code Array
& lt;
& gt;
...
I rely on HtmlSanitizer. It is a .NET library for cleaning HTML fragments and documents from constructs that can lead to XSS attacks.
It uses AngleSharp to parse, manipulate, and render HTML and CSS.
Because HtmlSanitizer is based on a robust HTML parser it can also shield you from deliberate or accidental
"tag poisoning" where invalid HTML in one fragment can corrupt the whole document leading to broken layout or style.
Usage:
var sanitizer = new HtmlSanitizer();
var html = #"<script>alert('xss')</script><div onload=""alert('xss')"""
+ #"style=""background-color: test"">Test<img src=""test.gif"""
+ #"style=""background-image: url(javascript:alert('xss')); margin: 10px""></div>";
var sanitized = sanitizer.Sanitize(html, "http://www.example.com");
Assert.That(sanitized, Is.EqualTo(#"<div style=""background-color: test"">"
+ #"Test<img style=""margin: 10px"" src=""http://www.example.com/test.gif""></div>"));
There's an online demo, plus there's also a .NET Fiddle you can play with.
(copy/paste from their readme)

Emitting unencoded strings in a Razor view

As ScottGu says in his blog post «by default content emitted using a # block is automatically HTML encoded to better protect against XSS attack scenarios».
My question is: how can you output a non-HTML-encoded string?
For the sake of simplicity, pls stick to this simple case:
#{
var html = "<a href='#'>Click me</a>"
// I want to emit the previous string as pure HTML code...
}
This is my favorite approach:
#Html.Raw("<p>my paragraph text</p>")
Source was Phil Haack's Razor syntax reference: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
You can create a new instance of MvcHtmlString which won't get HTML encoded.
#{
var html = MvcHtmlString.Create("<a href='#'>Click me</a>")
}
Hopefully there will be an easier way in the future of Razor.
If you're not using MVC, you can try this:
#{
var html = new HtmlString("<a href='#'>Click me</a>")
}
new HtmlString is definitely the answer.
We looked into some other razor syntax changes, but ultimately none of them ended up really being any shorter than new HtmlString.
We may, however, wrap that up into a helper. Possibly...
#Html.Literal("<p>something</p>")
or
#"<p>something</p>".AsHtml()
I'm using ASP.NET MVC and Razor under Mono.
I couldn't get HtmlHelper from System.Web.WebPages of System.Web.Mvc for some reasons.
But I managed to output unencoded string after declaring model's property as RazorEngine.Text.RawString. Now it outputs as expected.
Example
#{
var txt = new RawString("some text with \"quotes\"");
var txt2 = "some text with \"quotes\"";
}
<div>Here is unencoded text: #txt</div>
<div>Here is encoded text: #txt2</div>
Output:
<div>Here is unencoded text: some text with "quotes"</div>
<div>Here is encoded text: some text with "quotes"</div>
I ran into this problem as well when transitioning our project to the new Razor view engine. The approach I took was slightly different because we had to generate JSON data from C# and wanted to output it upon page load.
What I eventually did was to implement a RawView that was a parallel of View inside of the cshtml files. Essentially, to get a raw string,
#(new HtmlString(View.Foo))
// became
#RawView.Foo
This requires a few changes to the project layout, so I just wrote up a blog post about it here. In short, this required a duplicate implementation of MVC's DynamicViewDataDictionary and a new WebViewPage that contains the RawView. I also went ahead and implemented the index operator on the RawView to allow for
#RawView["Foo"]
In the off-chance that someone needs to loop over the data with a list of keys.
Reading anurse's comment, it probably would have been better off if I had named this as a Literal instead of RawView.

Resources