"The multi-part identifier could not be bound" sql, visual studio - c#

I am just learning c# and sql server. This question has been asked a couple of times but the solutions posted don't seem to help me.
I have a table called "LoginInfo" that has a user's "email" and "pass".
In visual studio i have this method that checks a users login information
private boolean dbQueryLogin(string email, string password)
{
string com = "SELECT pass FROM LoginInfo WHERE email = XXXXX#yahoo.com";
SqlCommand command = new SqlCommand(com, conn);
SqlDataReader reader = command.ExecuteReader();
return reader.GetString(0).Equals(password);
}
This keeps on throwing the error "Additional information: The multi-part identifier "XXXX.edu" could not be bound."
The syntax looks right to me, is there anything i'm missing??

The clue is in the error message:
The multi-part identifier "XXXX.edu" could not be bound.
That strongly suggests that the problem isn't with identifying your table - it's with the bit that ends with "edu", which seems like to be an email address.
The immediate problem is that you've forgotten to quote a value. The deeper problem is that you should be using parameterized SQL anyway, to avoid SQL injection attacks, conversion problems and unreadable code. Given that the value you've given in the same code isn't the same as what's in the error message, I suspect you really have code like:
string sql = "SELECT pass FROM LoginInfo WHERE email = " + email;
Don't do that. Use parameterized SQL instead:
private boolean dbQueryLogin(string email, string password)
{
string sql = "SELECT pass FROM LoginInfo WHERE email = #email";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(sql))
{
command.Parameters.Add("#email", SqlDbType.NVarChar).Value = email;
using (var reader = command.ExecuteReader())
{
// FIXME: What do you want to do if
// there are no matches?
reader.Read();
return reader.GetString(0) == password;
}
}
}
}
This still isn't good code though:
Don't store plain-text passwords in a database
Handle the case where there are no results
Don't build your own authentication system at all; use an existing one written by people with more experience in securing data

Related

Unable to query Oracle database via C# API

Good morning.
I am attempting to connect to an Oracle database I have set up. before I go into detail, here's the code:
//string was slightly altered.
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=name)));User Id = system; Password = mypass; ";
string toReturn = "D.BUG-";
using (OracleConnection oracleConnection = new OracleConnection(connectionString))
{
oracleConnection.Open();
using (OracleCommand oracleCommand = new OracleCommand())
{
oracleCommand.Connection = oracleConnection;
oracleCommand.CommandText = "SELECT lixo FROM lixeira WHERE lixo IS NOT NULL";
oracleCommand.CommandType = CommandType.Text;
using (OracleDataReader oracleDataReader = oracleCommand.ExecuteReader())
{
//This point IS reached!
while (oracleDataReader.Read())
//This point is never reached...
toReturn += oracleDataReader.GetString(0);
}
}
}
return toReturn;
Now, I know for a fact that connecting works, and I know for a fact that the table "lixeira" can be found; I have tested this by changing that name to another name, and getting the corresponding "i can't find that table" exception.
'ORA-00942: tabela ou visualização não existe'. (Table or View does not exist)
The issue is that this code is unable to read. The same query ran through SQL Developer works:
SQL Developer screenshot of the same query
So, I'm kinda at a loss as to why oracleDataReader.Read() just never works. Am I doing something wrong?
Make sure your user/password in the connection string is the correct one.
If a table doesn't exist but exists... it probably doesn't exist for your current user (= that user has not the necessary permissions)
Previous answer is correct, I am just adding another bit.
can you replace your query as following :
SELECT lixo FROM <table owner>.lixeira WHERE lixo IS NOT NULL
This will give more appropriate error of what you are missing.
Its probably a permission (grant select) issue.
Abhi

Trying to connect neo4j with c# and run a query

