C# creating an HTML line with escaping - c#

I'm creating a loop in which each line is a pretty long HTML line on the page. I've tried various combinations of # and """ but I just can't seem to get the hang of it
This is what I've got now, but the single quotes are giving me problems on the page, so I want to change all the single quotes to double quotes, just like a normal HTML line would use them for properties in the elements:
sOutput += "<div class='item link-item " + starOrBullet + "'><a href='" + appSet + linkID + "&TabID=" + tabID + "' target=’_blank’>" + linkText + "</a></div>";
variables are:
starOrBullet
appSet
LinkID
tabID (NOT $TabID=)
linkText
BTW, appSet="http://linktracker.swmed.org:8020/LinkTracker/Default.aspx?LinkID="
Can someone help me here?

You have to escape the double quotes (") with \"
For your case:
sOutput += "<div class=\"item link-item " + starOrBullet + "\"><a href=\"" + appSet + linkID + "&TabID=" + tabID + "\" target=’_blank’>" + linkText + "</a></div>";
If you concat many strings, you should use StringBuilder for performance reasons.

You can use a verbatim string and escape a double quote with a double quote. So it will be a double double quote.
tring mystring = #"This is \t a ""verbatim"" string";
You can also make your string shorter by doing the following:
Method 1
string mystring = #"First Line
Second Line
Third Line";
Method 2
string mystring = "First Line \n" +
"Second Line \n" +
"Third Line \n";
Method 3
var mystring = String.Join(
Environment.NewLine,
"First Line",
"Second Line",
"Third Line");

You must make habit to use C# class to generate Html instead concatenation. Please find below code to generate Html using C#.
Check this link for more information
https://dejanstojanovic.net/aspnet/2014/june/generating-html-string-in-c/
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.htmltextwriter
Find below code for your question
protected void Page_Load(object sender, EventArgs e)
{
string starOrBullet = "star-link";
string appSet = "http://linktracker.swmed.org:8020/LinkTracker/Default.aspx?LinkID=";
string LinkID = "2";
string tabID = "1";
string linkText = "linkText_Here";
string sOutput = string.Empty;
StringBuilder sbControlHtml = new StringBuilder();
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
{
//Generate container div control
HtmlGenericControl divControl = new HtmlGenericControl("div");
divControl.Attributes.Add("class", string.Format("item link-item {0}",starOrBullet));
//Generate link control
HtmlGenericControl linkControl = new HtmlGenericControl("a");
linkControl.Attributes.Add("href", string.Format("{0}{1}&TabID={2}",appSet,LinkID,tabID));
linkControl.Attributes.Add("target", "_blank");
linkControl.InnerText = linkText;
//Add linkControl to container div
divControl.Controls.Add(linkControl);
//Generate HTML string and dispose object
divControl.RenderControl(htmlWriter);
sbControlHtml.Append(stringWriter.ToString());
divControl.Dispose();
}
}
sOutput = sbControlHtml.ToString();
}

Related

Populating a Textbox with a Text File but it always adds a blank first line?

I have a file containing text and I can get it to populate a textbox on page load but it always adds a blank first line. Any ideas? I've tried skipping the first line in the array in case it was blank (both 0 and 1) but 0 does nothing and 1 skips the first line in the text file.
I've also tried to set the textbox to null and "" first in case it was appending to the textbox in some way.
//Populating the contents box
string[] str = null;
if (File.Exists(docPath + prefix + libIDPath + "\\" + oldFileName))
{
str = File.ReadAllLines(docPath + prefix + libIDPath + "\\" + oldFileName);
//str = str.Skip(0).ToArray();
//FDContentsBox.Text = null;
}
foreach (string s in str)
{
FDContentsBox.Text = FDContentsBox.Text + "\n" + s;
}
In your foreach you are appending the "\n" before appending the string itself. Try
FDContentsBox.Text = FDContentsBox.Text + s + "\n";
instead.
Please try this, there is no need to read all lines nor a foreach loop
var filePath = docPath + prefix + libIDPath + "\\" + oldFileName;
if (File.Exists(filePath))
{
FDContentsBox.Text = File.ReadAllText(filePath);
}

Environment.NewLine Does Not Put Each entry On New Row

I have the following code which is to display an address but it does not seem to put each address row on a new line and cant figure out why
var selectedOrigoScheme = origoCedingSchemes.Where(x => x.complyingFundId.ToString() == SelectedSchemeId).ToList();
string origoName = !String.IsNullOrEmpty(selectedOrigoScheme[0].origoName) ? selectedOrigoScheme[0].origoName + Environment.NewLine : "";
string propertyName = !String.IsNullOrEmpty(selectedOrigoScheme[0].propertyName) ? selectedOrigoScheme[0].propertyName + Environment.NewLine : "";
string streetNumber = !String.IsNullOrEmpty(selectedOrigoScheme[0].streetNumber) ? selectedOrigoScheme[0].streetNumber + Environment.NewLine : "";
string street = !String.IsNullOrEmpty(selectedOrigoScheme[0].street) ? selectedOrigoScheme[0].street + Environment.NewLine : "";
string street2 = !String.IsNullOrEmpty(selectedOrigoScheme[0].street2) ? selectedOrigoScheme[0].street2 + Environment.NewLine : "";
string suburb = !String.IsNullOrEmpty(selectedOrigoScheme[0].suburb) ? selectedOrigoScheme[0].suburb + Environment.NewLine : "";
string district = !String.IsNullOrEmpty(selectedOrigoScheme[0].district) ? selectedOrigoScheme[0].district + Environment.NewLine : "";
string postcode = !String.IsNullOrEmpty(selectedOrigoScheme[0].postcode) ? selectedOrigoScheme[0].postcode + Environment.NewLine : "";
string Origoaddress = origoName + propertyName + streetNumber + street + street2 + suburb + district + postcode;
viewData["Origoaddress"] = Origoaddress;
When I debug I get the following result:
Aviva\r\nNorwich Business Capture Centre\r\nPO Box 520\r\nNorwich\r\nNR1 3WG \r\n
If I look at the result in text visualizer it displays correctly:
Aviva
Norwich Business Capture Centre
PO Box 520
Norwich
NR1 3WG
But if I look at it using HTML visualizer it displays as:
Aviva Norwich Business Capture Centre PO Box 520 Norwich NR1 3WG
Which is how its showing in my address field on the website.
What am I doing wrong as I cant see the issue.
HTML
<%=Html.TextBox("Origoaddress", ViewData["Origoaddress"].ToString())%>
Html ignores white spaces so is ignoring the line breaks you have added. If you were working in pure html you'd need to use < br>. Html.TextBox only supports single line strings so doesn't add line breaks that Html will understand.
In order to use multiple lines you will probably need to use TextArea. See creating multiline textbox using Html.Helper function
for further details.

