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'"+درج کردی+"')
Related
I am using ArcSDE and Oracle with the ST_GEOMETRY spatial type. I'm writing C# code using SqlGeoemtry types. What i want is to be able to request an intersect but use wkb instead of wkt.
I know it works with wkt but if my feature has many vertices I get an error from Oracle about the string literal being too large ( i guess it is 2000 characters or so).
I also know that i can chunk that large string into a CLOB and send the chunks in and have the intersect operation work.
What I would like would be to use the binary format and avoid all of these issues. But i'm having trouble with the syntax. Here is what works for wkt:
oracleCommand.CommandText = string.Format("SELECT OBJECTID FROM {0} WHERE sde.st_intersects(shape, sde.st_polyfromtext('{1}', 3071)) = 1", selectionLayerName, unionedBuffer.ToString());
Here is what does not work right now:
oracleCommand.CommandText = string.Format("SELECT OBJECTID FROM {0} WHERE sde.st_intersects(shape, sde.st_polyfromwkb('{1}', 3071)) = 1", selectionLayerName, unionedBuffer.STAsBinary());
Obstacle's complaint is ORA-29900: operator binding does not exist
What can i do to get Oracle to accept the incoming feature in a Binary format?
I figured it out. I had to create an Oracle parameter as a Blob then load in the byte array from the SqlGeometry call:
oracleCommand.CommandText = string.Format("SELECT OBJECTID FROM {0} WHERE sde.st_intersects(shape, sde.st_polyfromwkb(:THEBLOB, 3071)) = 1", selectionLayerName);
OracleParameter param = oracleCommand.Parameters.Add(new OracleParameter(":THEBLOB", OracleDbType.Blob));
param.Value = unionedBuffer.STAsBinary().Value;
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?
I want to security test our app. The column and user input text fields are set to maxlength of 500.
currently my attempt at creating such a string is catalog.Reward_desc=Enumerable.Range(1,500).Select (e =>"ﻷ").Delimit(string.Empty);
to see if I can get linqpad to let me search for an issue in a general c# sense.
How can I either using c# to create a string to pass into the DAL, or using a string pasted into the input element (on the html page), to make sure that this is being handled properly from front to middle and in the DAL?
edit -- adding information
here's sample code where I try to see if I've hit a character that isn't properly storable in that SQL_Latin1_General_CP1_CI_AS collated column:
var catalog= new Catalog() { Add_dt=DateTime.Now, Update_dt=DateTime.Now, Reward_name=string.Empty, Reward_image=string.Empty,Add_by=string.Empty,Update_by=string.Empty, Redemption_type_id=1 };
using(var db = new UserQuery(this.Connection)){
db.Catalogs.Max (c => c.Reward_desc.Length).Dump();
this.Connection.Open();
using(var tran = new TransactionScope())
{
var source=Enumerable.Range(1,500).Select (e =>"€").Delimit(string.Empty);
catalog.Reward_desc=source;
catalog.Reward_desc.Length.Dump();
db.Catalogs.InsertOnSubmit(catalog);
db.SubmitChanges();
db.Catalogs.Max (c => c.Reward_desc.Length).Dump();
var desc=db.Catalogs.Where(c=>c.Reward_catalog_id == catalog.Reward_catalog_id).Select (c => c.Reward_desc).First().Dump();
(desc==source).Dump();
}
db.Catalogs.Max (c => c.Reward_desc.Length).Dump();
}
Write a string and then read it back and compare values. If you use non-ansi letters, readed string will most probably be invalid (for example, extended letters will come back as ?.
Your picked character looks az a good candidate, however, it depends on the 8-bit encoding of the actual database.
var source=Enumerable.Range(1,500).Select (e =>'\u0FFE'.ToString()).Delimit(string.Empty);
is a legal varchar(500) but when stored in the db and pulled back out comes out with the high bits truncated. So no exceptions, but truncation sounds like it is dangerous if the browser will submit it this way and c# will run it to the db (passing most validation because it's not containing anything blacklisted by c# checks.)
lCommon.SetCommandObject("select Card_Id,Date from Student_Attendance where Card_Id='" + CardId + "'AND Date='"+AttenDate+"'");
lReader = lCommon.objCommand.ExecuteReader();
bool flag = lReader.Read();
if (flag != true)
{
checkAtenDate = lReader["Date"].ToString();
AttenCardId = lReader["Card_Id"].ToString();
}
I have this code where lcommon and lreader are from my classes. CardId and AttenDate are variables. Now my requirement is to match Card_Id and Date from the SQL Server 2008 database, and then on its basis perform a task for that particular value.
I have tried converting the variable value to string and also to datetime format. And even tried by changing datatype in database to date, datetime and also string but unable to match the date value. Kindly help me in doing it. Actually I am trying to match today's date (getting from system) and match it from the database value for per day and perform my task accordingly.
The present problem is the bool value comes true for flag!= true i.e. flag's value is false and the values are not stored in the variables. Do help me.
Use command.Parameters.AddWithValue method and rewrite your SQL:
lCommon.SetCommandObject("select Card_Id,Date from Student_Attendance where Card_Id=#Card_Id AND Date=#AttenDate");
I have a UNICODE string (chinese) which I want to convert back to MBCS so as to add it as a parameter to an SQL query. (the column in SQL Server in varchar and so this conversion is necessary for me).
How can I convert to MBCS in c#?
Please help.
Thanks,
Praseo
“MBCS” could be a number of encodings. For the China locale, it would be code page 936, a GB-variant, and you could encode to its bytes using:
byte[] bytes= Encoding.GetEncoding(936).GetBytes("你好")
=>
{196, 227, 186, 195}
If you aren't specifically talking about GB encoding and want whatever multibyte encoding is the default for your current system, then you can just use the Default (“ANSI”) encoding which will be that MBCS encoding:
byte[] bytes= Encoding.Default.GetBytes("你好")
=>
{196, 227, 186, 195} // on a system in the China locale (cp936)
{167, 65, 166, 110} // on a system in the HK locale (cp950)
Now to get your byte array into the query you'll have to either:
1) best, use a parameter with a byte-based SqlDbType, eg:
command.Parameters.AddWithValue("#greeting", bytes);
2) orif you have to insert it directly into the query string, encode the bytes as a hex literal, eg:
"0x"+BitConverter.ToString(bytes).Replace("-", "")
=>
... WHERE greeting=0xC4E3BAC3 ...
(this is non-ANSI-standard SQL Server syntax)
Thanks bobince for the hint.
I could not parameterize my query execution though.
Finally, one of my senior colleagues helped. :)
Here is another solution to convert a Unicode encoded string to one consisting of Multibyte characters(MBCS) for comparison in T-SQL against varchar columns in legacy database.
We can make use of the method GetNonUnicodeBytes() of the class SqlString.
Here is a code snippet below.
string inputUnicodeString = "你好";
SqlString mySqlString = new SqlString(inputUnicodeString);
byte[] mbcsBytes = mySqlString.GetNonUnicodeBytes();
string outputMbcsString = string.Empty;
for (int index = 0; index < mbcsBytes.Length; index++)
{
outputMbcsString += Convert.ToChar(mbcsBytes[index]);
}
This helped me compare the required varchar database column with user requested string in UNICODE.
Hope this reply helps others.
Regards,
Praseo
I'm not sure whether you want this:
string result = Encoding.GetEncoding("gb2312").GetString(Encoding.Unicode.GetBytes(yourStr));