Im expirementing with databases and most recently specifically with the graph-database Neo4J. Im trying to connect Neo4j with C#, just as what I did with postgreSQL (see code)
class Sql_connection : DatabaseConnection
{
public string Server, Port, User_Id, Password, Database, Connstring;
public NpgsqlConnection SQLconnection;
public Sql_connection(string Server, string Port, string User_Id, string Password, string Database)
{
this.Server = Server;
this.Port = Port;
this.User_Id = User_Id;
this.Password = Password;
this.Database = Database;
this.Connstring = "Server="+this.Server+";Port="+this.Port+";User Id="+this.User_Id+";Password="+this.Password+";Database="+this.Database /* +";" */;
this.SQLconnection = new NpgsqlConnection(this.Connstring);
this.SQLconnection.Open();
}
public string InsertQuery(string INSERT_INTO, string VALUES)
{
NpgsqlCommand InsertCommand = new NpgsqlCommand();
InsertCommand.Connection = this.SQLconnection;
InsertCommand.CommandText = "insert into "+INSERT_INTO+" values "+VALUES;
InsertCommand.ExecuteNonQuery();
return "succes";
}
I already typed "Install-Package Neo4j.Driver-1.0.2" in the NuGetPackagemanager.
Besides that, I of course did some research myself, but I found multiple websites and github-repositories all saying something different, and I dont know what to believe/do anymore.
My two concrete questions are:
1: "How do you make a Neo4J-C# connection?"
2: "How do you run a query with this library/API"
I am aware of how graph-databases work and the syntax of Neo4j, so I understand the insertquery will not have insert into and values as key words.
Thanks in advance to everyone trying to help :D
Neo4j has good official documentation. Out of all sources the developers should be the most trustworthy. This is straight from their website and seems to work fine.
using Neo4j.Driver.V1;
using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("Username", "Password")))
using (var session = driver.Session()) {
sesion.Run("CREATE (a:Person {name:'Arthur', title:'King'})");
var result = session.Run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title");
foreach (var record in result)
Console.WriteLine($"{record["title"].As<string>()} {record["name"].As<string>()}");
}
Taken from here : https://neo4j.com/developer/dotnet/
Simply replace the localhost with your server ip (or localhost if you run it locally) and the username and password with your own username and password.
The developers have given multiple links to examples both documentation and Github source code. Hope this helps.

c# WCF service - How to get textbox input value

I'v created a "Login" windows form app with WCF,
How to send the input username and password to WCF and check if the username in SQL?
private void loginbt_Click(object sender, EventArgs e)
{
string username = textBox1.Text;
string password = textBox2.Text;
//check username and password are not empty
if (username.Trim().Length != 0 && password.Trim().Length != 0)
{
checkPassword.CustomerServiceClient service= new checkPassword.CustomerServiceClient();
var enterPassword = service.checkPassword(username, password);
//check input value here with WCF?
}
}
I'm getting Index was outside the bounds of the array. exception when I add string getUsername = enterPassword[0].name;. It looks like the WCF did not get the input value from textbox, in other words checkPassword(null, null).
public Customer[] checkPassword(string name, string password){
List<Customer> customers = new List<Customer>();
SqlConnection connection = new SqlConnection(
"Data Source = 11111; Initial Catalog = 1111;" +
"User ID = 1111; Password = 11111");
connection.Open();
SqlCommand command = new SqlCommand("select customerId, customerName, address, password, phone from Customer where customerName='"+name+"'", connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()){
Customer newCustomer = new Customer(reader.GetString(1), reader.GetString(3));
string correctPW = reader.GetString(3);
if (correctPW == password)
{
customers.Add(newCustomer);
}
}
reader.Close();
connection.Close();
return customers.ToArray();
}
sorry, I am really confuse with this question, hope you can understand my question, thanks for help.
It is not possible that the service call got executed as checkPassword(null, null) because you call Trim on username and password further up in the execution sequence. You would have received a NullReferenceException before the service call if both variables were null.
One red flag that I see is that you are testing the trimmed (whitespace truncated) versions of username and password when deciding to make the service call, but yet you go ahead and used the unadulterated versions when passing them as parameters to the service call. Could it be that the service is not behaving the way you think it should because there is whitespace in the parameters?
What you really need to do is verify the values of username and password just prior to calling to the service. Ask yourself, "Does my service respond correctly using the parameter values specified?" The problem may be with the service and not the caller. You are going to have to do some old fashioned debugging here. That is something we cannot do for you so take off those socks and shoes and get your feet wet!
As a side note, it appears that you are passing a password in plain text across the network. It is not terribly difficult (actually it could be quite easy) for a middle man to intercept this information. And along the same lines I can see that you are open to SQL injection attacks as well. Knowing that you are using parameterless inline SQL I could tell you my username is x' or 'a'='a and that would cause all rows from the Customer table to be returned. I do not know if that would necessarily cause a security breach in your cases, but I hope you at least can imagine the kinds of havoc this could cause. I only mention all of this because your WCF appears to be security related.
Fixed my problem.
It is because I use the input username to select data from sql, so when I input a not exist username, it will give a error.
Thanks all.

