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);
Related
I'm using PushSharp to handle push notifications for iOS.
Everything went well until I realized the way I'm handling the push isn't too powerful:
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = device.DeviceIdentifier,
Payload = JObject.Parse("{\"aps\":{\"alert\" : {\"title\" : \"" + title
+ "\", \"body\" : \"" + body + "\"}, \"badge\":" + badgeCount + "}, " +
"\"entity_id\" : \"" + entityId + "\", \"category_id\" : \"" + categoryId + "\", \"sub_id\" : \"" + subId
+ "\"}")
});
Edit / Update One of the parameters I am trying is \t\ud83d\uddbc️\ (basically I wanted to pass in the unicode character of the picture frame emoji, so it can be rendered in the APNS alert). It is breaking currently.
I am sending that in C# like this: #"\t\ud83d\uddbc️\"
So as you can see, I'm rendering out the JSON Payload and this framework takes in a JObject. The problem, as I immediately assumed during my code review, is that if any of those parameters above (title, body, etc) end up being strings such as { or " or { etc that it will "break" the JSON because JObject can't parse that as valid JSON.
What do you think I should do in this case? Do I have to encode it and I suppose the only drawback would be I have backslashes or something in the encoding? Any recommendations to permit the user input (title and body can be free form text so anything is possible).
Thank you in advance for any advice!
EDIT
Thank you again Zero for your help.
var escapedString = JsonConvert.ToString(normalString);
saved the day. It's important to note that if you are using this, then escapedString should not be wrapped in ""'s since it will already be escaped (as he mentioned below).
As long as your variables are quoted (inside ") there's no need to escape braces ({ and })
As for breaking the quote (having ") inside variables, you could do something like this:
//Escapes quotes
param = param.Replace(#"""", #"\""");
You also need to escape the escape char itself \
//Escapes backslash
param = param.Replace(#"\", #"\\");
Also, here are all valid escapes.
If you're using Newtonsoft.Json they have a method to do this for you.
Example usage below or take a look here. Be aware this will add quotes to the string for you.
//Or use the return value inline with interpolation "$" or concatenation "+"
var escapedString = JsonConvert.ToString(normalString);
I have an ASP.Net WebAPI service that accepts OData queries. One of my controller methods accepts an ODataQueryOptions instance and applies it to an IQueryable instance. So far so good. Everything is working as planned.
Now, I have a specific need to obtain one of the key/value pairs from the OData query. For example, if I have two filters specified (someproperty eq 123 and otherproperty eq 456), how can I obtain one of the key/value pairs from the raw filter? I've looked at some of the ODataUriParser documentation, but it is really complicated and seems overkill. Isn't there an easier way to obtain simple key/value pairs, like I would from a normal QueryString?
EDIT: I've since put in some manual string parsing to accomplish what I needed, but that's obviously not ideal. Therefore, I'm putting up a bounty on this question. Hopefully someone has a simple solution to this!
There is an easy approach using regex where you convert your Odata query filter into key Value pair , regex found from this answer Here
string strRegex = #"(?<Filter>" +
"\n" + #" (?<Resource>.+?)\s+" +
"\n" + #" (?<Operator>eq|ne|gt|ge|lt|le|add|sub|mul|div|mod)\s+" +
"\n" + #" '?(?<Value>.+?)'?" +
"\n" + #")" +
"\n" + #"(?:" +
"\n" + #" \s*$" +
"\n" + #" |\s+(?:or|and|not)\s+" +
"\n" + #")" +
"\n";
your replacement string is something like,
string strReplace = #"${Resource}:${Value},"
Which gives you output like,
someproperty:123,otherproperty:456
Then convert that string into dictionary of your KeyValue parameter or however you want to consume it
public Dictionary<String, String> getKeyValue(String input)
{
return input.Split(',').ToDictionary(kv => kv.Split(':').First(), kv => kv.Split(':').Last());
}
I'm trying to save the contents of my listView.
But I'm having some issues with it. In my text file it will look like this:
ListViewItem: {1234};ListViewSubItem: {daily};ListViewSubItem: {Backup};ListViewSubItem: {Every 2 days at: 23:0};ListViewSubItem: {};ListViewSubItem: {}
But I don't like that it adds "ListViewItem:" and "ListViewSubItem:" etc with my data.. I just want those strings inside {}.
And here is my code:
FileStream file = new FileStream(dataFolder + "\\BukkitGUI\\schedule.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(listItem + ";" + listItem.SubItems[1] + ";" + listItem.SubItems[2] + ";" + listItem.SubItems[3] + ";" + listItem.SubItems[4] + ";" + listItem.SubItems[5]);
}
sw.Close();
file.Close();
Any help on this?
EDIT: Image of my listView:
Your code does this:
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(listItem + ";" + listItem.SubItems[1] + ";" + listItem.SubItems[2] + ";" + listItem.SubItems[3] + ";" + listItem.SubItems[4] + ";" + listItem.SubItems[5]);
}
This is doing the following:
foreach (ListViewItem listItem in listView1.Items)
{
string listItemString = listItem.ToString();
// etc.
}
What do you think the value of listItem.ToString() will be?
The default implementation of object.ToString() simply outputs the name of the type. The implementation for ListViewItem and ListViewSubItem apparently output the name of the type, plus the content of the item or subitem.
If you want something different output, then you need to do it yourself. Output listItem.Text and listItem.SubItems[n].Text instead.
Q: If your input data is in JSON format, perhaps your best bet is to get a JSON parser?
For example:
Parsing REST Services JSON Responses (C#): illustrates System.Runtime.Serialization.Json
Otherwise, if it's just a "funny format", look at the .Net TextFieldParser:
Parsing Text Files with the TextFieldParser Object
It's too long to post it as comment so I'll write an answer. I hope at least it will give you a good direction on one way to deal with it. In general you need some way to manipulate string. Many options comes to mind, but in your case I think that using regex or regular expressions is the best option since they are powerful, you have a clear criteria about what should go inside the .txt file and what not, and you work with relatively small amount of data so even though the regular expressions are considered slower than other options, in your case I think this won't be a problem.
Here is what I've tried - just created a static method (some sort of helper method) that will clean the string for you so that you get only the info you need. The method itself is :
public static string ParseListView(string ListViewText)
{
var regex = new System.Text.RegularExpressions.Regex("{.*?}");
var match = regex.Match(ListViewText);
return match.ToString().TrimStart('{').TrimEnd('}');
}
Pretty simple method. There's a lot of things that you can adjust if needed to work better for your case. For example I'm using regex.Match() which returns only the first match, but maybe you'll find regex.Matches() more suitable for you. There are also a lot of other options when you work with regular expressions in C# so be sure to check them out.
Then in you foreach loop you just:
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(ParseListView(listItem) + ";" + ParseListView(listItem.SubItems[1]) + ";" + ParseListView(listItem.SubItems[2]) + ";" + ParseListView(listItem.SubItems[3]) + ";" + ParseListView(listItem.SubItems[4]) + ";" + ParseListView(listItem.SubItems[5]));
}
Of course this looks pretty ugly so the logic inside the foreach loop most probably can be improved but I think this will get you going.
If i have an image tooltip that is being populated from a database table. I am generating this html below from my server side C# code
public string GetImage()
{
return "<img class='iconSpace' title ='" + dataIssue + "' src='/Content/Images/Icons" + size + "/information_red.png' />";
}
the issue is that if the variable dataIssue has an apostrophe in it, it only shows the characters in the string up to that point.
What is the best way to show the whole string in the tooltip given the code above?
' is not special symbol for HTML, and browser shows whole string without problems, but you can have problems with following symbols " < > & they should be escaped as:
"
<
>
&
if your browser treats HTML standard incorrectly and cut the rest of the string, you can try to escape single quote with ' - this will work for all browsers
so, according HTML standard attribute values should be surrounded by " symbol, not by ', so the problem here should be solved:
dataIssue = any_kind_of_html_escape_function_here(dataIssue);
return "<img class=\"iconSpace\" title=\"" + dataIssue + "\" src=\"/Content/Images/Icons" + size + "/information_red.png\" />";
For asp.net htmlencode function is defined here: http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx
Would this work for you?
string img = "<img class=\"iconSpac\" title=\"" + dataIssue + "\" " + "scr=\"/Content/Images/Icons\"" + size + "/information_red.png\" />";
You should use HttpUtility.HtmlEncode("...") for it.
http://msdn.microsoft.com/en-us/library/73z22y6h.aspx
wassup guys im new to C# coding and i did a search but couldn't find exactly what im looking for. So i have a couple of text-boxes which holds string elements and integers
what i want to do is when these boxes are filled in i want to send a summary of the email to client/customer but the format is whats getting me.
(first, one) are strings equaling different text-boxes
my code is:
emailCompseTask.Body = first + one + Enviroment.NewLine +
second + two + Enviroment.NewLine
and so on problem is which i send thru email it shows something like this:
computer service25.00
instead of:
computer service 25.00
is there a way to add spacing to make this more presentable? or even a better way perhaps thanks in advance guys
try this :
emailCompseTask.Body = first + one + " "+ second + two ;
body takes as HTML input, check here for more spacing option.
I'm a bit confused, but you just want to add some spacing in the output? Just throw some spaces in there like you would another variable.
first + " " + one + Environment.NewLine
+ second + " " + two + Environment.NewLine;
You can use a table
string tableRow = #"<tr>
<td>{0}</td>
<td>{1}</td>
</tr>";
string htmlTable = #"<table>
{0}
</table>";
string rows = "";
// Can do this in a loop
rows += string.Format(tableRow, first, one);
rows += string.Format(tableRow, first, one);
emailComseTask.Body = string.Format(htmlTable, rows);