Replace variables after retrieving string from sql - c#

I would like for C# to detect the variables in my mailbody and replace them with the values each of them already has in my method.
I'm saving my mails in a TEXT datatype in mysql
This is what i save into my Text:
<html>
<h1>
<span style='text-decoration: underline;'>
<strong>Solicitud</strong>
</span>
</h1>
<br/>" + "<body>Blabla" + user.Nombre + " " + user.Apellido + " p<br/>La razón a que: <br />"+ razon+ ".</body>
</html>
I want it to replace user.Nombre user.Apellido and razon which are variables already available in the method
For example if my method has:
user.Nombre = "MATT";
user.Apellido ="CASA";
razon = "why not?";
Then detecting the variables i would have:
<html>
<h1>
<span style='text-decoration: underline;'>
<strong>Solicitud</strong>
</span>
</h1>
<br/>" + "<body>Blabla" + "MATT"+ " " + "CASA" + " p<br/>La razón a que: <br />"+ "Why not?"+ ".</body>
</html>
The problem is making C# detect that the string already has variables inside of it.

If I understand your question correctly, which is pretty hard given then English you have used.
You want to replace a parts of a string you retrieved from a database?
You can perform string replacements like the below example.
string email = emailAsString.Replace("+ user.Nombre +", variable1);
You can read more on this here, if you so wish.
String Replace - https://www.dotnetperls.com/replace