How to connect to Mysql using C#?

I'm just a beginner in C#. I'm using XAMPP server for MySQL database and Visual C# 2010. Then I have created a database named "testdb" in phpMyAdmin and a table named "login". I have inserted my username and password in the table. I'm doing a simple WinForm login where I made two text boxes for username and password and a button. I have my codes done and there's no compiler error. But I had troubled in one line. It says "Unable to connect to any of the specified MySQL hosts". I added MySql.Data to my references. I want to fetch the data in the database table when I'm going to log in. Then authorize the user or if not matched, it will prompt an error message.
Here is my code:
using MySql.Data.MySqlClient;
public bool Login(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=localhost;username…");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM login WHERE username='" +
username + "' AND password='" + password + "';");
cmd.Connection = con;
con.Open(); // This is the line producing the error.
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
*I hope for your your feedback. :)
Your immediate problem is probably either an incorrect connection string or the database server is not available. The connection string should be something like this
Server=localhost;Database=testdb;Uid=<username>;Pwd=<password>;
with <username> and <password> replaced with your actual values.
Besides that your code has several issues and you should definitely look into them if this is intended to become production code and probably even if this is just a toy project to learn something. The list is in particular order and may not be comprehensive.
Do not hard code your connection string. Instead move it to a configuration file.
Do not include plain text passwords in configuration files or source code. There are various solutions like windows authentication, certificates or passwords protected by the Windows Data Protection API.
Do not just dispose IDisposable instances by calling IDisposable.Dispose(). Instead use the using statement to release resources even in the case of exceptions.
Do not build SQL statements using string manipulation techniques. Instead use SqlParameter to prevent SQL injection attacks.
Do not store plain text passwords in a database. Instead at least store salted hashes of the passwords and use a slow hash function, not MD5 or a member of the SHA family.
You can use IDbCommand.ExecuteScalar to retrieve a scalar result and avoid using a data reader.
Comparing a boolean value with true or false is redundant and just adds noise to your code. Instead of if (reader.IsDBNull(0) == true) you can just use if (reader.IsDBNull(0)). The same holds for if (reader.Read() != false) what is equivalent to if (reader.Read() == true) and therefore also if (reader.Read()).
Using an O/R mapper like the Entity Framework is usually preferred over interacting with the database on the level of SQL commands.
Try modifying your ConnectionString accordingly to the Standard MySQL ConnectionString:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Source:
MySQL ConnectionStrings
You can also take a look at the following link, that shows how to connect to a MySQL database using C#:
Creating a Connector/Net Connection String (MYSQL)
Make it simple and sql injection free, and also don't forget to add MySql.Web
in your references since your using XAMPP
public bool Login(string username, string password)
{
DataTable dt = new DataTable();
string config = "server=....";
using (var con = new MySqlConnection { ConnectionString = config })
{
using (var command = new MySqlCommand { Connection = con })
{
con.Open();
command.CommandText = #"SELECT * FROM login WHERE username=#username AND password=#password";
command.Parameters.AddWithValue("#username", username);
command.Parameters.AddWithValue("#password", password);
dt.Load(command.ExecuteReader());
if (dt.Rows.Count > 0)
return true;
else
return false;
} // Close and Dispose command
} // Close and Dispose connection
}

