c# , Mysql data comparison issue - c#

I am using mysql with asp.net to save data in DB . When I save data in DB after using server.HTMLEncode(), the data is saved after removing \ . This is how I am saving data
INSERT INTO Users(ID,Name) Values(1,Server.HTMLEncode(User.Identity.Name))
In this case if name is XXX\ABC , it is being saved as XXXABC. Slashes are removed while saving in DB.
Next time when I read the same , I need to check if logged in user is the one against whom I saved data so I do following
if ( existingRowEditor == Server.HtmlEncode(User.Identity.Name))
{
}
but the issue is that the above condition is always false because I have following values
existingRowEditor="XXXABC" and Server.HtmlEncode(User.Identity.Name) =XXX\\ABC.
So how can I check if the above condition is true?

HTML encoding is not suitable for encoding data for storage in the database.
The reason that the backslashes disappears is that you are pasting together SQL code, and encoding the text for display in the web page instead of escaping it for being text in an SQL query. The backslash is used as escape character in MySQL, so any bacslashes in the string will escape the next character.
Preferrably you should use parameterised queries instead of concatenating the data into the SQL query. If that is not possible, you must escape the text properly to be in a string literal in SQL code, so you have to replace every backslash with double backsashes, and prepend every apostrophe with a backslash. If you fail to escape it properly, you application will be wide open for SQL injection attacks.
HTML encoding values should be done when you display it in a web page, not before you put it in the datbase.

You could use the following:
var sqlQueryString = "INSERT INTO Users(ID,Name) Values(#Id,#Name)";
var sqlCommand = new SqlCommand(sqlQueryString, sqlConnection);
sqlCommand.Parameters.Add(new SqlParameter("Id", 1);
sqlCommand.Parameters.Add(new SqlParameter("Name", User.Identity.Name);
sqlCommand.ExecuteNonQuery();

Related

Reading signs like Č, Ć, Š, Đ, Ž, from Oracle

I need to display some data from Oracle. But Address name contains some special character like "Č, Ć, Š, Đ, Ž" etc. These special characters are displayed properly in database, but when I try to get values from database using c#, I get this from dataReader:
for Č, I get È
for č, I get è
for Ć, I get Æ
for ć, I get æ
for Ž, I get \u008e
for ž, I get \u009e
for š, I get \u009a
What I need to do to get from dataReader the same value like value from database? I didn't find the answer on google yesterday, so I decided to ask here.
Someone please help.
I'm using C# and Visual Studio 2015. I just need to select rows from base, I'm not able to update or insert values. This is my code:
private OracleConnection _connection;
private OracleCommand _command;
public List<Address> GetAddressList()
{
string query = "SELECT id, name FROM address";
_command = new OracleCommand(query, _connection);
OracleDataReader dataReader = _command.ExecuteReader();
List<Address> addressList = new new List<Address>();
while (dataReader.Read())
{
Address address = new Address
{
id = dataReader["id"].ToString(),
Name = dataReader["name"].ToString()
};
addressList.Add(address);
}
dataReader.Close();
return addressList;
}
This question is basically the same: Trouble using/displaying special characters from Oracle db in .Net app
You have some data stored in database and You need to display them. There are several things that must be checked:
1) Have I been using the right encoding during save?
2) Are the information stored in the database in readable form (correct encoding codec)?
3) Am I using correct encoding during data receive (decoding)?
It is important to check all 3 things, as You might encode them good, but Oracle (or any DB) will just convert them to final encoding, which might not support the characters. Also when You will query this against DB, it will return in the set encoding and You will be converting it to some final form.
EDIT:
As the database is storing all the characters in this encoding: WE8ISO8859P1, I would recommend You to read other StackOverflow answer:
- NLS_CHARACTERSET WE8ISO8859P1 and UTF8 issues in Oracle
Problem is that the characters are stored as 1 byte (8 bits) only and the encoding is for American_America, You will be unable to store such characters as 'ž' 'č' or others.
Solution would be to change Encoding of the Table and/or better for whole Database.
EDIT #2 as Wernfried Domscheit stated:
You database character set is WE8ISO8859P1. This character set does not support characters like Č, Ž, š, see ISO-8859-1. Unless you use NCHAR data type, resp. migrate your database character set to something else you cannot insert or select such characters.

How to Insert Data in Database if it has Quotes or apostrophe

I am taking the input of address from the user in my existing application.
The issue which is coming often is that the user enters any apostrophe or quotation in data due to which exception occurs.
For example :
The user input is :
PLOT # B-102 BLOCK 'C'
Due to the quotes, exception occurs when the data is inserted in database as it looks the syntax mistake in oracle database.
I gone through the following example:
INSERT INTO Person
(First, Last)
VALUES
('Joe', 'O''Brien')
/\
right here
But it depends upon the location where the apostrophe will be inserted , but in my case I don't know whether and where will the user will try to insert such quotations.
How can I handle this ?
Can anyone please help me
Thanks in advance.
It seems like you are building your insert statement by concatenating the string. This is not a good practice. Your application will become vulnerable to SQL injections. You should use parametrized queries to do this.
If you still want to do this, you can use the replace method to replace ' to '' like following code snippet
Replace("'", "''")
To use parameterized queries check the following links.
http://www.techrepublic.com/article/shorten-development-time-by-using-parameterized-queries-in-adonet/
https://www.safaribooksonline.com/library/view/adonet-in-a/0596003617/ch04s04.html
You need to replace the single quotes with 2 single quotes to escape the single quote
string Address = txtAddress.Text;
Address = Address.Replace("'","''");
You can also try this...
string address = "PLOT # B-102 BLOCK \'C\'";
Details: https://msdn.microsoft.com/en-us/library/267k4fw5(v=vs.110).aspx

