I have the following code in C# that I'm able to attach to IE, and it runs through fine until I hit the JSON, which I receive a javascript error complaining about the syntax. How exactly should I escape javscript code within C# ?
string jsonStr = #"[
{ \'name\': \'Obj1\', \'description\': \'Test description...\', \'url\':\'http://www.test.com\' },
{ \'name\': \'Obj2\', \'description\': \'Testing...\', \'url\':\'http://www.test.com\' },
{ \'name\': \'Obj3\', \'description\': \'Welp...\', \'url\':\'http://www.test.com\' }
]";
IHTMLScriptElement scriptObject = (IHTMLScriptElement)document.createElement("script");
scriptObject.type = #"text/javascript";
scriptObject.text = #"function test() {
var Edit = 'document.getElementById(\'tTest\').innerHTML = \'<h2 class=\'label3\'><span>Foo</span></h2><ol class=\'container-list\'>';
var json = '" + jsonStr + #"';
$.each(json, function (index, x) {
Edit += '<li class=\'test1\'><h3><a href=\'#\'><b>' + x.name + '</b> 1</a></h3><div class=\'url\'><cite>' + x.url + '</cite></div><div class=\'creative\'>' + x.description + '</div></li>';
});
Edit += '</ol>\';
eval('Edit');
}";
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);
IHTMLDocument2 doc = (IHTMLDocument2)this._webBrowser2.Document;
IHTMLWindow2 parentWindow = doc.parentWindow;
if (parentWindow != null)
parentWindow.execScript("test();", "javascript");
The c# code is fine, I'm just having trouble wrapping my head about injecting the javascript code with all the quotations, single quotes, etc to eliminate the javascript error. Any help is GREATLY appreciated!
When using verbatim string literals prefixed with #, it means that the enclosed string is treated as literal. So basically no backslash '\' escaping. To escape double quote ("), just double it ("").
string jsonStr = #"[
{""name"": ""Obj1"", ""description"": ""Test description..."", ""url"":""http://www.test.com"" },
{ ""name"": ""Obj2"", ""description"": ""Testing..."", ""url"":""http://www.test.com"" },
{ ""name"": ""Obj3"", ""description"": ""Welp..."", ""url"":""http://www.test.com"" }
]";
Related
This question already has answers here:
Deserialize JSON with C#
(10 answers)
How can I deserialize JSON with C#?
(19 answers)
Closed 8 months ago.
I am looking for a way to convert the following manually typed JSON list to a List I can load, but still output the same format in C#, so in can be POSTed to a REST API.
var accs = #"{
" + "\n" +
#" ""Cities"": [
" + "\n" +
#" ""Atlanta"",
" + "\n" +
#" ""Chicago"",
" + "\n" +
#" ""San Diego""
" + "\n" +
#" ]
" + "\n" +
#"}
" + "\n" +
#"";
Assuming this is your model:
public class State
{
public List<string> Cities { get; set; }
public State(List<string> cities)
{
Cities = cities;
}
}
This is how you serialize and deserialize:
using System.Text.Json;
var listOfCities = new List<string>() { "Atlanta", "Chicago", "San Diego"};
var state = new State(listOfCities);
//Serialize
var jsonArray = JsonSerializer.Serialize(state);
// Deserialize
var obj = JsonSerializer.Deserialize<State>(jsonArray);
When you use #", you can avoid the + concatenation like:
var accs = #"
{
'Cities': [
'Atlanta',
'Chicago',
'San Diego'
]
}
";
You'll need to use ' (single quotes) instead of " in your JSON text, otherwise you have to escape \" them.
you don't need any custom classes, you can just parse your json string
using Newtonsoft.Json;
var jsonParsed=JObject.Parse(accs);
if you need list of cities as c# instance
List<string> cities =jsonParsed["Cities"].ToObject<List<string>>();
if you need just a well formatted json string
accs = jsonParsed.ToString();
result
{
"Cities": [
"Atlanta",
"Chicago",
"San Diego"
]
}
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();
}
I am trying to construct a raw json string as below to send it out in http request
var requestContent = #"{
""name"": ""somename"",
""address"": ""someaddress""
}";
Instead of having name and address value hardcoded I was hoping to supply them from below variables
string name = "someName";
string address = "someAddress";
But the below does not work. Any idea ?
var requestContent = #"{
""name"": \" + name \",
""address"": \" + address \"
}";
The correct syntax is:
var requestContent = #"{
""name"": """ + name + #""",
""address"": """ + address + #"""
}";
Or, you could use string.Format:
var requestContent = string.Format(#"{
""name"": ""{0}"",
""address"": ""{1}""
}", name, address);
Or you could use an actual JSON serializer.
You could use a verbatim string together with interpolation as well:
var requestContent = $#"{{
""name"": ""{name}"",
""address"": ""{address}""
}}";
EDIT: For this to work you have to make sure that curly braces you want in the output are doubled up (just like the quotes). Also, first $, then #.
Instead use Newtonsoft.JSON JObject() like
dynamic myType = new JObject();
myType.name = "Elbow Grease";
myType.address = "someaddress";
Console.WriteLine(myType.ToString());
Will generate JSON string as
{
"name": "Elbow Grease",
"address": "someaddress"
}
I'm using base64 encrypting of html tags due to solve a postback issue with my code. My html tag contain symbols like + , - , / or * . While decrypting the encrypted string im getting the following error :
Invalid length for a Base-64 char array.
Can anybody suggest a workaround here please?
JavaScript Calling from aspx page.
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function encode64(input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
}
else if (isNaN(chr3)) {
enc4 = 64;
}
output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
return output;
}
C# Code to decode the string # pageload:
public string DecodeBase64String(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
Error can be generated by giving a simple string that contain any of the symbols i'd mentioned or even a space character.
Html String :
"<tbody id=\"selectedColumnsTbody\">\n <tr style=\"cursor: move;\" id=\"ExprCountryMasterID10\"><td></td><td><input id=\"chk\" checked=\"checked\" class=\"textChangeClass\" type=\"checkbox\"></td><td>CountryMaster.ID + 10</td><td><input id=\"aliastextCountryMasterID10\" class=\"aliasTextChangeClass\" value=\"\" type=\"text\"></td>><td><input id=\"hiddenIDSortCountryMasterID10\" value=\"\" type=\"hidden\"></td></tr></tbody>\n
Calling decrypt method from cs page:
protected void Page_Load(object sender, EventArgs e)
{
//HtmlTextWriter htmlTable = new HtmlTextWriter();
//htmlTable.InnerHtml = htmlContent;
//Master.FindControl("ContentPlaceHolder1").Controls.Add(htmlTable);
if (Session["HtmlTable"] != null)
{
htmlContent = Session["HtmlTable"].ToString();
//htmlContent = htmlContent.Replace(" ", "+");
htmlContent = DecodeBase64String(htmlContent);
htmlTable = new HtmlGenericControl();
ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
if (contentPlaceHolder != null)
{
htmlContent = "<table cellspacing=\"0\" cellpadding=\"0\" id=\"selectedColumns\" width=\"100%\">" + htmlContent + "</table>";
htmlTable.InnerHtml = htmlContent;
test.InnerHtml = htmlContent;
}
}
}
Javascript where im calling htmlEncode
function StoreSessionForHtml(htmlContent) {
// var encodedObject = htmlEncode(htmlContent);
// var decodedObject = htmlDecode(encodedObject);
//htmlContent = htmlContent.replace(/ /g, "+");
var encodedObject = encode64(htmlContent);
var requesthtmlContentParameter = '{' +
'htmlContentToServer:"' + encodedObject + '"}';
$.ajax({
type: "POST",
url: "Webtop.aspx/HTMLTableContent",
data: requesthtmlContentParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//alert("Success", msg.d);
}, //Event that'll be fired on Success
error: function() {
// alert("Try Again");
} //Event that'll be fired on Error
});
$("#<%= HiddenHtmlContainer.ClientID %>").val(encodedObject);
}
Why don't use the HttpUtility.HtmlEncode Method
to prevent attack
There shouldn't be any problems with encoding any character since you are not encoding characters, you are encoding bytes.
The error you are getting I would assume is due to the legnth of your base64 encoded string not being correct. Base 64 encoding effectively changes groups of three bytes into groups of four characters. This means that decoders will want a string to decode that is a multiple of four characters. This is achieved by using the special character "=" to pad it out. This allows the decoder to know that those bytes don't exist (as opposed to just being blank or indeed missing).
The chances are that you had a problem purely because of the number of characters in the string you were decoding.
http://base64encode.org/ may be helpful for validating the strings you are generating to check whether your problem is with the encoding or decoding.
I have problem with deserialization of json string, because string is bad format.
For example json object consist string property statusMessage with value "Hello "dog" ".
The correct format should be "Hello \" dog \" " .
I would like remove double quotes from this property.
Something Like this. "Hello "dog" ". -> "Hello dog ".
Here is it original json string which I work.
"{\"jancl\":{\"idUser\":18438201,\"nick\":\"JANCl\",\"photo\":\"1\",\"sex\":1,\"photoAlbums\":1,\"videoAlbums\":0,\"sefNick\":\"jancl\",\"profilPercent\":75,\"emphasis\":false,\"age\":\"-\",\"isBlocked\":false,\"PHOTO\":{\"normal\":\"http://u.aimg.sk/fotky/1843/82/n_18438201.jpg?v=1\",\"medium\":\"http://u.aimg.sk/fotky/1843/82/m_18438201.jpg?v=1\",\"24x24\":\"http://u.aimg.sk/fotky/1843/82/s_18438201.jpg?v=1\"},\"PLUS\":{\"active\":false,\"activeTo\":\"0000-00-00\"},\"LOCATION\":{\"idRegion\":\"6\",\"regionName\":\"Trenčiansky kraj\",\"idCity\":\"138\",\"cityName\":\"Trenčianske Teplice\"},\"STATUS\":{\"isLoged\":true,\"isChating\":false,\"idChat\":0,\"roomName\":\"\",\"lastLogin\":1294925369},\"PROJECT_STATUS\":{\"photoAlbums\":1,\"photoAlbumsFavs\":0,\"videoAlbums\":0,\"videoAlbumsFavs\":0,\"videoAlbumsExts\":0,\"blogPosts\":0,\"emailNew\":0,\"postaNew\":0,\"clubInvitations\":0,\"dashboardItems\":1},\"STATUS_MESSAGE\":{\"statusMessage\":\"\"Status\"\",\"addTime\":\"1294872330\"},\"isFriend\":false,\"isIamFriend\":false}}"
Problem is here, json string consist this object:
"STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"}
Condition of string which I want modified:
string start with "statusMessage":"
string can has any *lenght from 0 -N *
string end with ", "addTime
So I try write pattern for string which start with "statusMessage":", has any lenght and is ended with ", "addTime.
Here is it:
const string pattern = " \" statusMessage \" : \" .*? \",\"addTime\" ";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
//here i would replace " with empty string
string result = regex.Replace(jsonString, match => ???);
But I think pattern is wrong, also I don’t know how replace double quotes with empty string (remove double quotes).
My goal is :
"statusMessage":" "some "bad" value"
to "statusMessage":" "some bad value"
Thank for advice
To serialize json on client side I use something like this:
var JSON = JSON || {};
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
then
$.ajax({
...
data: JSON.stringify({
someThing1: [
{ Id: '001', FooValue: ''},
{ Id: '002', FooValue: ''}
],
someThing2: [
{ Id: '001', FooValue: ''},
{ Id: '002', FooValue: ''}
]
}),
...
});
On server-side I use Newton.Json ( http://james.newtonking.com/pages/json-net.aspx )
object deserializeObject = JsonConvert.DeserializeObject(requestParameterTextRepresentation, RootType);
If you have no ability to modify client-side script to pass correct json-string, then all your regexps are vain effort.
This should do it:
var str = '"STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"}"';
str = str.replace(/("statusMessage"\s*:\s*")(.+?)("\s*,\s*"addTime)/, function(m0,m1,m2,m3) { return m1 + m2.replace(/"/g,'') + m3; });
//now str == "STATUS_MESSAGE": {"statusMessage":" some bad value ", "addTime" :"1294872330"}"
Edit: sorry i don't know why i confused this with a javascript question :s - You are able to do a very similar approach in c# tho i can't come up with the syntax right now.
While it is an extremely weak, hacky, solution, this should work in simple cases:
string pattern = #"(?<=""statusMessage"":"").*?(?="",""addTime"")";
string result = Regex.Replace(malformedJSON, pattern,
match => match.Value.Replace("\"", ""));
I'm using lookarounds to find the string, and then remove all quotes from it. You may also escape them by replacing with "\\\"".
Try This (Not a perfect solution though):
string data = "\"STATUS_MESSAGE\": {\"statusMessage\":\" \"some \"bad\" value\" \", \"addTime\" :\"1294872330\"}";
Regex rxStatusMessage = new Regex("\\s*\"statusMessage\"\\s*:\"\\s*");
Regex rxAddTime = new Regex("\",\\s*\"addTime\"\\s*:");
data = rxStatusMessage.Replace(data, "\x02");
data = rxAddTime.Replace(data, "\x03");
Regex rxReplace = new Regex("\x02.*\x03");
data = rxReplace.Replace(data, m => m.Value.Replace("\"", ""));
data = data.Replace("\x02", "\"statusMessage\":\"");
data = data.Replace("\x03", "\", \"addTime\" :");