passing multiline string variable from c# to javascript - c#

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.

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

Getting a string from url split after a character c#

I'm trying to use a url to post a username back and fourth from another page. My current code (which gives an error "StartIndex cannot be less than zero.".
if (Convert.ToString(Context.Request.QueryString).StartsWith("username"))
{
string username = Convert.ToString(Context.Request.QueryString);
string input = username.Substring(username.LastIndexOf(":"));
txt_username.Text = input;
}
the url looks like 192.168.1.1/p/login.aspx?username:textIwantintxtbox
Obviously just trying to put the last bit into a text box.
You seem to be taking a longer way to get the value you actually want. Since you start with a QueryString, you should just use that.
txt_username.Text = Context.Request.QueryString['username'];
As for your actual error, Substring needs to start from at least index 0, LastIndexOf seems to be returning -1, indicating it hasn't found the colon, probably because get parameters normally use an = instead of a :

Send out literal string from web api in C#

I have a literal string generated by my bussiness logic that I need to send out on my web api via my controller.
The end part of my controller function looks like this, where the text variable is a literal string, thus containing "\\" to indicate a single backslash:
var text = _transformation.ToTextFormula(new Formula("", formula, parts));
return Ok(text);
The problem this creates is that when I then consume my api the duble backslashes are still there and not just the single one intended. Surely there must be a way to correct what is sent out?
If I inspect the "text" variable to look at the value in real format there is just a single slash before leaving the method.

Validation of symbols in search textbox

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.

How can i add double quotes to a string?

I want to add double quotes for a sting . I know by using /" we can add double quotes . My string is
string scrip = "$(function () {$(\"[src='" + names[i, 0] + "']\"" + ").pinit();});";
When i do this on the browser i am getting &quot instead of " quotes . How can i overcome with the problem ?
If your browser has displayed a "&quot" instead of a " character, than there are only a few causes possible. The character should have been emitted to the browser as either itself, or as a HTML entity of ". Please note the semicolor at the end. If a browser sees such 'code', it presents a quote. This is to allow writing the HTML easier, when its attribtues need to contain special characters, compare:
<div attribute="blahblahblah" />
if you want to put a " into the blahs, it'd terminate the attribute's notation, and the HTML code would break. So, adding a single " character should look like:
<div attribute="blah&quote;blahblah" />
Now, if you miss the semicolon, the browser will display blah&quotblahblah instead of blah"blahblah.
I've just noted that your code is actually glueing up the JavaScript code. In JavaScript, the semicolon is an expression delimiter, so probably there is actually a " in the emitted HTML and it is just improperly presented in the error message... Or maybe you have forgotten to open/close some quotes in the javascript, and the semicolon is actually treated as expression terminator?
Be also sure to check why the JavaScript code undergoes html-entity translation. Usually, blocks are not reparsed. Are you setting that JavaScript code as a HTML element attribute? like OnClick or OnSend? Then stop doing it now. Create a javascript-function with this code and call that function from the click/send instead.. It is not worth to encode long expressions in the JS into an attribute! Just a waste of time and nerves.
If all else fails and if the JavaScript is emitted correctly, then look for any text-correcting or text-highlighting or text-formatting modules you have on your site. Quite probable that one of them is mis-reading the html entities and removed the semicolon, or the opposite - that they add them were they are not needed. The ASP.Net itself in general does its job right, and it translates the entites correctly wherever they are needed, so I'd look at the other libraries first.
You can use something like this:
String str=#"hello,,?!"
This should escape all characters
Or
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);
Here's the manual: http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx
What else are you doing with the string?
Seems that somewhere after that the string gets encoded. You can could use HttpUtility.HtmlDecode(str); but first you'll have to figure out where your string gets encoded in the first place.
Keep in mind that if you use <%: %> in aspx or #yourvarin Razor it will get encoded automatically. You'll have to use #Html.Raw(yourvar) to suppress that.

Categories

Resources