Method has no supported translation to SQL(Linq to Sql) - linq-to-sql

After I execute a query on the database, and try to print the result of that execution, I got this error:
Method has no supported translation to SQL.
My code:
Table<User> users = DAL.DALConnection.Database.GetTable<User>();
var query = from user in users
where user.Get_UserName().ToString() == username
select user;
foreach (User user in query)
Console.WriteLine(user);

Is Get_UserName() a C# function you've written in your code? If so, the error coming back makes sense, because SQL Server doesn't know about that function.
Instead, you would probably want to do something like where user.username == username, assuming your table has a username field.

Related

Is it safe to check for empty value direct in query using php?

I am creating a password recovery system with expire time.
Querying like in example bellow when user click to url in their email:
SELECT * FROM PassReset WHERE selector = ? AND token = ? AND token <>"" AND tokenExpire >= NOW()
if not execute display error, Looks like it works fine on itself without any validating like if statement.
I want to know if is safe to check for empty (not null) values direct in the query and do I need more validating if it executes?

How do I use SQL statement to get data from a website if all I know is the username?

I am new to MYSQL, and I have a school task that says this:
This is the PhP code that shows how users are authenticated:
$input_uname = $_GET[’username’];
$input_pwd = $_GET[’Password’];
$hashed_pwd = sha1($input_pwd);
...
$sql = "SELECT id, name, eid, salary, birth, ssn, address, email,
nickname, Password
FROM credential
WHERE name= ’$input_uname’ and Password=’$hashed_pwd’";
$result = $conn -> query($sql);
// The following is Pseudo Code
if(id != NULL) {
if(name==’admin’) {
return All employees information;
} else if (name !=NULL){
return employee information;
}
} else {
Authentication Fails;
}
I have tried so many different things like this:
SELECT * FROM credential WHERE name= 'admin';
SELECT * FROM credential WHERE name= 'admin' and Password= 'xyz';
and I put this statement in the username box and xyz in the password box.
I am not sure if I am even approaching this correctly. The SQL statement should in the username box, correct? Is the Password box left empty? My professor hasn't covered this in class. Can someone please clarify how this is done? I have seen examples online and they all look somewhat similar to the above. But, I get the same error every single time:
`There was an error running the query [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'admin' and password= "xyz"; and Password= da39a3ee5e6b40d3255bfe95601890afd80 at line 3]\n`
Thank you all in advance!
I don't agree that the question is meant to teach people how to hack. It is meant to teach backend developer to sanitize input in order to avoid sql injection or other type of attacks.
To answer your question, you can leave the password field empty and just use the user name.
You can see on the server code that no control is made on the input as the input is taken as is and put on the sql statement. So in order to make the sql statement do what you are looking for, the field can has the following value:
admin'; --
The hyphens are sql comments that allow you to disable the last part of the select statement to not have to provide the password. And the quote and ; will close the statement. Result, you'll login as admin ;-)
Turns out this is what worked for me:
Admin’ or ‘1=1
I’m not completely sure why this also works but it does:
Admin’ or ‘

prevent SQL injection in django forms

I use this for validation:
class MyValidationForm(forms.Form):
title = forms.CharField()
body = forms.Textarea()
taxonomy = forms.IntegerField()
and this is my class-based view:
class blog_createpost(dashboardBaseViews):
template_name = "dashboardtems/blog_createpost.html"
model = {}
def post(self, request, *args, **kwargs):
form = MyValidationForm(request.POST)
if not form.is_valid():
return HttpResponse("not valid")
new_data = post(title=request.POST['title'],
body=request.POST['body'],
description=request.POST['description'],
taxonomy=get_object_or_404(taxonomy,
pk=request.POST['taxonomy']),
writer=request.user)
new_data.save()
return HttpResponse("done")
like you see i check my received request validation in this line: if not form.is_valid(): and its working on but when i add some SQL-command inside my form inputs. it does not preventing to insert the value inside database!..
means i have a field in database which contains some value like select * from user where 1=1!.
doesn't it cause sql-injection danger from user inputs?...
You have misunderstood what SQL injection means. Django has successfully protected you from such an attack, the string "select * from user where 1=1" is being treated as data, not as a command, and ended up as a value in the database.
A SQL injection attack alters the SQL that is being executed by the database. A successful attack tricks the database into executing data as commands instead. You'd not end up with select * from user where 1=1 as a value, but instead you end up with the attacker getting access to all results from the user table.
A classic error is to not properly escape data, by constructing the SQL command as a string. Lets say the server uses the following query to look up data for the current user:
SELECT * FROM user WHERE username='$user_id'
where $user_id comes from the request. Normally that'd be a login name, say
user_id = "zopatista"
so the query becomes
SELECT * FROM user WHERE username='zopatista'
If the server does not protect against SQL injection attacks, an attacker can replace user_id and inject more SQL commands:
user_id = "zopatista' OR 1=1 -- "
so after simply interpolating that string into the query, now the server will send the following SQL to the database:
SELECT * FROM user WHERE username='zopatista' OR 1=1 -- '
and suddenly the meaning of the query command has changed and the database will return all rows rather than just one row matching the login name.
The classic XKCD joke on SQL injection goes a step further and injects SQL code that deletes the whole table, rather than try to get access to more information.
A server protecting against SQL injection will make sure that user-provided data is always parameterised, sending the data to the database driver separately from the query to make sure it can never be seen as part of the query.
As long as you use Django's models and querysets, you'll be protected from SQL injection attacks. You would only be at risk if you mixed extra() or RawSQL() with user data without using their parameter features.

