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);
Related
hi guys I made an app to extract .lua file when I push the button
my problem is I need to pass this string like this
QUESTID = LuaGetQuestID("QNO_QUEST_AR")
QNO_QUEST_AR extracted from textBox1 so my code =
File.Write(" QUESTID = LuaGetQuestID("+textBox1.Text+")\r\n");
I need to add 2x " mark like this (""+textBox1.Text+"")
anyway to do that ? thanks
You can use a 'verbatim identifier' (#) and escape quotes with double quotes.
Note that you can also combine the 'string interpolation identifier' ($) so that you're not building up the string with pluses. See:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim
and
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
Then you could write your code something like:
var myString = #$"QUESTID = LuaGetQuestID(""{textBox1.Text}"")";
thanks, guys it works with this code
File.Write(" QUESTID = LuaGetQuestID(" + '"' + textBox1.Text + '"' + ")\r\n");
I have some Json files containing special character like this :
{
"someProperties" : "someValues",
"$ROOT_QUERY.searchResults({\"path\":\"/some/url\"}).features":
{
"propertyOtherA": "valueA",
"propertyOtherB": "null",
},
"$ROOT_QUERY.searchResults({\"path\":\"/some/url\"}).otherText":
{
"propertyOtherA": "valueA",
"propertyOtherB": "null",
}
}
How can I set the token path to get it ?
When I try the standard path, I get a Unexpected character exception
string path = "$ROOT_QUERY.searchResults({\\\"path\\\":\\\"" + request.RequestUri.PathAndQuery + "\\\"})";
var token = jObject.SelectToken("$." + path + ".features");
I also tried to replace string in Json, but the string.Contains method is not returning true, whereas it works fine in notepad.
I also tried simple Regex, but i've not succed to make it work.
My last idea is atomic Regex, but before entering to this hell, I'm trying to ask you if I can any chance to get it with a simplier way.
Thank you
You need to escape path using '[]' - note that .features should also be included:
var path = "['$ROOT_QUERY.searchResults({\"path\":\"" + request.RequestUri.PathAndQuery + "\"}).features']";
var token = jObject.SelectToken("$." + path);
Console.WriteLine(token);
You need to escape this entire path, because you have multiple "reserved" characters there: $, ., () (see this non-oficial documentation). See other escaping examples here.
demo.
I'm relatively new to C# and trying to deserialize a string from JSON for this value; ["format"]["tags"]["ENCODER"]
// Manually building the string works fine
string test = (dict["format"]["tags"]["ENCODER"]);
string found_value = "";
const char quote = '\u0022';
string encoder = "[" + quote + "format" + quote + "][" + quote + "tags" + quote + "][" + quote + "ENCODER" + quote + "]";
// Just as a test
encoder = encoder.Replace("\u005c\u0022", "\u0022");
// This Fails
found_value = (dict[encoder]);
It throws an exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll but was not handled in user code
Additional information: The given key was not present in the dictionary.
So I'm sure it's the way I'm passing the encoder string. Probably something really simple but I've spent hours trying various things and become blind to it now.
Thanks in advance
Basically, C# isn't a scripting language, but is a compiled language. This means that there is no equivalent of a javascript eval() function, and strings don't perform the same as the equivalent code string. So the second lookup, you're trying to do this:
dict["[\"format\"][\"tags\"][\"eval\"]")
And it is rightly complaining that your first dictionary there doesn't have a key of the name
"[\"format\"][\"tags\"][\"eval\"]"
Why are you trying to do this in the second way, when the first one works?
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 want to form a string as <repeat><daily dayFrequency="10" /></repeat>
Wherein the value in "" comes from a textboxe.g in above string 10. I formed the string in C# as
#"<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>" but i get the output as
<repeat><daily dayFrequency="+ txt_daily.Text+ " /></repeat>. How to form a string which includes the input from a textbox and also double quotes to be included in that string.
To insert the value of one string inside another you could consider string.Format:
string.Format("foo {0} bar", txt_daily.Text)
This is more readable than string concatenation.
However I would strongly advise against building the XML string yourself. With your code if the user enters text containing a < symbol it will result in invalid XML.
Create the XML using an XML library.
Related
How can I build XML in C#?
Escape it with \ Back slash. putting # in front wont do it for you
string str = "<repeat><daily dayFrequency=\"\"+ txt_daily.Text + \"\" /></repeat>";
Console.Write(str);
Output would be:
<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>
You could do it like this:
var str = String.Format(#"<repeat><daily dayFrequency="{0}" /></repeat>",
txt_daily.Text);
But it would be best to have an object that mapped to this format, and serialize it to xml
string test = #"<repeat><daily dayFrequency=" + "\"" + txt_daily.Text + "\"" + "/></repeat>";