Well searched far and wide in the web, there is a method to compile manually but its highly dangerous so I decided to use String.Format , and the templates of my mails swap the "+ variable +" to {#}
Interpolating a string stored in a database
After retrieving use:
var formatedString= String.Format(string , variables);

Related

Quotes generating html entity

I'm trying to replace a bunch of consecutive
var: $("#var").val()
lines in my JS script with a simple loop in c# like this:
#foreach(var q in myList){
#(q.var + ": $('#" + q.var + "').val()," + Environment.NewLine);
}
But any symbol I try to pass (', \" or "") generates the html entity (&-#39; or &-quot;).
var: $("#var").val()
and JS errors.
With a view only solution, is it possible to fix this?
To have an official answer in this post (or for futur readers) I will put my comment as an answer, which seems to have resolved the issue.
What you should use is Html.Raw to print raw content.
#(q.var + Html.Raw(": $(\"#") + q.var + Html.Raw("\").val(),") + Environment.NewLine);

Issue with placing variable with string in ASP/Visual Studio

First off, forgive me for I know very little about MS Visual Studio & ASP, but my issue is that I can not seem to figure out the syntax for placing a variable within a string in the following ASP code....
description = viewCat[0]["description"].ToString();
metaHTML = #"
<title></title>
<meta name='description' content='" + description + "' />
";
Question I'm looking for is what is the correct way of placing the variable "description" within the string??
To create a string from a variable, you can use String.Format:
string description = "something";
string formattedStr = String.Format("Some string and {0}",description);
In your case:
description = viewCat[0]["description"].ToString();
metaHTML = String.Format("<title></title><meta name='description' content='{0}'/>", description);
Your assignment of metaHTML comprises three strings - two literals and the variable description. Only the first literal is a multiline string (you prefix it with #). The second string is not: the characters "' /> are an unterminated string, and aren't correlated with the characters on the next line.
What you want to do is this - note the extra #:
metaHTML = #"
<title></title>
<meta name='description' content='" + description + #"' />
";
What is the error that you get since this is a nice way of doing the stuff that you're talking about.
#"<title></title>
<meta name='description' content='" + description + "' />";
The only thing that you must worry about is any un escapted " inside the string. On the first occurance this string would break the string. Otherwise it would work.
Red squiggly lines in VS
In the Visual Studio the Red Squiggly lines are due to the error in the String length. In ASP.NET and C# to create multiline Strings you use # before the string to make it multiline. Like the first line of your String value.
Otherwise each string is single line and you cannot start a new line in it like you're doing right now. So either use this
<meta name='description' content='" + description + "' />";
... or else use this
<!-- note the # in the string -->
<meta name='description' content='" + description + #"' />
";
The better function is to use the first code I provided, because it ends the line where it must be ended. Try it, it would remove the red lines.

How can I use asp helper inside javascript script?

I am rendering page layout inside javascript but I would like to use there some CMS helpers. Rendering works well but helpers doesn't work (I obtained "NaN" instead of text I wanted). How can I add helpers to javascript variable?
var detailsTemplate =
'<table cellspacing="0" cellpadding="0">' +
'<tr>' +
'<th class="info">' +
<%# CMS.GlobalHelper.ResHelper.GetString("ReceiptsList.ProductName") %> +
'</th>' +
'</tr>' +
'<tbody>' +
'{0}' +
'</tbody>' +
'</table>'
Set single quotation marks around the ASP tags:
'<th class="info">' +
'<%# CMS.GlobalHelper.ResHelper.GetString("ReceiptsList.ProductName") %>' +
'</th>'
Look at the code generated and you will see, without the quotes you will have something like '<th>' + foo + '</th>' which will cause your current error. With the quotation marks you will have '<th>' + 'foo' + '</th>' which will run fine.
It works, I just add:
<span runat="server"> <js code..> </span>
and changed helper to (without single quotes):
<%= CMS.GlobalHelper.ResHelper.GetString("ReceiptsList.ProductName") %>

How to operate with html radioButtons. Validation , checking if checked, collecting values?

I need help. I'm trying to make a .Net, c# application for online creating surveys. I have a few types of questions, and than I dynamicly put labels, combos, textboxes ... on the form. Up to this point, I somehow managed to get. Than, on click on add button, I write down the responses in html format using stringBuffer and append function. Example.
public string RetOptionalQuestion(string seq_numm, string question, string answersOpt)
{
StringBuilder _output = new StringBuilder();
_output.Append(# " <tble><t"r"><th>" + seq_numm + "." + question + "</th></tr>");
_output.Append(#"<tr><td><table>");
string[] words = answersOpt.Split(';');
int m = 0;
foreach (string word in words)
{
if (word != "")
{
_output.Append(#" <tr><td> <label> " + word + "</label> </td> <td>
<input id='optional" + question + Convert.ToString(m) +
"'type='radio' name='rbOpt" + question + "' </td> ");
m++;
}
}
_output.Append("</table></td></tr></table>");
return _output.ToString();
}
Now, I hawe to validate this questions(at least one radio checked...). They have the same name,this mean the same group, so only on e can be selected.
Than I have also to save the values(responses) of this questions to the database.
Problem is that I don't know how to operate with this html objects. Also how to set tehm the ID-s. I'm trying with javaScript , but with no success. Do you have any advice, hint, example, solution ... where to start...
I would be very pleased
Thanks, Martin
Any input controls posted to the form can be found in the Request.Form dictionary, the key is the 'Name' attribute of the input tag. (I think)
http://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx

C# - Literal control vulnerable to XSS attack

I'm using a literal to display some javascript on a product page control. Basically what I'm doing is in my code behind I'm declaring a new stringbuilder, writing the script while inserting some dynamic variables to populate the script then setting the literal text to the stringbuilder. This leaves me open to xss attacks. What can I do to prevent this?
EDIT. Here is an example of the stringbuilder. when the page gets loaded the xss vulnerability occurs right after the javascript is generated.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
//loop through items in the collection
for (int i = 0; i < _prod.ActiveProductItemCollection.Count; i++)
{
sb.Append("<script type='text/javascript'>");
//add +1 to each item
sb.AppendFormat("mboxCreate(\"product_productpage_rec{0}\",", i+1);
sb.Append("\"entity.id=" + _prodID + "\",");
sb.Append("\"entity.categoryId=" + _categoryID + "\",");
sb.Append("\"entity.name=" + _prod.ActiveProductItemCollection[i].Title + "\",");
sb.Append("\"entity.pageURL=" + Request.Url.ToString() + "\",");
//The following value has been taken from the productImageControl code behind.
//Might have to refactor in future as a property of the image control.
string filename = AppSettingsManager.Current.ProductImagePathLarge + _prod.ActiveProductItemCollection[i].Sku
+ AppSettingsManager.Current.ProductImageExtension;
sb.Append("\"entity.thumbnailURL=" + filename + "\",");
sb.Append("\"entity.inventory=" + _prod.ActiveProductItemCollection.Count + "\",");
sb.Append("\"entity.value=" + _prod.ActiveProductItemCollection[i].ActualPrice + "\",");
sb.Append("\"entity.ProductItemID=" + _prod.ActiveProductItemCollection[i].Sku + "\",");
sb.Append("\"entity.addToCartImg=~/Images/Buttons/btn_AddToCartFlat.gif\");<");
//The last line has to be /script. < inserted on prev line. do not change it or bad things will happen.
sb.Append("/script>");
}
this.LiteralMBoxScript.Text = sb.ToString();
You need to properly encode any user-generated data that you're putting into the Javascript.
In ASP.Net 4.0, you can call HttpUtility.JavaScriptStringEncode.
In earlier versions, you can use the Web Protection Library.
To prevent XSS you could HTML encode the value.
Alternately, you could write your javascript to read the user supplied data off of the page. This will result in less javascript code, and a faster page load.
If you are using JQuery for example, you can use the $.Parent() and $.Children() selectors to traverse the DOM to the appropriate form controls to reference information about that particular record in the loop.
Here is a relatively simple sample
function doSomething(context) {
var IDInput = $(context).parent('td').parent('tr').children('td.id').children('.hidden');
//Do something with the value
IDInput.val();
}
This would work with the following html example:
<table>
<tr>
<td><input type="button" onclick="doSomething(this)" value="Do Something"/></td>
<td class="id">Hidden ID Value <input type="hidden" value="1"/></td>
</tr>
<tr>
<td><input type="button" onclick="doSomething(this)" value="Do Something"/></td>
<td class="id">Hidden ID Value <input class="hidden" type="hidden" value="2"/></td>
</tr>
</table>
The advantage of doing it this way is that you no longer have to write javascript functions that take the ID as a parameter, meaning you don't need to dynamically generate the functions on the button, and can load them in the header in a separate JS file.
Well, if it is just your own script being written to the literal, you are no more open to attacks than if you simply included a js file on your site. If on the otherhand your script is interspersed with user supplied data of any kind, then you need to sanitize that data before you write it to the page.
If you are using .NET 4.0, you could output the value using the <%: theText %> syntax.

Categories

Resources