How to update a row in a MySQL database using Ruby's Sequel toolkit?

This should be the simplest thing but for some reason it's eluding me completely.
I have a Sequel connection to a database named DB. It's using the Mysql2 engine if that's important.
I'm trying to update a single record in a table in the database. The short loop I'm using looks like this:
dataset = DB["SELECT post_id, message FROM xf_post WHERE message LIKE '%#{match}%'"]
dataset.each do |row|
new_message = process_message(row[:message])
# HERE IS WHERE I WANT TO UPDATE THE ROW IN THE DATABASE!
end
I've tried:
dataset.where('post_id = ?', row[:post_id]).update(message: new_message)
Which is what the Sequel cheat sheet recommends.
And:
DB["UPDATE xf_post SET message = ? WHERE post_id = ?", new_message, row[:post_id]]
Which should be raw SQL executed by the Sequel connector. Neither throws an error or outputs any error message (I'm using a logger with the Sequel connection). But both calls fail to update the records in the database. The data is unchanged when I query the database after running the code.
How can I make the update call function properly here?
Your problem is you are using a raw SQL dataset, so the where call isn't going to change the SQL, and update is just going to execute the raw SQL. Here's what you want to do:
dataset = DB[:xf_post].select(:post_id, :message).
where(Sequel.like(:message, "%#{match}%"))
That will make the where/update combination work.
Note that your original code has a trivial SQL injection vulnerability if match depends on user input, which this new code avoids. You may want to consider using Dataset#escape_like if you want to escape metacharacters inside match, otherwise if match depends on user input, it's possible for users to use very complex matching syntax that the database may execute slowly or not handle properly.
Note that the reason that
DB["UPDATE xf_post SET message = ? WHERE post_id = ?", new_message, row[:post_id]]
doesn't work is because it only creates a dataset, it doesn't execute it. You can actually call update on that dataset to run the query and return number of affected rows.

LINQ to SQL - Struggling with query

I have a table with server names and logins. I need to retrieve the logins that are common across a group of servers.
Given the following data:
ServerName Login
-------------------------------
Server1 User1
Server2 User1
Server2 User2
I would pass in Server1,Server2 and get back only User1 as User2 is not associated Server1.
Can anyone tell me how this would be achieved in LINQ to SQL?
I have tried Contains but that returns me all users on any of the servers which is kind of the opposite to what I'm looking for.
EDIT: One of my colleagues managed to write the SQL version of what I'm after....
SELECT Login
FROM ServerLogins
WHERE ServerName IN ('Server1', 'Server2')
GROUP BY Login
HAVING count(Login) = 2
but neither of us know how to translate this into a LINQ query.
ADDITIONAL EDIT:
With Ryan's help and some Googling of the differences in LINQ between VB and C# I got the following to work.
Dim logins = From l In dc.ServerLogins _
Where servers.Contains(l.ServerName) _
Group l By l.Login Into Group _
Where Group.Count() = servers.Count _
Select Login
Thanks again to everyone for their help.
Nick
Here is what I came up with. You'll probably want to check and find out what SQL it actually generates if you're worried about it.
List<string> servers = new List<string>{"Server1", "Server2"};
var logins = from l in context.ServerLogins
where servers.Contains(l.ServerName)
group l by l.Login into g
where g.Count() == servers.Count
select g.Key;
Personally I think this is a good place NOT to use Linq to SQL and instead to use either a sproc or a standard SQL query. I think that even if you were to come up with the correct query in Linq, it would not be very readable and/or efficient.
The SQL you would have would look something like this:
SELECT Login
FROM ServerLogins
WHERE ServerName IN ('Server1', 'Server2')
GROUP BY Login
HAVING COUNT(*) = 2
Note that the "2" in the last line should be replaced with the number of server names in the list above ("IN ('Server1', 'Server2')").
As long as there's a reasonable practical limit on the # of servers being passed in I'd go with something like this:
public ICollection<Login> GetLoginsForServers(params string[] servers)
{
if (servers == null || servers.Length == 0)
return new List<Login>();
var logins = db.Logins.Where(p => p.ServerName == servers[0]);
for (int i=1; i<servers.Length; i++)
{
logins = logins.Intersect(db.Logins.Where(p => p.ServerName == servers[i]));
}
return logins.ToList();
}
Basically you're starting with all the logins associated with the first server then limiting it by those associated with each subsequent. Since the query doesn't get executed until ToList() you still only query the database once, and although the query itself is bound to be ugly, the hope is that the LINQ2SQL provider generates something that will result in an efficient query plan.