In JavaScript:
encodeURIComponent("©√") == "%C2%A9%E2%88%9A"
Is there an equivalent for C# applications? For escaping HTML characters I used:
txtOut.Text = Regex.Replace(txtIn.Text, #"[\u0080-\uFFFF]",
m => #"&#" + ((int)m.Value[0]).ToString() + ";");
But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:
txtOut.Text = Regex.Replace(txtIn.Text, #"[\u0080-\uFFFF]",
m => #"%" + String.Format("{0:x}", ((int)m.Value[0])));
Returns "%a9%221a" for "©√" instead of "%C2%A9%E2%88%9A". It looks like I need to split the string up into bytes or something.
Edit: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel.
Uri.EscapeDataString or HttpUtility.UrlEncode is the correct way to escape a string meant to be part of a URL.
Take for example the string "Stack Overflow":
HttpUtility.UrlEncode("Stack Overflow") --> "Stack+Overflow"
Uri.EscapeUriString("Stack Overflow") --> "Stack%20Overflow"
Uri.EscapeDataString("Stack + Overflow") --> Also encodes "+" to "%2b" ---->Stack%20%2B%20%20Overflow
Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)
HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode
You can add a reference to the System.Web assembly if it's not available in your project
I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this
c# CODE:
string a = "!##$%^&*()_+ some text here али мамедов баку";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");
the result is:
!%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83
After you decode It with Javascript's decodeURLComponent();
you will get this:
!##$%^&*()_+ some text here али мамедов баку
Thank You for attention
System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.EscapeDataString() worked for me.
Try Server.UrlEncode(), or System.Web.HttpUtility.UrlEncode() for instances when you don't have access to the Server object. You can also use System.Uri.EscapeUriString() to avoid adding a reference to the System.Web assembly.
For a Windows Store App, you won't have HttpUtility. Instead, you have:
For an URI, before the '?':
System.Uri.EscapeUriString("example.com/Stack Overflow++?")
-> "example.com/Stack%20Overflow++?"
For an URI query name or value, after the '?':
System.Uri.EscapeDataString("Stack Overflow++")
-> "Stack%20Overflow%2B%2B"
For a x-www-form-urlencoded query name or value, in a POST content:
System.Net.WebUtility.UrlEncode("Stack Overflow++")
-> "Stack+Overflow%2B%2B"
You can use the Server object in the System.Web namespace
Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.
Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.
Related
I have a soap client and in order to make a call to a service of my company I need, among others, a parameter containing a CDATA string.
Simple version of the C# code I have is the following:
ServiceRef.GetArraySoapClient client = new ServiceRef.GetArraySoapClient();
String codes = #"
<Codes>
<Code><Batch>AAA</Batch><Item>YYY</Item></Code>
<Code><Batch>BBB</Batch><Item>XXX</Item></Code>
</Codes>";
client.GetArray("uname", "pword", "<![CDATA[" + codes + "]]>");
When I did the same using SoapUI, it works. But within the C# code, it gives me an error that goes like "error in the format of Code items".
I don't understand what is wrong with defining CData like this?
Okay, apparently I don't need to add something special before and after 'codes' while sending the request.
When running Veracode, it generated a bunch of errors pointing to the lines with InnerHtml.
For example, one of those lines is:
objUL.InnerHtml += "<tr><td></td><td class=\"libraryEdit\">" + HttpUtility.HtmlEncode(dtitems.Rows[currentitem]["content"].ToString()) + "</td>";
What do alternatives exist to fix it without using html server controls?
What exactly are you trying to do, and what exactly does Veracode say?
Most likely, it is complaining that you could end up with an arbitrary code injection vulnerability if the data passed into your InnerHtml is untrusted and could contain malicious JavaScript.
The tool may not complain if you manually construct the DOM elements using the JavaScript createElement function to build each DOM element manually.
I have faced this issue in my ASP.NET Webforms application. The fix to this is relatively simple.
Install HtmlSanitizationLibrary from NuGet Package Manager and refer this in your application.
At the code behind, please use the sanitizer class in the following way.
For example if the current code looks something like this,
YourHtmlElement.InnerHtml = "Your HTML content" ;
Then, replace this with the following:
string unsafeHtml = "Your HTML content";
YourHtmlElement.InnerHtml = Sanitizer.GetSafeHtml(unsafeHtml);
This fix will remove the Veracode vulnerability and make sure that the string gets rendered as HTML. Encoding the string at code behind will render it as 'un-encoded string' rather than RAW HTML as it is encoded before the render begins.
I am getting data from a web service end point and place it into a list in a for each loop. The service gets it's data from a Wordpress website.
var list = new ItemList
(
(string)data.id.ToString(),
(string)data.name,
(string)subcategory
);
I then print this on the XAML page. The code works fine in that it successfully gets the data from the service and prints it on the page of my windows 8 app.
However in (string)data.name,, which is the name of the items, if the name contains a "&" it shows up in the app as $#038;. Also if a item name contains a "'", apostrophe s, it shows up as ’.
EG. D & G, shows up as D $#038; G
The "&" and "'" show up as these weird symbols.
How do I get rid of these and fix it so that they render correctly in the app.
I'm going to take the risk of giving you a wrong hint, because I guess you're talking about a Windows 8 Store App (XAML), thus you don't have access to every class on .NET, but...
What about decoding HTML entities?
Check this HttpUtility method: HtmlUtility.HtmlDecode.
Check WebUtility.HtmlDecode, which is on System.dll, thus available for Windows 8 Store Apps.
You'll need to add a reference to System.Web on your Visual Studio project.
It looks like the service is returning XML escaped entities. & means a character with a code of (decimal) 38 (which is &). ’ is similar and means a code of 8217 (which is ’).
You can decode these using System.Web.HttpUtility.HtmlDecode(inputString), but that requires a reference to System.Web. If you don't want to or cannot reference that, you can try something like this:
var xml = new XmlDocument();
xml.LoadXml("<x>" + inputString + "</x>");
var output = xml.InnerText;
Given Testing ’stuff" & things, it will return Testing ’stuff" & things.
I'd go with HtmlDecode() if you can, but absolutely try and avoid rolling your own decoder unless you have no other choice.
You can use WebUtility.HtmlDecode Method (String)
Or you can use if you don't want to add additional libraries.
public string Decode(string text)
{
var replacements = new Dictionary<string, char> {
{ "’", ''' },
// ...etc
}
var sb = new StringBuilder( text );
foreach( var c in replacements.Keys ) {
sb.Replace( c.ToString(), replacements[c] );
}
return sb.ToString();
}
I am working with .net 4.0 c#.
I want to be able to get the url from the current http request, including any virtual directory. So for example (request and sought value):
http://www.website.com/shop/test.aspx -> http://www.website.com/shop/
http://www.website.com/test.aspx -> http://www.website.com/
http://website.com/test.aspx -> http://website.com/
How is it possible to achieve this?
This is what I use
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
Request.Url should contain everything you need. At that point it's a matter of checking the string, and what you prefer to grab from it. I've used AbsoluteUri before, and it works.
This example isn't fool proof, but you should be able to figure out what you need from this:
string Uri = Request.Url.AbsoluteUri;
string Output = Uri.Substring(0, Uri.LastIndexOf('/') + 1 );
This solution could work and is shorter:
string url = (new Uri(Request.Url, ".")).OriginalString;
This should work
Request.Url.OriginalString.Substring(0, Request.Url.OriginalString.LastIndexOf(Request.FilePath.Substring(Request.FilePath.LastIndexOf("/")))) + "/"
I'm upgrading an old project from MVC 1.0 to MVC 3.0 (yes, it's that old), and I've run into an issue where calling HtmlHelper.Button(..., onClickMethod, ...) HTML-encodes single quotes into '
I can see how this would not be an issue if onClickMethod was just the name of a method to be called in javascript, however this is how we are using it:
return helper.Button(name, buttonText, HtmlButtonType.Button,
string.Format("window.location='{0}'", url));
which obviously is now broken.
Is there any way to bypass this encoding? I can see hacking it by changing the return type of the method to string, and doing:
return string.Format(helper.Button(name, buttonText, HtmlButtonType.Button,
"window.location={0}").ToString(), "'" + url + "'");
but this is more or less a hack, and not elegant.
Having the ' should work. Even though the document stream contains the encoded value the browser unencodes it when it builds the DOM. You can use a DOM inspection tool to see yourself.
If I put the following on a page I see the alert box just fine upon click:
<input type="button" onclick="alert('Hello');" />
You can use the URI class to convert html codes into regular text
Uri.UnescapeDataString(string);