I'm sending back a bunch of image tags via JSON in my .ashx response.
I am not sure how to format this so that the string comes back with real tags. I tried to HtmlEncode and that sort of fixed it but then I ended up with this stupid \u003c crap:
["\u003cimg src=\"http://www.sss.com/image/65.jpg\" alt=\"\"\u003e\u003c/li\u003e","\u003cimg src=\"http://www.xxx.com/image/61.jpg\" alt=\"\"\u003e\u003c/li\u003e"]
What the heck is \u003c ?
here's my code that created the JSON for response to my .ashx:
private void GetProductsJSON(HttpContext context)
{
context.Response.ContentType = "text/plain";
int i = 1;
...do some more stuff
foreach(Product p in products)
{
string imageTag = string.Format(#"<img src=""{0}"" alt=""""></li>", WebUtil.ImageUrl(p.Image, false));
images.Add(imageTag);
i++;
}
string jsonString = images.ToJSON();
context.Response.Write(HttpUtility.HtmlEncode(jsonString));
}
the toJSON is simply using the helper method outlined here:
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx
\u003c is an escaped less-than character in unicode (Unicode character 0x003C).
The AJAX response is fine. When that string is written to the DOM, it will show up as a normal "<" character.
You are returning JSON array. Once parsed using eval("("+returnValue+")") it is in readily usable condition.
EDIT: This code is from jquery.json.js file:
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
$.quoteString = function(string)
// Places quotes around a string, inteligently.
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
{
if (escapeable.test(string))
{
return '"' + string.replace(escapeable, function (a)
{
var c = meta[a];
if (typeof c === 'string') {
return c;
}
c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + '"';
}
return '"' + string + '"';
};
Hope this gives you some direction to go ahead.
all you need to do is to use javascript eval function to get a pure HTML (XML) markup on the front end.
i.e. in a ajax call to a webservice, this can be the success handler of tha call,
the service returns a complex html element:
...
success: function(msg) {$(divToBeWorkedOn).html(**eval(**msg**)**);alert(eval(msg));},
...
Related
I am getting exception
'', hexadecimal value 0x0B, is an invalid character. Line 23, position 22.
I have already tried solution from Here, but it is not working for me. As my project is in 3.5 version, I cannot use XmlConvert.IsXmlChar method MSDN
How to handle it ?
You can replace these invalid characters using the below method.
public static string CleanInvalidXmlChars(this string StrInput)
{
//Returns same value if the value is empty.
if (string.IsNullOrWhiteSpace(StrInput))
{
return StrInput;
}
// From xml spec valid chars:
// #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
// any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
string RegularExp = #"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]";
return Regex.Replace(StrInput, RegularExp, String.Empty);
}
If you don't want to remove the vertical tab (hexadecimal value 0x0B) from the string (e.g. database export), you can also set CheckCharacters to false in your XmlWriterSettings.
Gets or sets a value that indicates whether the XML writer should
check to ensure that all characters in the document conform to the
"2.2 Characters" section of the W3C XML 1.0 Recommendation. Returns:
true to do character checking; otherwise, false. The default is true.
e.g.
private static System.Xml.XmlWriter CreateXmlWriter(System.IO.Stream stream)
{
System.Xml.XmlWriterSettings xs = new System.Xml.XmlWriterSettings();
xs.Indent = true;
xs.IndentChars = " ";
xs.NewLineChars = System.Environment.NewLine;
xs.OmitXmlDeclaration = false; // // <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
// xs.Encoding = System.Text.Encoding.UTF8; // doesn't work with pgsql
// xs.Encoding = new System.Text.UTF8Encoding(false);
xs.Encoding = new System.Text.UTF8Encoding(false, false);
xs.Async = true;
xs.CheckCharacters = false;
return System.Xml.XmlWriter.Create(stream, xs);
} // End Function CreateXmlWriter
I have a hidden field that gets populated with a javascript array of ID's. When I try to iterate the hidden field(called "hidExhibitsIDs") it gives me an error(in the title).
this is my loop:
foreach(string exhibit in hidExhibitsIDs.Value)
{
comLinkExhibitToTask.Parameters.AddWithValue("#ExhibitID", exhibit);
}
when I hover over the .value it says it is "string". But when I change the "string exhibit" to "int exhibit" it works, but gives me an internal error(not important right now).
You need to convert string to string array to using in for loop to get strings not characters as your loop suggests. Assuming comma is delimiter character in the hidden field, hidden field value will be converted to string array by split.
foreach(string exhibit in hidExhibitsIDs.Value.Split(','))
{
comLinkExhibitToTask.Parameters.AddWithValue("#ExhibitID", exhibit);
}
Value is returning a String. When you do a foreach on a String, it iterates over the individual characters in it. What does the value actually look like? You'll have to parse it correctly before you try to use the data.
Example of what your code is somewhat doing right now:
var myString = "Hey";
foreach (var c in myString)
{
Console.WriteLine(c);
}
Will output:
H
e
y
You can use Char.ToString in order to convert
Link : http://msdn.microsoft.com/en-us/library/3d315df2.aspx
Or you can use this if you want convert your tab of char
char[] tab = new char[] { 'a', 'b', 'c', 'd' };
string str = new string(tab);
Value is a string, which implements IEnumerable<char>, so when you foreach over a string, it loops over each character.
I would run the debugger and see what the actual value of the hidden field is. It can't be an array, since when the POST happens, it is converted into a string.
On the server side, The Value property of a HiddenField (or HtmlInputHidden) is just a string, whose enumerator returns char structs. You'll need to split it to iterate over your IDs.
If you set the value of the hidden field on the client side with a JavaScript array, it will be a comma-separated string on the server side, so something like this will work:
foreach(string exhibit in hidExhibitsIDs.Value.Split(','))
{
comLinkExhibitToTask.Parameters.AddWithValue("#ExhibitID", exhibit);
}
public static string reversewordsInsentence(string sentence)
{
string output = string.Empty;
string word = string.Empty;
foreach(char c in sentence)
{
if (c == ' ')
{
output = word + ' ' + output;
word = string.Empty;
}
else
{
word = word + c;
}
}
output = word + ' ' + output;
return output;
}
Assuming the placeholder $2 is populated with an integer, is it possible to increment it by 1?:
var strReplace = #"$2";
Regex.Replace(strInput, #"((.)*?)", strReplace);
You can use a callback version of Regex.Replace with a MatchEvaluator, see examples at:
http://msdn.microsoft.com/en-us/library/cft8645c.aspx
http://www.dotnetperls.com/regex-replace
Here's an example (ideone):
using System;
using System.Text.RegularExpressions;
class Program
{
static string AddOne(string s)
{
return Regex.Replace(s, #"\d+", (match) =>
{
long num = 0;
long.TryParse(match.ToString(), out num);
return (num + 1).ToString();
});
}
static void Main()
{
Console.WriteLine(AddOne("hello 123!"));
Console.WriteLine(AddOne("bai bai 11"));
}
}
Output:
hello 124!
bai bai 12
In standard (CS theoretic) regular expressions, it is impossible with a regular expression.
However, Perl and such have extensions to Regular Expressions, which has implications for their behaviour, and I am not familiar enough with them to definitely say that the extended regexes will not do it, but I'm fairly sure that this behaviour is not possible with a regex.
It's not possible with a standard regular expression but you can if you write a custom MatchEvaluator.
string str = "Today I have answered 0 questions on StackOverlow.";
string pattern = #"\w*?(\d)";
var result = Regex.Replace(str, pattern,
m => (int.Parse(m.Groups[0].Value)+1).ToString() );
Console.WriteLine(result);
Today I have answered 1 questions on StackOverlow.
I have a standard HTML page with an CKEditor on it wrapped in a form.
The form submits (POSTS) to Send_Emails.aspx
Send_Emails.aspx reads the content of the FCKEditor into a variable
Dim html As String = Request.Form("ck_content")
Then it sends an email.
Problem
Characters such as:
 -> this seems to show as a special character for blank spaces/carriage returns
’ -> this seems to show as apostrophe's
Can you reccomend some methods to cleanze my post data of these non-standard characters?
Thanks
I figured out how to strip unwanted characters by using this function:
function removeMSWordChars(str) {
var myReplacements = new Array();
var myCode, intReplacement;
myReplacements[8216] = 39;
myReplacements[8217] = 39;
myReplacements[8220] = 34;
myReplacements[8221] = 34;
myReplacements[8212] = 45;
for(c=0; c<str.length; c++) {
var myCode = str.charCodeAt(c);
if(myReplacements[myCode] != undefined) {
intReplacement = myReplacements[myCode];
str = str.substr(0,c) + String.fromCharCode(intReplacement) + str.substr(c+1);
}
}
return str;
}
Anyone know of a nice efficient function that could convert, for example:
HelloWorld --> Hello World
helloWorld --> Hello World
Hello_World --> Hello World
hello_World --> Hello World
It would be nice to be able to handle all these situations.
Preferably in in VB.Net, or C#.
I don´t know if this is the most efficient way. But this method works fine:
EDIT 1: I have include Char.IsUpper suggestion in the comments
EDIT 2: included another suggestion in the comments: ToCharArray is superfluous because string implements enumerable ops as a char too, i.e. foreach (char character in input)
EDIT 3: I've used StringBuilder, like #Dan commented.
public string CamelCaseToTextWithSpaces(string input)
{
StringBuilder output = new StringBuilder();
input = input.Replace("_", "");
foreach (char character in input)
{
if (char.IsUpper(character))
{
output.Append(' ');
}
if (output.Length == 0)
{
// The first letter must be always UpperCase
output.Append(Char.ToUpper(character));
}
else
{
output.Append(character);
}
}
return output.ToString().Trim();
}
There are some other possibilities you might want to cater for - for instance, you probably don't want to add spaces to abbreviations/acronyms.
I'd recommend using:
Private CamelCaseConverter As Regex = New Regex("(?<char1>[0-9a-z])(?<char2>[A-Z])", RegexOptions.Compiled + RegexOptions.CultureInvariant)
Public Function CamelCaseToWords(CamelCaseString As String) As String
Return CamelCaseConverter.Replace(CamelCaseString, "${char1} ${char2}")
End Function
'Gives:
'CamelCase => Camel Case
'PIN => PIN
What it doesn't do is uppercase the first letter of the first word, but you can look at the other examples for ways of doing that, or maybe someone can come up with a clever RegEx way of doing it.
Sounded fun so I coded it the most important part is the regex take a look at this site for more documentation.
private static string BreakUpCamelCase(string s)
{
MatchCollection MC = Regex.Matches(s, #"[0-9a-z][A-Z]");
int LastMatch = 0;
System.Text.StringBuilder SB = new StringBuilder();
foreach (Match M in MC)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch, M.Index + 1 - LastMatch));
LastMatch = M.Index + 1;
}
if (LastMatch < s.Length)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch));
}
return SB.ToString();
}