Querying remote MySql server

I think I have a straight forward question. I'm writing a system that allows users from company A to single sign on to the system and for this I go back to the central database of users at company A and validate the user credentials passed to me.
Currently my implementation involves building up my query using a stringbuilder and then passing the string as command text. My question is; is there a nicer way of doing this. below is my code;
public User LoginSSO(string UserName, Int32 sectorCode)
{
using (OdbcConnection con = new OdbcConnection(ConfigurationManager.ConnectionStrings["ComapnyA"].ConnectionString))
{
con.Open();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Select mx.Id, mx.UserName, mx.firstname,mx.surname,mx.sectorCode,");
sb.AppendLine("mx.deleteFlag, dn.sectorGroupCode, dn.region, dn.district");
sb.AppendLine("from users mx");
sb.AppendLine("Inner Join sector dn on dn.sectorCode = mx.sectorCode");
sb.AppendLine("Where (mx.UserName = '{0}')");
string commandText = string.Format(sb.ToString(), UserName, sectorCode);
using (OdbcCommand comm = new OdbcCommand(commandText, con))
{
using (OdbcDataReader reader = comm.ExecuteReader())
{
if (reader.Read())
{
User user = new User();
user.Id = Convert.ToInt32(reader["Id"]);
user.Username = Convert.ToString(reader["UserName"]);
user.Firstname = Convert.ToString(reader["firstname"]);
user.Surname = Convert.ToString(reader["surname"]);
_dealerGroupCode = Convert.ToString(reader["sectorGroupCode"]);
_region = Convert.ToInt32(reader["region"]);
_district = Convert.ToInt32(reader["district"]);
_dealerCode = dealerCode;
_accessLevel = AccessLevel.Sector;
return user;
}
}
}
}
return null;
}
I don't like the fact that I am building up my sql which is ultimately a static script. Please note that I can't manipulate the remote server in any way or add any stored procedures to it. For the rest of the app I have been using LINQ but I'm assuming that isn't an option.
This is the most low-level way of querying a database with ADO.NET. Open connection, send command, read out results. You should however use parametrized queries instead of String.Format, since that will open up your program to SQL injection. Just consider what would happen if UserName has a ' character in it. The following would be much better:
string sql = #"Select mx.Id, mx.UserName, mx.firstname, mx.surname,
mx.sectorCode, mx.deleteFlag, dn.sectorGroupCode,
dn.region, dn.district
From users mx
Inner Join sector dn on dn.sectorCode = mx.sectorCode
Where (mx.UserName = ?)";
var command = new OleDbCommand(sql);
command.Parameters.AddWithValue(0, UserName);
If you want a higher level interface, look into DataSets/DataAdapters. They aren't as fancy as LINQ, but they'll give you an easy fill/update, and work with any database adapter. If you're using Visual Studio, you even get a visual designer that can generate Typed Datasets in drag-and-drop fashion that'll give you strong-typed accessors for all your data.
You might also want to look into the native MySql connector classes, instead of using ODBC.
You can use ‘sp_addlinkedserver’ system store procedure to link to the remote server server and then fire a query. following is the sample command.:
EXEC sp_addlinkedserver
#server = ‘SourceServer’
, #Srvproduct = ”
, #Provider = ‘SQLNCLI’
, #datasrc = ‘Remote SQL Server instance name’
I suggest you to please refer following link to know about how to run sql query on remote server http://ashishkhandelwal.arkutil.com/sql-server/sql-query-to-the-remote-sql-server/

Categories

Resources