Validation of symbols in search textbox - c#

I experienced error when typing symbols in my search box. I already used the ajax tool to validate symbols like " ' / etc. ". With this, you are not allowed to type any symbols you declared to be invalid. What if I will search for a character or word that contains that symbol? For example, the name of the customer I want to search is O'Brien but how will I search if I am not allowed to type that symbol?

You won't be able to. That is why you have set that value as invalid. Remove the value from the invalid symbols and you will be able to.
If a symbol can be valid some of the time but not all of the time, it is probably better to allow it by default than block it. That way you are less likely to upset an end user.
If you are required to then you should handle the symbol in your code that processes the search.

That's a bit tricky. You should not allow user to add such stuff to the database I mean he should not be inserting any data while signing up, so that you don't have to worry about it later. If you want to let the users add these special characters then you must do the coding work while letting the user search for that name of whatever it is.
Solution:
If you are using JavaScript (jQuery) then you can try out this:
What you will do here, is:
First get the input value.
Replace ' character will `` (empty).
Then check whether that was the only character placed.
Code is as follows:
if($('#input-id').val().replace("'", "") == "") { // only quote was written
$('#input-id').val(''); // and tell him to write a name..
} else {
// search for name..
}
Secondly I will assume you are talking about SQL Injection, because using ' in SQL Select clause of LIKE will break the Query, so I will first try to tell you either save the name without these characters or try to change them into some other format. Here http://www.ascii.cl/htmlcodes.htm
Otherwise, try to learn about SQL Injections.
Ajax:
You said you are using Ajax, so if you are using ASP.NET. You can use this:
var data = Request["data"];
data.ToString().Replace("'", "");
if(data == "") {
// tell him to behave!
} else {
// search for name..
}
This is the easiest way to get rid of these characters without using any plugin.
its just JavaScript.

Related

