Trouble querying SQL Server database via C# - c#

I have created a web form using a custom login control to access a local SQL Server database. The database contains a table named Employees with various info about the employee, however, the relevant columns for my question are EmployeeID (primary key), Username, and Password.
I am trying to query the database using the username and password entered in the login control to retrieve the EmployeeID. An exception is thrown when trying ExecuteScalar(). The exception states that 'Employees' is an invalid object name, so I suspect my problem is the connection string. I retrieved the connection string by viewing the properties of the database in SQL Server 2014 Management Studio, which is where I also created the db. Another guess is that authentication when connecting to the db. I'm not really sure though, so can someone help please?
string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Joshua\\AppData\\Local\\Microsoft\\VisualStudio\\SSDT\\SignProDatabase\\SignProDatabase.mdf;Integrated Security=True;Connect Timeout=30";
string query = "select EmployeeID from Employees where Username = 'user' and Password = 'pass'";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, connection);
try
{
object test = cmd.ExecuteScalar();
Console.WriteLine(test.ToString());
}
catch(Exception err)
{
Console.WriteLine("Exception Message: " + err);
Console.ReadLine();
}

As Martin mentioned in the comments, the account that is running the application will need access to the server and database, as well as select permission on the Employees table. Also, if the code provided is not just for example then for security reasons you shouldn't be storing the actual passwords in your database and you will want to validate the input to protect against SQL injection attacks.

Related

Oracle connection with port, service name, and database from C# (ORA-12514

I'm new to Oracle. Trying to connect C# windows app to an Oracle database but can't seem to establish a proper connection. Keep getting exception: "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor". I have to specify the port, service name, and database name in the connection string because the service id has access to multiple databases. I know that the values in the string are valid (valid server, valid serviceid, valid username, password, etc) because I have a third-party tool that is able to connect using the same parameters from a wizard. I've tried a lot of different ways to format the connection string but I always get the same 12514 error. In the code example, you'll see three formats (cxn, cxn2, and cxn3), I've tried each of them but get the same error.
string cxn = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyServerName)(PORT=MyPortNumber))" +
"(CONNECT_DATA=(SERVICE_NAME=MyServiceId)));User Id=MyUserName; Password=MyPassword;";
string cxn2 = "DATA SOURCE=MyServerName:MyPortNumber/MyUserName;" +
"PERSIST SECURITY INFO=True;USER ID=MyUserName; password=MyPassword; Pooling = False;";
string cxn3 = "DATA SOURCE=MyServerName:MyPortNumber/MyServiceId;" +
"PERSIST SECURITY INFO=True;USER ID=MyUserName; password=MyPassword; Pooling = False;";
using (OracleConnection conn = new OracleConnection(cxn3))
{
string sqlSelect = "SELECT * FROM PERSONS";
using (OracleDataAdapter da = new OracleDataAdapter(sqlSelect, conn))
{
var table = new DataTable();
da.Fill(table);
if (table.Rows.Count > 1)
Console.WriteLine("Successfully read oracle.");
}
}
Again, I've used MyServiceId in the third-party tool's wizard and I connect just fine and select my database. I'm using Oracle.ManagedDataAccess.Client. I consulted a number of articles online including Oracle's guidance in section "Getting Started with ODP.NET, Managed Driver". How can I get the driver to recognize the valid service id and then also accept the database name? Any guidance is appreciated. Thanks.
Well I wish I had a more definitive explanation but as it turns out the code from my original question works NOW using the connection string defined in variable "cxn". I ran it many times before with no success, so my only guess is that the DBA changed something or rebooted the server since initial configuration.

Sending authentication information to SQL Server isn't working (C#)

I already asked about a similar issue to this one but I've narrowed it down to my problem and I've been working on this for hours and unable to figure this out.
Basically, I have a visual studio wep application and I'm trying to use a login page and sql server database to validate user credentials. The user enters a string for username and password on the log-in screen which gets sent here on the code behind:
private bool ValidateUser(string userName, string passWord)
{
SqlConnection conn;
SqlCommand cmd;
string lookupPassword = null;
// Consult with your SQL Server administrator for an appropriate connection
// string to use to connect to your local SQL Server.
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["databaseConnect"].ConnectionString);
conn.Open();
// Create SqlCommand to select pwd field from users table given supplied userName.
cmd = new SqlCommand("Select Password from Users where User=#userName;", conn);
cmd.Parameters.Add("#userName", System.Data.SqlDbType.VarChar, 25);
cmd.Parameters["#userName"].Value = userName;
lookupPassword = (string)cmd.ExecuteScalar();
// If no password found, return false.
if (null == lookupPassword)
{
return false;
}
private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
(logs in)
}
The application is connected a table in a database, which currently holds one test item, as shown here: http://i.imgur.com/YFOQYKm.jpg
However, when I enter "test" as username and "password" as password, it doesn't accept the log-in.
I tried to include only the relevant parts of my code to make it more clear for anybody trying to answer the question but here's a few comments about my problem:
-When I set if (null == lookupPassword) to "return true" instead of "return false" the application allows logins. Which means lookupPassword is still null after "lookupPassword = (string)cmd.ExecuteScalar();"
-The application works fine when I change if(ValidateUser(txtUserName.Value,txtUserPass.Value)) to if(userName=test and passWord=password). So the problem is not with the actual act of logging into the application, it just isn't finding the SQL Server credentials to be true.
-"databaseConnect" is working elsewhere on the application, so that is not the issue.
-The application is not breaking when I submit the login credentials, it is simply not accepting them as correct.
Going off that, it seems to me that the problem comes from these four lines:
cmd = new SqlCommand("Select Password from Users where User=#userName;", conn);
cmd.Parameters.Add("#userName", System.Data.SqlDbType.VarChar, 25);
cmd.Parameters["#userName"].Value = userName;
lookupPassword = (string)cmd.ExecuteScalar();
Does anybody see where the problem might be for me? I'm very new to programming so please keep the answers as simple as possible please. Thank you in advance for any help. :)
This table design is using several reserved words in SQL Server. If you cannot modify this schema, you can update your query as follows:
SELECT [Password] FROM [Users] WHERE [User] = #Username
That being said, storing passwords in plaintext is a horrible security practice. Passwords should never be stored encrypted or as plaintext, they should be hashed using a salt to help avoid rainbow tables from cracking your password. I would look into the suggestion from #Richard regarding Rfc2898DeriveBytes. You can also search Google or Bing for using salt and SHA256.