Escape ( ' ) symbol in Textbox for asp.net c#

Currently I learning the asp.net in c#,
I found that if I allow users to input some value in Textbox field,
the (') simbol will cause the sql statement throw error
the good practices to avoid this kind of error is to block the symbol using javascript like "event.keyCode!=222" or replace it by other symbol?
If you are using an ORM (such as entity framework) the (') symbol should not be an issue.
In any case you should handle special characters on the server side (C#) and not the client side (JS) , otherwise your code will be vulnerable to SQL injection and other nasty pests.
It's not only the ' character, there can be more. Check this Which characters are actually capable of causing SQL injection in mysql for better understanding.
And you should do the filtering on server side, do not rely on client side JavaScript as that can be skipped.
Better option is to use a stored procedure, and pass the value submitted by user through a parameter, instead of dynamically constructing SQL strings. That could reduce the risk of SQL injection.
If you want to prevent SQL injection by escaping query string, either use methods which convert apostrophes and special symbols into plain text on server-side, or use parameterized queries with stored procedures.
You can perform Regex.Replace to escape all apostrophes and double minus (comment sign) to plain query string on server side similar to this:
String yourEscapePattern = "[escaped patterns]";
String replacementString = "[replacement here]";
Regex reg = new Regex(yourEscapePattern);
String query = Regex.Replace(input, replacementString);
Parameterized query example:
using (var command = new SqlCommand("[stored procedure name]", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Parameter1", SqlDbType).Value = Value1;
// other parameters here
command.ExecuteNonQuery(); // or ExecuteReader
}
you can use
HttpUtility.UrlEncode("some Text'(");
befor saving your text to datebase

Replace ' with \' in all textboxes in my program

So throughout my program I have probably 50 or so text boxes in various places. I know how to replace a single quote with something (in this case ' -> \'), but I am thinking there must be a better way to do this than go through and add specific code for every single text box. I have to do this because when this stuff is getting sent to the database, if there is a single quote, it gives an error. Is there a way to change the default TextBox control behavior so that all textboxes in the program automatically replace all single quotes with \'?
EDIT:
string statement = "select count(*) from users where username='#username'";
MySqlCommand command = new MySqlCommand(statement, conn);
command.Parameters.AddWithValue("#username", username);
if (Convert.ToInt32(command.ExecuteScalar()) == 1)
I have been playing with the paramerterized code and this is what I have right now. From how I understand it, the statement string is basically the same as before, but where I used to have the variable "username" I know use a parameter (which I called #username), then the command is created. Then in the parameters.addwithvalue, it replaces the parameter username, with whatever is in the variable username. Unfortunately, this is not working for me, and I don't really see how it helps because username is still just getting stuck in the command?
EDIT: Found the problem, in the statement you don't need to put single quotes around '#username'
so it should be:
string statement = "select count(*) from users where username=#username";
Don't use concatenation to build SQL queries. Use proper parametrized queries. This will make repeated queries a bit faster and will also eliminate input sanitizing code (replacing ' with \' for example) and SQL injection attacks.
You should be using parameterized queries, not only to resolve the problem you have, but also to reduce your exposure to SQL injection. When you use string concatenation to build SQL queries you are suseptable to SQL injection attackes.
U can use onKeyUp javascript function or asp.net OnTextChanged event to create function that will change quotes.

SQLite issues, escaping certain characters

I'm working on my first database application. It is a WinForms application written in C# using a SQLite database.
I've come across some problems, when a apostrophe is used, my SQLite query fails. Here is the structure of my queries.
string SQL = "UPDATE SUBCONTRACTOR SET JobSite = NULL WHERE JobSite = '" + jobSite + "'";
For instance, if an apostrophe is used in the jobSite var, it offsets the other apostrophes in the command, and fails.
So my questions are:
1. How do I escape characters like the apostrophe and semicolon in the above query example?
2. What characters do I need to escape? I know I should escape the apostrophe, what else is dangerous?
Thanks for your help!
Rather use Parameters
There is a previous stack-overflow question about it
Adding parameters in SQLite with C#
if you need more functionality you can also use Entity Framework
http://sqlite.phxsoftware.com/
Sorry not to familiar with the Syntax but the concept should same.
Something like :
SQLiteCommand Command = "UPDATE SUBCONTRACTOR SET JobSite = NULL WHERE JobSite = #JobSite";
Command.Parameters.Add(new SQLiteParameter("#JobSite", JobSiteVariable));
command.ExecuteNonQuery();
to escape an apostrophe add another apostrophe...
so a string like it's should be inserted as it''s
You may also need to escape quotation marks. The way to do this is to use a backslash as an escape charater...
like so... 'and he said\"escape all those quotes\"'
You should also beware of SQL injections... depending on the type of programming language you are using there exist different functions that can help clean out any malicious code.
C# tutorial on SQL Injections for example
You should never concatenate strings to build SQL queries for SQLite - or for any other SQL DB if possible. It makes your code fragile and opens up potential entry points for injection attacks.
The proper way to do it is to use hosted parameters. This approach removes the need for cumbersome string filtering. I am not sure how to do that in C# for SQLite but any decent language binding for SQLite should allow you to use hosted parameters.

Categories

Resources