SELECT from PHP (MySQL) Back Into Android (C#)

I have an Android app and I'm attempting to use PHP/MySQL.
I'm having a lot of trouble getting my results from PHP accessible in C#/Android.
This is my PHP so far:
$sql = "SELECT Name FROM Employees WHERE Password='$password'";
if(!$result = $mysqli->query($sql)) {
echo "Sorry, the query was unsuccessful";
}
while($employee = $result->fetch_assoc()) {
$jsonResult = json_encode($employee);
$employee->close();
}
I've left out the basic connection code as I have all that up and running. Here is my C#:
private void OnLoginButtonClick()
{
var mClient = new WebClient();
mClient.DownloadDataAsync(new Uri("https://127.0.0.1/JMapp/Login.php?password=" + _passwordEditText.Text));
}
As you can see I really am at a very basic stage. I've installed Newtonsoft so I'm ready to deal with the Json that is coming back, however I have a few questions.
I'm well aware of SQL injection, and the way that my variable (password) is passed to the PHP concerns me. Is there a safer way of doing this?
Secondly, I am now unsure of how to get the 'Employees' that match the MySQL command in PHP back into C#. How am I able to access the object that is passed back from PHP?
Leaving aside other aspects of the code in the question, I sugest some reading on sanitizing and escaping user data.
For this specific case of a password see #Jay Blanchard comments. For other input you would not trasform upon input, the idea is to sanitize it as soon as you receive it.
This is to make sure you receive what you were expecting. In the case of a String, trim() the text, match it against a regex of allowed characters. If you allow html tags or not you can match it against a white list of them. Max length.
Then you would validate it. This is that it makes sense and meets the business requirements.
At the time of storing it in the database you can avoid sqlinjection by using prepared statements. By doing this it is clear what is text to be stored and what is sql instructions.
At the time of using the data, you will escape it accoring to where it is going to be used, for example, if it is html content you escape it for html content, if it is an html attribute, or an URL parameter, you do the escaping accordingly for each case. (Wordpress has a nice suite of functions that do this)
Also don't send passwords as URL parameters. Use a form instead with method POST. Urls are seen in the Browser's address widget. And they also get copy pasted in emails, facebook, etc

passing multiline string variable from c# to javascript

I have a webpage that checks login credentials. The page calls a function which then makes a connection to a table in a oracle database and checks to see that this user is allow to see the application. This is all done using c# however if their is a fatal error from the database, i would like to notify the user using javascript. in my c# code i have a string variable that will basically print the javascript function into the webpage. it looks like this.
string javaScript =
"<script>"+
"var find = ':';"+
"var re = new RegExp(find, 'g');" +
"str='#"+CheckAccess[0]._ERROR.ToString().Replace(":"," ")+"';"+
"str = str.replace(re, '');"+
"if ($('#login_error').css('display') == 'none') {" +
"$('#login_error').text(str).show(); }" +
"else {Return;}</script>";
When the database return an error it return a multiline error the looks like this.
ORA-06550 line 1, column 7
PLS-00306 wrong number or types of arguments in call to 'GETUSERACCESS'
ORA-06550 line 1, column 7
PL/SQL Statement ignored at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure, Boolean bCheck)
All the examples Ive seen on the web say to break it up with "/" so that i dont continue to get the "unterminated string literal" error. However i don't see an efficient way to do this. Could there be a better way to achieve what I'm trying to accomplish or do i have to some how figured out a way to parse this string and guess where the line breaks are going to be. Any help would be most appreciated.
Thanks
Miguel
I wouldn't recommend trying to do it the way you are right now. Something smells about having JS code written out in a C# string like that, e.g. it looks like it'd be possible for an injection attack to occur, if the error message string doesn't include what you expected it to.
Instead of trying to pass JS code to the client when an error occurs, you could include the JS code to handle errors in the page to start with, then just pass a JSON-serialized data structure containing your error string. That should allow multiline strings and other special characters to pass from the server to the client correctly.
E.g. if your class is something like this:
public class MyClass
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
Then your controller method might look like:
public JsonResult TryToValidate(...)
{
MyClass myClass = // result
return Json(myClass);
}
With pseudo-JS on the login page that looks like:
MakeAjaxCallToTryToValidate(...)
.whenThatsDone(function ...() {
if !result.Success
alert(result.ErrorMessage);
});
Or, since you shouldn't really be exposing error details to average users anyway, you could just log the error's details on the server where the admin can see it, and give the user a generic error message. If it was something invalid that you might expect the user to do, (e.g. type in a wrong password) then the error message should tell them so, and how to fix it themselves, but a "wrong number or types of arguments" error isn't usually in that category.
You do not have to "guess" where the line breaks will be. The are usually represented by one or two special escape characters:
\r (CR = carriage return), and
\n (NL = new line).
(MS Windows usually use CRLF, Unix-based systems have traditionally used only LF, but this may vary). For example, you can find them with CheckAccess[0]._ERROR.ToString().IndexOf("\r\n"), and use the same technique to replace them.
Since you know you will be pushing error text directly to HTML element, you can replace the \r\n (CRLF) with <br/> (HTML line break).
Code:
CheckAccess[0]._ERROR.ToString().Replace(":"," ").Replace("\r\n", "<br/>")
Since Oracle can run on Unix machines also (for example) and may return just LF in the error message instead of CRLF you may want to be extra safe and be generic, first try to replace CRLF, then CR, then LF:
CheckAccess[0]._ERROR.ToString().Replace(":"," ")
.Replace("\r\n", "<br/>")
.Replace("\r", "<br/>")
.Replace("\n", "<br/>")
Then your javascript will not inject the whitespace from the CRLF, and will instead render the html to create the line breaks.

HttpRequestValidationException workaround

I have a textbox that when user inputs a string such as "<daily" (to signify less than daily) it throws a HttpRequestValidationException. However if there is a space between the less than symbol and the string, it works fine such as "< daily".
I have had it change the value that is submitted in the code behind by using the replace function. For example:
string s = "This is a <test";
if(s.Contains("<")){
s = s.Replace("<", "< "); //I have also used "<" & "<"
}
However, I still get the exception because in the textbox it is still showing it as "<daily". I am wondering if there is a way that if the focus is off the textbox to dynamically add a space to the string?
I understand that the HttpRequestValidationException is not supposed to allow those characters, but it seems to allow if there are spaces. Any thoughts?
It would be nice to know how you use the string in the HttpRequest. Depending on how and where you use we could come up with some ideas.

