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
Related
We are trying to correct the spelling of words in a TextArea
We have tried two methods onRemoveTwo failed with an IndexOutOfBoundsException
The other method onRemove works but it does a replaceAll we use replace in our code
Here are the results from both methods
Results from using onRemoveTwo
Initial text Take = Cariage NOT ME Carriag add missing voel to Carriage
Request was to correct "Cariage"
First correction results Take = Carriage NOT ME Carriag add missing voel to Carriage
With sb = sb.replace(from, to);
Request was to correct "Carriag"
Second correction results Take = Carriagee NOT MEg add missing voel to Carriage
We have this error Caused by: java.lang.IndexOutOfBoundsException
Caused by this line of code which we understand
while is finding two occurrence of the word
txaInput.replaceText(match.start(),match.end(),txtReplacementWord.getText());
Results from using onRemove
Initial text Take = Cariage NOT ME Carriag add missing voel to Carriage
Request was to correct "Cariage"
First correction results Take = Carriage NOT ME Carriag add missing voel to Carriage
Request was to correct "Carriag"
Second correction results Take = Carriagee NOT ME Carriage add missing voel to Carriagee
Notice both "Carriage" were changed to "Carriagee"
So our question is how to be more specific about the word to be corrected?
private void onRemoveTwo(){
if(txtReplacementWord.getText().isEmpty()){
txtMessage.setText("No Replacement Word");
return;
}
cboMisspelledWord.getItems().remove(txtWordToReplace.getText());
// Line Above Removes misspelled word from cboSelect
// ==================================================
String text = txaInput.getText();
String wordToFind = txtWordToReplace.getText();
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while(match.find()){
///System.out.println("Found "+word+" "+ match.start() +" - "+ (match.end()-1));
String from = word.toString();
String to = txtReplacementWord.getText();
String sb = txaInput.getText();
sb = sb.replace(from, to);
txaInput.replaceText(match.start(),match.end(),txtReplacementWord.getText());
txtMessage.setText("");
txtReplacementWord.setText("");
txtWordToReplace.setText("");
cboCorrectSpelling.getItems().clear();
cboMisspelledWord.requestFocus();
// Code above replaces misspelled word with correct spelling in TextArea
// =====================================================================
int SIZE = cboMisspelledWord.getItems().size();
if(SIZE == 0){
onCheckSpelling();
}
}
}
Workable method but changes multiple words
#FXML
private void onReplace(){
if(txtReplacementWord.getText().isEmpty()){
txtMessage.setText("No Replacement Word");
return;
}
cboMisspelledWord.getItems().remove(txtWordToReplace.getText());
// Line Above Removes misspelled word from cboSelect
// ==================================================
String from = txtWordToReplace.getText();
String to = txtReplacementWord.getText();
String sb = txaInput.getText();
sb = sb.replace(from, to);
//sb = sb.replaceAll(from,to);
txaInput.setText("");
txaInput.setText(sb);
txtMessage.setText("");
txtReplacementWord.setText("");
txtWordToReplace.setText("");
cboCorrectSpelling.getItems().clear();
cboMisspelledWord.requestFocus();
// Code above replaces misspelled word with correct spelling in TextArea
// =====================================================================
int SIZE = cboMisspelledWord.getItems().size();
if(SIZE == 0){
onCheckSpelling();
}
}
Well #Grendel I have no idea why this question is voted down. I have been working on a similar project with a TextArea and liked your code and like you found it frustrating that the StringBuilder finds any occurrence of the characters. So here is an answer the code is not real neat you will need to clean it up. I was unhappy that I had to go to a String[] array then to a ArrayList will keep working on this issue
In spite of the down votes enjoy the code
Send the check to 90.83.140.38
#FXML
private void onReplace(){
if(txtReplacementWord.getText().isEmpty()){
txtMessage.setText("No Replacement Word");
return;
}
cboMisspelledWord.getItems().remove(txtWordToReplace.getText());
// Line Above Removes misspelled word from cboMisspelledWord
// ==========================================================
String line = txaInput.getText();
oneA = line.split("\\s");
List<String> list = new ArrayList<>(Arrays.asList(oneA));
int theIndex = list.indexOf(txtWordToReplace.getText());
String gotME = list.get(theIndex);
list.remove(theIndex);
list.add(theIndex,txtReplacementWord.getText());
sb = new StringBuilder();
for (String addWord : list) {
sb.append(addWord);
sb.append(" ");
}
txaInput.setText(sb.toString());
txtMessage.setText("");
txtReplacementWord.setText("");
txtWordToReplace.setText("");
cboCorrectSpelling.getItems().clear();
cboMisspelledWord.requestFocus();
// Code above replaces misspelled word with correct spelling in TextArea
// =====================================================================
if(cboMisspelledWord.getItems().isEmpty()){
onCheckSpelling();
}
}
A similar question to a previous one I asked, but the difference being that this not for direct rendering from an underlying field - it's instead part of a some SSJS.
This is for a view column which displays the result of a SSJS function, which returns HTML that gets rendered. This HTML includes a date from a DateTime field, which gets converted to text using #Text. The problem I have with this is, #Text converts dates using the locale settings of the server, not the browser.
Is there an alternative to #Text(dateValue,"D0S0") that's browser locale aware?
The most "XPagey" way to do this is to use a date/time converter. For example (using a stand-in for the computed value):
<xp:viewColumn columnName="">
<xp:this.value><![CDATA[#{javascript:
new java.util.Date()
}]]></xp:this.value>
<xp:this.converter>
<xp:convertDateTime type="both"/>
</xp:this.converter>
</xp:viewColumn>
That "convertDateTime", with its built-in formats, will respect the browser's provided locale. If you set the option in the Xsp Properties to use the browser's time zone and "Round trip", it should also respect the user's time zone.
I've managed to get round this by using DateFormat.getDateInstance. The only problem with this is it doesn't return a short date in the same format as the XPage date converter (no leading zeros and a 2-figure year). I've got round this though with some fiddling around with the string after.
Here's the full function:
function returnLocalShortDate(ndtDate) {
// Receives NotesDateTime object, Java date or string; returns localised date string in XPages short date format
importPackage(java.text);
if (#IsText(ndtDate)) { // string
var jsDate = #TextToTime(ndtDate);
} else if (ndtDate instanceof Date) { // Java date
var jsDate:Date = ndtDate;
} else if (#IsTime(ndtDate)) { // Notes date/time
var jsDate:Date = ndtDate[0].toJavaDate();
} else {
return("");
}
var strDate:String = java.text.DateFormat.getDateInstance(DateFormat.SHORT, context.getLocale()).format(jsDate);
var strYear = jsDate.getFullYear();
var strDateArray = strDate.split("/");
strDate = ('0' + strDateArray[0]).slice(-2) + '/' + ('0' + strDateArray[1]).slice(-2) + '/' + strYear;
return(strDate);
}
Actually, if you know the format you want, rather than what the user might want via their browser settings, you should use the SimpleDateFormatter class. You can supply the format in accordance with whatever pattern you want from the javadocs for that class. If you supply the NotesDocument object and the field name, this returns the date in dd-MMM-yyyy format.
function getFormattedDate ( doc:NotesDocument, fieldName:String ) {
importPackage(java.text);
var dateFormatter:java.text.SimpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
var d:Date = new Date(#Today());
if ( doc.hasItem (fieldName) ) {
var valueVector:java.util.Vector = doc.getItemValueDateTimeArray(fieldName);
var iterator = valueVector.iterator();
while (iterator.hasNext()) {
var itemvalue = iterator.next();
if ((typeof(itemvalue)).endsWith("DateTime")) {
d = new Date(itemvalue.toJavaDate());
return dateFormatter.format(d);
}
}
} else {
return fieldName + " is not on the document"
}
}
I owe credit to Declan Lynch's blog entry on date formatting, which takes a little debugging because SSJS returns the date value as an Vector now.
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;
}
I have this code,but getting some error.after that i change the code.but i wanted to know is that correct.
modifiedMessage = convertToISOfromUtf8(modifiedMessage, "ISO8859-1", "UTF-8");
char[] characters_to_removed_from_start = { ' ' };
modifiedMessage = modifiedMessage.TrimStart(characters_to_removed_from_start);
String msg_arr = modifiedMessage.Split(' ');
String keyword = msg_arr[0];
//Linq
if (keyword != null)
{
string[] key = Regex.Split(msg_arr, #keyword).Skip(0).ToArray();
// message_in = String.Join(message_in,key);
message_in = String.Join(msg_arr, key);
modifiedMessage="";
}
Those are Errors shown
Error 1 Cannot implicitly convert type 'string[]' to 'string'
Error 2 Cannot implicitly convert type 'char' to 'string'
Then i change my code like this..(Only changed code listed below)
String msg_arr = modifiedMessage.Split(' ').ToString();
String keyword = msg_arr[0].ToString();
I wanted to know my works is Correct ?
No, thats not correct, change
String msg_arr = modifiedMessage.Split(' ');
to
String[] msg_arr = modifiedMessage.Split(' ');
this will resolve "Error 1 Cannot implicitly convert type 'string[]' to 'string'"
and Error 2 dissapears also
Declare the msg_arr variable as string[] or as var.
Your syntax is not compliant to .NET and C# naming guidelines, use StyleCop to have an help.
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));},
...