Error connecting to SQL server through string, not recognising user name or password

the problem I am having is connecting to an account on my sql server (2005) from an ASP.NET application.
Ive tried using the default sa login and users ive created already also the setting of the sql management studio are set to mixed properties, I have the string connection in the webconfig as well but also doesnt work.
c# code
//string conStr = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
string conStr = #"server=JAMES-PC\SQLEXPRESS; database=projectDB; uid=james; password=password;";
string query = "SELECT [TaskID], [Task], [Start Date] AS Start_Date, [End Date] AS End_Date, [Priority], [Time Allowance] AS Time_Allowance, [Details], [Catagory] FROM [schedulerData0]";
SqlDataAdapter dataAdapt = new SqlDataAdapter(query, conStr);
DataTable table = new DataTable();
dataAdapt.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
The error message I receive is:
Login failed for user 'james'. The user is not associated with a trusted SQL Server connection.
Any help appreciated
James
Your SQL SERVER configured for Windows Only connections and you current windows user not associated as trusted. Try to configure your SQL SEREVR to accept Mixed Mode connections.
Try this,I'm not sure but hope it will work-
<connectionStrings>
<add name ="conStr" connectionString ="Initial Catalog = projectDB;
Data Source =JAMES-PC\SQLEXPRESS; User Id=james;Password=password;"/>
</connectionStrings>
try mapping projectDB to user:james. open SQL Server Management Studio, select Security - Logins, double click user:james, select page:User Mapping, check projectDB.
Please try the following format If It is Sql Server user mode,
ConStr = "Server=JAMES-PC\SQLEXPRESS;Database=projectDB;User Id=james;
Password=password;"
if you are trying to connect using windows,
then you must provide Trusted Connection = true

Connecting to a database server

There is a database server at IP address 192.168.1.11. There are several databases on that server. It has authentication, like user : System and pass : 123123 .
Now I want to connect to this server only, not any particular database, and then get a list of databases available on that server.
I know the normal procedure of connecting to a database with SqlConnection. But I'm wondering how I could just get connected to the server and get the list of the databases on that server.
I am using Visual Studio 2010 and SQL Server 2008-
run this query on a Method
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4
or by
String connString ="Data Source=localhost;User ID=username;Password=passwrd;";
using (SqlConnection sqlConn = new SqlConnection(connString))
{
sqlConn.Open();
DataTable tblDatabases = sqlConn.GetSchema("Databases");
sqlConn.Close();
DataTable td = tblDatabases.Select("dbid>6").CopyToDataTable();
}

Connection String in c#

I am trying to connect to a database with my connection string and recieve the following error when trying to connect to the database. For intergrated Security I user SSID so I don't have to enter a username and password. Also, the database resides on the same machine and was created inside VS2010. I can connect to the db without a problem using the SqlDataSource, but I am looking to start writing my own connection strings.
protected void btnUpdate_Click(object sender, EventArgs e)
{
string source = "server=(local)" + "integrated security=SSPI;" + "Connect Timeout=30; " + "database=Name";
SqlConnection conn = new SqlConnection(source);
conn.Open();
conn.Close();
}
The Error I get is this:
A network-related or instance-specific
error occurred while establishing a
connection to SQL Server. The server
was not found or was not accessible.
Verify that the instance name is
correct and that SQL Server is
configured to allow remote
connections. (provider: Named Pipes
Provider, error: 40 - Could not open a
connection to SQL Server)
Try the following syntax as connection string:
string source = "Data Source=Server Address;Initial Catalog=Database Name;Integrated Security=SSPI;";
Where Server Address should be localhost or .\SQLExpress
Hope thats correct. I have'nt installed a vs for testing
You are missing a ; after the server name.
Why are you concatenating all the parts of the connection string if they do not change? It makes it more difficult to read.
Try this:
string source = "server=(local);integrated security=SSPI;ConnectTimeout=30;database=Name";
You need a semicolon after (local)
string source = "server=(local);" + "integrated security=SSPI
I notice you tagged the question with asp.net
by default asp.net runs under a system account, when you are using integrated security then that account is trying to access your database, it probably doesn't have permission.
Take a look here for some information.
I would recommend you to use the SqlConnectionStringBuilder: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder(v=VS.100).aspx
That will probably make it easier.
To connect to SQL Server from C#.NET, you need to create a connection string such as below:
private SqlConnection connection;
private string connectionString =
#"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123";
connection = new SqlConnection( connectionString );
Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:
SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = #Cid",
connection);
The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.
Next to execute the SQL queries in the database, you use the following methods:
ExecuteReader - to execute SELECT queries
ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.
This is a very short description of how to connect to SQL Server database from C# and execute SQL queries in the database.
For details about the connection string, the methods and their parameters check the following link: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html )
Here you will also find details about how to pass parameters to the SQL queries as well as calling stored procedures and much more.

Categories