C# passing quotes in string

I am trying to pass quotes in string. I am having a hard time formulating the code.
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = "Set-UserPhoto ";
format += "" + user + "";
format += " -PictureData ([System.IO.File]::ReadAllBytes(";
format += "" + path + #"";
format += ")";
The user and path are variables that needs to be inside single quotes for the AD Command. command. What I have isn't working.
User \" for " symbol or \' for '
format += "\"" + user + "\"";
First of all , use string.format for such tasks. Second you have to escape quotes ( but you dont need to escape single quotes).
Double quotes can be escaped by double quote or by backslash based on type of string literal you are using:
var s = #"something "" somethin else "; // double double quote here
var s2 = "something \" somethin else ";
Now, using string.format, your code will turn into:
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = string.format("Set-UserPhoto {0} -PictureData ([System.IO.File]::ReadAllBytes(\"{1}\")", user, path);
or
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = string.format(#"Set-UserPhoto {0} -PictureData ([System.IO.File]::ReadAllBytes(""{1}"")", user, path);
string format = "Set-UserPhoto "; format += "'" + user + "'"; format += " -PictureData ([System.IO.File]::ReadAllBytes("; format += "'" + path + #"'"; format += ")";
I would suggest using string interpolation within a here-string as follows, this will prevent you from having to use string concatenation and escaping.
$format = #"
Set-UserPhoto " + user + " -PictureData ([System.IO.File]::ReadAllBytes(" + path + ")"
"#

How to escape apostrophe when displaying inside a ASP.NET label

I have the following function which truncates a SQL Server varchar column and adds it to a string:
public void Pp()
{
strSql = #""; //query
using (SqlConnection conn = new SqlConnection(gstr))
{
try
{
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
myDataSet = new DataSet();
da.Fill(myDataSet);
string specific = "";
string generic = "";
string strTemp = "";
foreach (DataRow r in myDataSet.Tables[0].Rows)
{
if (r["MessageText"].ToString().Length <= 65)
{
strTemp = r["MessageText"].ToString();
}
else
{
strTemp = TruncateLongString(r["MessageText"].ToString(), 65);
}
specific += "</b><span class='hoverText' title='" + r["MessageText"] + "'>" + strTemp + "...</span>";
strTemp = "";
}
lblMessage.Text = "<b>SPECIFIC MESSAGES:</b> <br />" + specific;
}
catch (Exception ce)
{
}
}
}
public string TruncateLongString(string str, int maxLength)
{
return str.Substring(0, maxLength);
}
If the r["MessageText"] contains an appostrophe, it cuts off anything after it. (full text: no way no way HERE we go again but this is not working. Is it? or Is it not? I can't be too sure though. Can someone please check.)
Here is an example of a live preview (the title is shown but gets cut off because of the apostrophe):
Here is the source (the apostrophe is shown in the purple box. Also the color coding gets out of whack due to the apostrophe, which means the code is not correct):
How can I ensure it doesn't escape any escape characters, e.g. ', /, \.
You need to encode the HTML first.
Call this.Server.HtmlEncode( str ). This will also protect against other special characters like & and <.
That said, you're using single-quotes for attribute delimiters but HtmlEncode only encodes double-quotes, so you need to change your code to this:
specific = String.Format( CultureInfo.InvariantCulture, #"</b><span class=""hoverText"" title=""" + this.Server.HtmlEncode( r["MessageText"] ) + """>" + strTemp + #"...</span>";
.Replace(" ' ", "\\' "); You will probably want to do the same with double quote as well.

accessing data from database and displaying it in textbox

I am using this code for accessing data from database and displaying it in textboxes,but i am getting whole string columns in 1st textbox ,how do i split and display in respective textboxes,i am getting this exception Index was outside the bounds of the array. at this line of code txtOption2.Text = coldata[2];
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('$');
txtQuestion.Text = coldata[0];
txtOption1.Text = coldata[1];
txtOption2.Text = coldata[2];
txtOption3.Text = coldata[3];
txtOption4.Text = coldata[4];
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
thank you in advance for any help
You appear to split the string by $ but you build the string up using ~ as the separator. You need to split the string by ~ to get the appropriate number of columns i.e.
string[] coldata = columns.Split("~")
You are seeing that error because you only have 2 items in coldata. Try debugging and view the length of the coldata array to see how many items it contains.
Change your code to use this split instead:
string[] coldata=columns.Split('~');
Looking at your code sample you just need to change:
string[] coldata=columns.Split('$');
To
string[] coldata=columns.Split('~');
As your columns are delimited by the ~ character.

Categories