C# read and react to a text string

assume that there is a string named "message", and assume an user type in the console,
"!My FB List", but words "FB" and "List" could be change. But "!My" won't change. So, I want to save the text the user type. Only if user used "!My" before the other words.
So, I don't know how to get this to 'if' command. Plz help me.
if (message == "!My "
Do you mean something like this?
if (message.StartsWith("!My "))
{
// do something
}
This code works in most situations. However, if you need to resolve situations like Kshitij Mehta mentioned in the comments, you'd be probably better off with a Split method parsing the string and comparing the first object of the array to the required string.
When you've split the input string into an array, you will just compare strings in a typical fashion (==), probably no need for fancy methods in that scenario.
One more "however" to consider - if your input string is long, splitting might not be the best idea to do. In that case I'd probably use regular expressions to compare the beginning of the inputted string.
The implementation depends on your needs. Just pick what suits you the best :)
It sounds like you want to accept commands and then do specific things based on those commands. Apparently, the "command" is the first word in the text typed by the user.
Thus, I'd split the message at whitespace and then switch for the first word:
var words = message.Split();
var command = words[0];
switch (command) {
case "!My":
// Do something
...
break;
case "!SomethingElse":
// Do something else
...
break;
...
}
Afterwards, you can use words[1] to get "FB" and words[2] to get "list". Be sure to use words.Length to verify if the required number of parameters has been specified before trying to access them.
String class includes many static methods, among which is StartsWith().
so your if statement can simply be
if(UserString.StartsWith("!My"))
{
// other conditional code here
}
It is not clear from your question whether you want to include cases where the user types "!My" before typing anything else, but he/she does NOT type a space immediately after typing !My.
If you only want to process the code if the three characters "!My" were followed by a space, then, (as suggested by #Walther), add a space to the test string in the StartsWith() method
if(UserString.StartsWith("!My "))
{
// other conditional code here
}

multiline textbox to string

I have a multiline textbox that I wish to convert to a string,
I found this
string textBoxValue = textBox1.Text.Replace(Environment.NewLine,"TOKEN");
But dont understand TOKEN what is TOKEN? whitespace or /n newline ?
If this is the incorrect answer then Please let me know of the correct way of doing this
Thanks
In the code snippet you gave, "TOKEN" is any value you wish to insert, such as an HTML <br /> tag, more Environment.NewLines for formatting, or just some random delimiter that will later allow you to split the text on it.
A very simple example:
string text = textBox1.Text.Replace(Environment.NewLine, "^"); // a random token
string[] lines = test.Split( '^' );
If you are handling input from a textbox available on the web, you also need to take into account XSS (http://en.wikipedia.org/wiki/Cross-site_scripting). Also, in a real scenario I would split on a more complex token and make sure to handle multiple carriage returns in the input value.
EDIT: now that I see your actual requirements, this code may do what you need:
// replace newlines with a single whitespace
string text = textBox1.Text.Replace(Environment.NewLine, " ");
EDIT #2:
further I need to enter this data into
SQLite and rewrite his whole
application, The company does not wish
to have information from the previos
application inputted to the new
database, there are hyperlinks etc
inbedded in the content , so if there
is a way I can make the text box only
accept RAW data this would be the
best.
Regular Expressions are the way to go for something like this, unless the data is structured enough to load into an XML or HTML DOM and process. You can build regular expressions in a variety of tools (do a Google search for a free online tester and you will find many). Once you have determined the expressions you need, you can use the Regex object in C# to match, replace, etc.
http://msdn.microsoft.com/en-us/library/ms228595(VS.80).aspx
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(v=VS.100).aspx
As it stands, "TOKEN" is just a meangingless string, unless it is elsewhere in your code? You can replace "TOKEN" with any text you like.
Edit:
Okay, so you say you're removing NewLine's from your client's text. So you would do it like this. Paste their text into a textBox called textBox2, then use the following:
textBox2.Text = textBox2.Text.Replace(Environment.NewLine, string.Empty);

Categories

Resources