Why doesn't razorengine render this as raw? - c#

I am creating data driven xaml using RazorEngine.
However, I cannot get this to work:
string template = "<k t=\" #Raw(Model.Name) \" ";
var model = new { Name = "CS
" };
string result = Razor.Parse(template, model);
this causes "result" to become
<k t="CS&#10; "
I do not want the "&" to be turned into
#amp;
If I remove any of the following:
the starting character "<"
the space between "k" and "t"
the \"
....then the razor engine parser Raw() function is behaving correctly by not converting "&" into "&"
I was also thinking that I could help Razor understand my intent better by using a code block #{} instead of just #.
However, I haven't figured how I can make a code block emit text to Razor output.

You don't need to do anything & is actually &.
if you try this code you will see that it outputs &
var str = HttpUtility.HtmlDecode("&")
See http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references and http://en.wikipedia.org/wiki/Character_encodings_in_HTML for more info.

Related

I need to replace : with ":" form the string "AAAA:123346hadhdhajkkd890" result like "AAAA":"123346hadhdhajkkd890" using Replace functionality in C#

I need to replace the string "AAAA:123346hadhdhajkkd890" with "AAAA":"123346hadhdhajkkd890" using the Replace function in C#.
Hi try to use the code below :
var str = "AAAA:123346hadhdhajkkd890";
str = str.Replace(":", "\":\"");
in order to put " in Replace function you have to use \" in the parameter.
var s1 = "AAAA:123346hadhdhajkkd890";
var s2 = str.Replace(":", "\":\"");
This is because \" will actually tell the compiler " and if simply " will mean the end of the string. This is known as the escape sequence.

How to get the bold tag <b> in a string to take effect when displayed on screen?

I have an MVC application wherein I have a string that gets created dynamically from the view model using C# code, there are certain words that need to be marked in bold. For instance, if the string created from C# code is 'This is a test', I wish to display the word 'test' as bold when it is passed from the view model to the cshtml view and is displayed on screen, I tried Regex.replace, which helped me get the text wrapped in bold tags, but after that what I saw on screen was plain text with tags 'This is a < b >test< /b >, while I expected it to be - 'This is a test'. I tried Regex.replace, but that didn't work. Can someone please suggest what should be done in this case ? Below is my code:
content = System.Text.RegularExpressions.Regex.Replace(content, wordToHighlight, "<b>" + wordToHighlight + "</b>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
In your case:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
String term = "test";
String input = "This is a test";
String result = Regex.Replace( input, String.Join("|", term.Split(' ')), #"<b>$&</b>");
Console.Out.WriteLine(result);
}
}
would give you: This is a <b>test</b>
In order to display this string in your View, use:
#Html.Raw(result)
which will display your string as: This is a test

C# appending string from variable inside double quotes

Hi I have the following line:
var table = #"<table id=""table_id"" class=""display"">
which is building a table and continues on the next line but I'm just trying to append a string at the end of table_id :
var table = #"<table id=""table_id" + instance + """ class=""display"">
so the final output (if instance = 1234) should be:
<table id="table_id1234" class="display">
But I think the quotes are throwing it off. Any suggestions on how t achieve the last line?
Thanks
A string.Format method placeholder is enough to concatenate instance without cutting through quote signs ({0} is the placeholder):
var table = string.Format(#"<table id=""table_id{0}"" class=""display"">", instance);
Or you can use escape sequence \" for escaping quotes without string literal:
var table = "<table id=\"table_id" + instance + "\" class=\"display\">"
Result:
<table id="table_id1234" class="display">
Demo: .NET Fiddle
Try to use escape character for double quote(\") using this code:
var id = "1234";
var table = "<table id=\"table_id" + id + "\" class=\"display\">";
Here is an online tool for converting string to escape/unescape:
https://www.freeformatter.com/java-dotnet-escape.html
So you can copy the result and place your variables.
I think the best idea and newest idea for this situation is $ sign before your text and with this sign you dont need to extra sign in your string
example
vat table = $"<table id='table_id{instance}' class='display'">
# is used to escape double quotes from one string but in your example, you are actually concatenating three different strings, soyou should escape the third string as well like this:
var table = #"<table id=""table_id" + instance + #" "" class=""display"" >";
Alternatively, you could also use the StringBuilder class which is more memory efficient and might make your strings easier to read.

Linq, how get properly string with convert

I have got problem with getting string from the file via linq.
My file is:
LANG_FORM="nnd documents acceptance"
%>
Response.Write "<SCRIPT LANGUAGE=javascript>alert('" & LN("KtśćóŻ") & "');</SCRIPT>"
it is part of asp file but now it is doesn't matter.
I have to get value in LN function.
I write linq synatx like:
var LN = from place in File.ReadAllLines(item.file)
where Regex.IsMatch(place, pattern)
select new { place };
In debug view i have non properly output:
{ place = Response.Write "<SCRIPT LANGUAGE=javascript>alert('" & LN("Kt���") & "');</SCRIPT>" }
My question is, how prepare linq syntax to get output properly (they are polish letters)?
I think encoding is wrong.
Try File.ReadAllLines(String, Encoding).
var LN = from place in File.ReadAllLines(item.file, Encoding.UTF8)
where Regex.IsMatch(place, pattern)
select new { place };
You can use desired encoding, not only Encoding.UTF8.

How do I replace all the spaces with %20 in C#?

I want to make a string into a URL using C#. There must be something in the .NET framework that should help, right?
Another way of doing this is using Uri.EscapeUriString(stringToEscape).
I believe you're looking for HttpServerUtility.UrlEncode.
System.Web.HttpUtility.UrlEncode(string url)
I found useful System.Web.HttpUtility.UrlPathEncode(string str);
It replaces spaces with %20 and not with +.
To properly escape spaces as well as the rest of the special characters, use System.Uri.EscapeDataString(string stringToEscape).
As commented on the approved story, the HttpServerUtility.UrlEncode method replaces spaces with + instead of %20.
Use one of these two methods instead: Uri.EscapeUriString() or Uri.EscapeDataString()
Sample code:
HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//Output: "https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"
Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"
//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"
I needed to do this too, found this question from years ago but question title and text don't quite match up, and using Uri.EscapeDataString or UrlEncode (don't use that one please!) doesn't usually make sense unless we are talking about passing URLs as parameters to other URLs.
(For example, passing a callback URL when doing open ID authentication, Azure AD, etc.)
Hoping this is more pragmatic answer to the question: I want to make a string into a URL using C#, there must be something in the .NET framework that should help, right?
Yes - two functions are helpful for making URL strings in C#
String.Format for formatting the URL
Uri.EscapeDataString for escaping any parameters in the URL
This code
String.Format("https://site/app/?q={0}&redirectUrl={1}",
Uri.EscapeDataString("search for cats"),
Uri.EscapeDataString("https://mysite/myapp/?state=from idp"))
produces this result
https://site/app/?q=search%20for%20cats&redirectUrl=https%3A%2F%2Fmysite%2Fmyapp
Which can be safely copied and pasted into a browser's address bar, or the src attribute of a HTML A tag, or used with curl, or encoded into a QR code, etc.
Use HttpServerUtility.UrlEncode
HttpUtility.UrlDecode works for me:
var str = "name=John%20Doe";
var str2 = HttpUtility.UrlDecode(str);
str2 = "name=John Doe"
HttpUtility.UrlEncode Method (String)
The below code will replace repeating space with a single %20 character.
Example:
Input is:
Code by Hitesh Jain
Output:
Code%20by%20Hitesh%20Jain
Code
static void Main(string[] args)
{
Console.WriteLine("Enter a string");
string str = Console.ReadLine();
string replacedStr = null;
// This loop will repalce all repeat black space in single space
for (int i = 0; i < str.Length - 1; i++)
{
if (!(Convert.ToString(str[i]) == " " &&
Convert.ToString(str[i + 1]) == " "))
{
replacedStr = replacedStr + str[i];
}
}
replacedStr = replacedStr + str[str.Length-1]; // Append last character
replacedStr = replacedStr.Replace(" ", "%20");
Console.WriteLine(replacedStr);
Console.ReadLine();
}
HttpServerUtility.HtmlEncode
From the documentation:
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);
But this actually encodes HTML, not URLs. Instead use UrlEncode(TestString).

Categories