Is there a way/function/reg-ex in SQL Server or Visual Studio by which we can escape any character/special character within a string?
I have a functionality/page where there are server text field and user can enter any kind of string there (including special characters). And as a result I am showing a JSON string as a 'Key', 'Value' pare of those text fields entries.
For ex: I have these fields on a page:
Name , LastName , Address
And the entered values for above fields are:
Name : *-+-#. Wwweee4426554456666yyyy5uuuuttrrrreree6655zfgh\\][;'/.uuuuuuuu66uuyt,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\
LastName : Piterson
Address : Park Road, LA
And I am showing the output like a JSON string below-
[{"Key":"Name","Value":"*-+-#.Wwweee4426554456666yyyy5uuuuttrrrreree6655zfgh\\][;'/.uuuuuuuu66uuyt,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\"},{"Key":"LastName","Value":"Piterson"},{"Key":"Address","Value":"Park Road, LA"}]
But while parsing this string I am getting a parsing error below -
"After parsing a value an unexpected character was encountered: K. Path '[4].Value', line 1, position 1246."
I am using below SQL Server function to parse the string -
ALTER function [dbo].[fnEscapeString](#text nVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
as
BEGIN
--if(CHARINDEX() )
if (CHARINDEX('\',#text) > 0)
set #text = Replace(#text,'\','\\')
if (CHARINDEX('"',#text) > 0)
set #text = Replace(#text,'"','\"')
return #text
END
This function is working in many other cases (with many other strings). But not working with above string. I think this function is not enough able to parse all kind of strings.
So is there any way where we can parse a string in a valid JSON row format. May be any reg-ex or sql function can do that. Please suggest.
You can directly convert your table data to json in 2016 for example,
SELECT name, surname
FROM emp
FOR JSON AUTO
but in case of lower versions you have to convert your sql table data to xml and then to Json.
Please refer this link to parse SQL Data to Json.
http://www.codeproject.com/Articles/815371/Data-Parsing-SQL-to-JSON
You can try this as mentioned here
var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + text + ')');
Try converting the input string to JSON by using:
a) System.Web.HttpUtility.JavaScriptStringEncode
string jsonEncoded = HttpUtility.JavaScriptStringEncode(s)
or
b) NuGet Package Newtonsoft.Json
string jsonEncoded = JsonConvert.ToString(s)
Reference: How to escape JSON string?
Related
I have a string for billingpostalcode. When you enter pure numbers on it ex: '12345' then it is working fine. But for example you put '123aa' or 'abcde' it is producing an exception. It is a string and not an integer so i don't understand the error.
{"Unexpected character encountered while parsing number: s. Path 'billingPostalCode', line 1, position 119."}
string billingPostal = billingPostalCode;
var obj = JsonConvert.DeserializeObject($"{{ 'odrDetailHdr' : {orderDetailHeaderJson}, 'billingPostalCode' : {billingPostal}, 'odrProductList': {orderTrackingDetailsProductJson}, 'odrDetailOtherHdr': {orderDetailOtherHeaderJson} }}");
Anyone has an idea why?
There is different notation between a string and a number in the json format.
"employee":{ "name":"John", "age":30, "city":"New York" }
Notice the difference between the string "name":"John"and the number "age":30, They are not interchangeable
However, in your example you could add the quotes, or use a converter via an attribute when using json.net
I am assigning Urdu text to a variable in c# and inserting it into database (SendMessages table), it saves Urdu message perfectly without any modification, great but when that message is received in any mobile handset then it appears as ??????????????????????, why ? i checked it with all urdu compatible handsets which receive other urdu messages perfectly but not this one.
Code asp.net:
String MessageLanguage= Convert.ToString(ViewState["LanguageCode"]); //
if (MessageLanguage == "ur")
{
String UrduMsg = ComplaintCode +" "+"اپکی سثیکایت درج کردی گیؑ ھے۔ سثیکایت کوڈ یہ ہے";
quebiz.Insert(lblContact.Text, UrduMsg, null, Convert.ToInt32(lblComplainantID.Text), null, null);
ViewState["LanguageCode"] = null;
}
In simple words, urdu message being passed from C# into sql table is fine and perfect, not problem but after receiving same sms in handset, it doesn't work that way. I tried base64 conversion like
String UrduMsg = ComplaintCode +" "+"اپکی سثیکایت درج کردی گیؑ ھے۔ سثیکایت کوڈ یہ ہے";
var UrduMsgBytes = System.Text.Encoding.UTF8.GetBytes(UrduMsg);
var Base64EncodedUrduMsg = Convert.ToBase64String(UrduMsgBytes);
but it resulted in saving a long string in database like it is rendering yu98yhr9h93h99hd9h9ash9dhas9yr090u0usjaosfhiehhw8hw.
Collation on column is ON, column is Nvarchar(1600).
why ? help ? I am using asp.net C#.net 4.0 with sql server 2014.
I am not sure but you can try N parameter for Insert command.
For example use:
insert into tableName(name) values(N'"+درج کردی+"')
I'm having problems reading the ampersand symbol from an XML file:
XElement xmlElements = XElement.Load(Path_Xml_Data_File);
I get error when I have:
<Name>Patrick & Phill</Name>
Error: Name cannot begin with the ' ' character, hexadecimal value 0x20. Xml.XmlException) A System.Xml.XmlException was thrown: "Name cannot begin with the ' ' character
Or with special Portuguese characters:
<Extra>Direcção Assistida</Extra> (= <Extra>Direcção Assistida</Extra>)
Error: Reference to undeclared entity 'ccedil'
Any idea how to solve this problem?
I'm afraid that you're dealing with malformed XML.
To represent the ampersand, the data that you're loading should use the "&" entity.
The ç (ç) and ã (ã) named entities are not part of the XML standard, they are more commonly found in HTML (although they can be added to XML by the use of a DTD).
You could use HtmlTidy to tidy up the data first, or you could write something to convert the bare ampersands into entities on the incoming files.
For example:
public string CleanUpData(string data)
{
var r = new Regex(#"&\s");
string output = r.Replace(data, "& ");
output = output.Replace("ç", "ç");
output = output.Replace("ã", "ã");
return output;
}
I have gotten a Json string to parse before that was an array of objects much longer than just a simple string, which makes me think that I'm doing something wrong with the formatting.
Here is word for word what our webservice is outputting as the json string:
{"news":"What is Legal/Awesome Dre"}
the first part is simply what I named the string in the application (news) and the second part is the string that will be changing as the song does which is why I would like to pull in a simple string of it.
When I run the app I'm getting a parse error at these lines:
Console.Out.Writeline (content);
news = JsonConvert.DeserializeObject(content);
The application output will show the Json string as it is on the website, but I get an error right after that's telling me Invalid Token: startPath... which last time meant that my Json string was formatted wrong for how I need to grab the data.
Anyone can help me with this?
(P.S. I am working in Xamarin Studio (mono for android) using C#, if that makes any difference)
The problem is that your serialized JSON object isn't a string, it's an object with the string value you want at the "news" property/key/name. This is a simple way to get the string:
dynamic jsonObj = JsonConvert.DeserializeObject(content);
string news = jsonObj.news;
Or you can use an anonymous type:
var jsonObj = JsonConvert.DeserializeAnonymousType(content, new { news = "" });
string news = jsonObj.news;
Or create a type with a string News property:
MyNewsType jsonObj = JsonConvert.DeserializeObject<MyNewsType>(content);
string news = jsonObj.News;
These all work in the following way:
var content = #"{""news"":""What is Legal/Awesome Dre""}";
// above code
Console.WriteLine(news); // prints "What is Legal/Awesome Dre"
Try to put square bracket in your JSON:
[{"news":"What is Legal/Awesome Dre"}]
I have a c# function that needs to write to a SQL image column. I have the image in a byte array. The standard seems to be the use of SqlCommand while passing the byte array as a parameter of type System.Data.SqlDbType.Image.
Unfotunately, my function can only use text queries (don't ask why) so I have to find a way to use T-SQL commands only. What I have so far can write to the column but I don't know what format of string to make the image blob string.
sql = "DECLARE #ptrval binary(16)" +
"SELECT #ptrval = textptr(Photo) FROM EMPhoto WHERE Employee='" + employeeID + "'" +
"WRITETEXT EMPhoto.Photo #ptrval " + imageByteArrayAsString;
I've tried converting imageByteArray to a Hex string and Binary string but it doesn't seem to end up correct in SQL or in the application that reads it.
A T-SQL Binary constant is an unquoted hexidecimal string prefixed with 0x. ie 0xFFD8FFE0...
string imageByteArrayAsString = "0x" + BitConverter.ToString(image).Replace("-", string.Empty);