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.
Related
I am using a Rest service (asp.net core) which returns a string to the caller . The caller then is supposed to visualize that string on a html page, using a javascript "alert" function.
If the Rest service returns a string containing the "è" special character , the "alert" function always translates the "è" as a "è" sequence. Is there anything I can do to fix the situation ?
If I inspect my razor code right before the alert call, to see what the string contains , I always find the right character ("è") which makes me think the problem is generated by the alert call .
I am working on a small application based on owin and katana to handle links internally.
So the application handles HttpGet requests. When someone calls
http:localhost/?document=path/to/my/document/foo.doc
the application opens this document.
My problem is: When the document name contains a special character like '+' my code interprets the + sign as space because the variable is parsed into a string.
[HttpGet]
[Route("")]
public HttpResponseMessage Get(string document = "")
{
//open document
}
So how to preserve the special characters and don't allow c# string to convert them before executing any code?
I tried with HttpResponseMessage Get([FromUri]string document = "")
I tried encoding the document variable afterwards with HttpUtility.UrlEncode but it will also encode the legit spaces.
Meanwhile I got a workaround:
this.Request.RequestUri.OriginalString
inside of the GET Method will give the the full link as string without any interpretations. The rest is to get the relevant variable with string.substring operations.
Nevertheless it would like to know if someone knows a more elegant solution.
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
I was just wondering what the best practice is for passing a parameter into a URL that contains characters that you do not wish to pass to the URL. For example, I pass the string /LM/W3SVC/7/ROOT into the URL but I want to pass it without the backslashes, thus like LMW3SVC7ROOT
The way I currently do this is by using .Replace(). This is the full line of code that I currently use #Html.DisplayFor(modelItem => item.Application) which works fine but throws out a warning every now and again so I was just wondering if this is the correct way of implementing it.
'Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string'
Thanks in advance.
The problem you're getting is from var queryString = RouteData.Values["id"];. If you look in Visual Studio and hover over var it will tell you the type of that particular var, which in this case is Object.
Try:
var queryString = RouteData.Values["id"].ToString();
In this case, you're finding yourself having to replace certain characters in your string, which probably means server side, you might be having to do some extra logic to cope without having these characters on the received string. In your View, just wrap the id in Url.Encode:
id = Url.Encode(item.Application)
You will receive this server side with the string decoded, i.e. /LM/W3SVC/7/ROOT
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.