C# double " mark in textstring - c#

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");

Related

Encoding with APNS Push in C#

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);

Add separator to string?

I got here an sample string output in numbers:
123456789
But What my goal is to make it like this:
Format: 123-45-6789
I was able to look for some codes here but they all have a fix interval , which is not fit from what I am making. It is required to make the input format to be like this "123-45-6789" but when saving it is only required 9 characters long because there is a limit to the space where it should be stored so I used this code to met the 9 characters long storation.
Input.Text = Input.Text.Trim().Replace("-", string.Empty);
Bio.SetString(UserName, "9Character", Input.Text.Trim());
But when displaying it again , it is again required to be on this format , 123-45-6789. Which is my problem.
You can also try something like:
string val = "123456789";
val = val.Substring(0, 3) + "-" + val.Substring(3, 2) + "-" + val.Substring(5) ;
Here is a working DEMO
something like,
string number = "123456789";
var output = Regex.Replace(number,
#"^(\d{3})[ -]?(\d{2})[ -]?(\d{4})( x\d+)?",
#"$1-$2-$3$4", RegexOptions.IgnorePatternWhitespace);
Console.WriteLine($"formated {output}");
output : formated 123-45-6789
Demo

how to insert newline after word in sql table in c#

I am trying to insert New Line after word car but it is not working with folowing solution
Char(13) - not working
Environment.NewLine - when i use this it works but appends '(' this char in sql rows like 'Car ( Rate:2CR'
\n\r - not working
Code:
cmd.Parameters.AddWithValue("#ColumnCar", Car + "char(13)" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + "\n\r" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + Environment.NewLine + "Rate:2CR";
cmd.ExecuteNonQuery();
Need output in sql table ColumnCar row value as follows:
Car
Rate:2cr
Note : here after Car there will be a newline and then Rate:2Cr will be added
With the LoC Car + "char(13)" + "Rate:2CR"; you will get a literal string "char(13)" between your 2 values, not a new line. If you want only a new line you can append "\n" or you can append the character equivalent (char)10 of new line.
Now what character or string actually represents a new line might depend on your environment including the collation you are using. In simple ascii/ansi this will work. It might not be the same for another collation. As #mhasan pointed out it could also be different depending on the O/S.
Using characters
const char carriageReturn = (char) 13; // see https://en.wikipedia.org/wiki/Carriage_return
const char newLine = (char) 10;
var car = "some car";
var toInsert = car + newLine + "Rate:2CR";
cmd.Parameters.AddWithValue("#ColumnCar", toInsert);
This would also work and produce the same result:
var toInsert = car + "\n" + "Rate:2CR";
Use combination of newline and carriage return characters i.e. char(13) + char(10) for inserting new line in windows OS system.
For MAC its \r char(13) , for Linux its \n i.e. char(10) but for windows its combination of both.
Try this code hope its working...
Make a string variable and store all value in variable..
ex: string abc=textbox1.text+" "+"Rate:2cr";
#ColumnCar=abc.tostring();
now put your code
cmd.Parameters.AddWithValue("#ColumnCar",datatype);
cmd.executenonquery();
The following code works fine with unicode fields in a MS SQL-Server 2016 DB :
string carString = $"Volvo{Environment.NewLine}Rate: 2CR";
SqlParameter parameter = new SqlParameter("#ColumnCar", carString);
command.Parameters.Add(parameter);
The '(' when you use Environment.NewLine must be another error somewhere else. What is Car in your code? A class instance? What does its ToString() expand to?
Don't use string1 + " " + string2 concatenation.
Use string.Format(), $"" - inline syntax (like above) or StringBuilder to build your strings.

escaping characters

How can I escape the Quotes so that this statement
string sScript =#"<script language='javascript'>function ShowDropDown(){var combo = $find("""+this.ClientID+""");combo.showDropDown(true);}</script>";
reads like this
function ShowDropDown() {
var combo = $find("ctl00_ctl00_MainContent_MainContent_VendorTypeIdComboBox");
combo.showDropDown(true);
}
EDIT- UPDATE
I might of asked the question wrong because i keep getting different errors. If I put the javascript directly on the page normally the function works. When I inject the javascript this way it doesnt work
I am doing this in code behind
string sScript =#"<script language='javascript'> function ShowDropDown(){ var combo = $find("""+this.ClientID+#"""); combo.showDropDown(true); } </script>";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "autoopendropdown", sScript, false);
OnClientFocus = "ShowDropDown()";
it gets generated this way
<script language='javascript'> function ShowDropDown(){ var combo = $find("ctl00_ctl00_MainContent_MainContent_VendorTypeIdComboBox"); combo.showDropDown(true); } </script>
but the variable combo is null and thats what the problem is. I cant figure out why when it is registered with code-behind it doesnt work and when write it normally on the page it does.
Simple way: Add the same # at the beginning of the second string literal:
string sScript =#"<script language='javascript'>function ShowDropDown(){var combo = $find("""+this.ClientID+#""");combo.showDropDown(true);}</script>";
Better way: use string.Format
string sScript = string.Format(
#"<script language='javascript'>
function ShowDropDown(){
var combo = $find(""{0}"");combo.showDropDown(true);
}
</script>",
this.ClientID);
(Best way: separate concerns using unobtrusive javascript.)
string sScript = "<script language='javascript'>\n" +
"function ShowDropDown() {\n" +
" var combo = $find(""" + this.ClientID + """);\n" +
" combo.showDropDown(true);\n" +
"}\n" +
"</script>";
The escape for double quotes in C# (and most C family languages) is \"
Or you could just use single quotes since it's valid in JavaScript.
If I understand your question correctly, you want to concatenate this.ClientID with the rest of the script.
You can do this using the String.Format method like so:
string scriptFormat = #"<script language='javascript'>function ShowDropDown(){var combo = $find(""{0}"");combo.showDropDown(true);}</script>";
string sScript = String.Format(scriptFormat, this.ClientID);
Note that inside a verbatim string literal, "" produces a single " character.
You can escape them using the \ character.
For a complete list of escape combinations, see section 2.4.4.4 Character literals of the C# language specification.
NOTE: language is deprecated for script tags, use type
string sScript =#"
<script type='text/javascript'>
function ShowDropDown(){
var combo = $find(""" + this.ClientID + #""");
combo.showDropDown(true);
}
</script>";

Issue with forming a string with double quotes

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>";

Categories

Resources