Cannot connect to SQL Server using SqlClient in a desktop application - c#

Connecting to SQL Server with a SQL username and password is no problem at all.
These scenarios work just fine:
from C# code using SqlClient in ASP.NET / MVC
with ssms
with Visual Studio Connection Properties Wizard
For example, this works in an MVC project:
new SqlConnection("Server=DB1;Database=testdb;User Id=testuser;Password=testuser1;").Open();
But this identical code fails when run in a desktop application project. It causes the following inner exception error:
user name or password is incorrect
(yes there is a space between user and name)
I've tried:
making sure the protocols are right in SQL Config Manager.
opening up ports in the firewall on client and server.
connecting to another database to see if it's the database and not the client.
the NuGet version of SqlClient.
restarting the dev machine and the server.
ensured the Browser SQL service is running.
ensured the main SQL service is set to automatic and is running.
SqlClient, OLEDB, and ODBC along with appropriate connection strings.
Storing the username and password in a separate credentials object.
Specifying Integrated Security=False in the connection string
But still, nothing.
Why can I connect to SQL Server from everything except from code running in a desktop .NET application? Is something along the way stripping my password out before the connection happens?

Let's try :
data source=DB1;initial catalog=testdb;persist security info=True;user id=testuser;password=testuser1;
User must be a SQL user.

Related

Login failed for user 'sa' in ASP.NET with SQL Server 2019

I am trying to connect my .NET project to SQL Server developer edition 2019 (named instance), but it always throw the error:
Login failed for user 'sa'.
It however connects perfectly through SSMS without any issues.
I tried all possible things as suggested over internet but could not make my website run, is it actually the named instance which causes this issue, or it's issue at large.
I am able to connect my project if i connect to my database located on the remote server. but the one on my local machine just does not works.
Here's how my connection string looks like
server=[machine]\\[instance]; Integrated Security=SSPI; initial catalog=[database];Connection Timeout=1000
I also tried the same with SQL Server authentication
server=[machine]\\[instance]; uid=sa; pwd=[password]; initial catalog=[database];Connection Timeout=1000
None of the above worked out.
Ok, SSMS can connect using direct.
However, from asp.net, you in most cases have to turn on networking.
For reasons of secuirty, by default, your local instance of SQL server express has this feature turned off by default.
so, you need to do two things - and this was NOT required with older versions of sql server, but for recent versions - starting around 2012, you need to:
Turn on the browser service. This "translates" the sql "instance" to your IP address. (on startup, sql server assigns a IP address to that instance, but it will NOT be the same IP as your computer). But, the NAT translator thus has to be running.
That IP translator? It called the SQL browser service, and as noted, you need to have that running now, where as in the past you did not. That is this setting - launch the sql configuration, and you see this:
So, make sure the SQL Server Browser service is running - it is NOW required and as noted was not in the past.
Next up:
You need to turn on networking for SQL server. SSMS (sql studio) is able to connect using memory pipes - applications using the sql server provider in .net cannot!!!
So, once you ensured and checked the above browser service is running?
Then click on SQL server Networking Configuration, and turn on network connections (again, they are not turned on by default). That is this:
Now, after doing above, you probably should re-start sql server, and then the browser service. (just right click on sql server again, and choose this:
So, while SQL studio can connect using shared memory, .net and asp.net sites can't.
So, start the sql browser service - it is required to "resolve" the instance of sql server. in most cases, that will be SQLEXPRESS.
And consider using the built in connection builder in Visual Studio - it will not only build the connection string for you, but will also test the connection - and this can be done long before you even run any code.

SqlServer2012-Error 40-Could not open a connection in SQL Server

I know this is an answered question , however I have tried all the steps mentioned
like:
In SQL Configuration manager have Enabled TCP/IP,Shared Memory and Named Pipes.
Restarted the SQLSERVER
In Services.msc I have restarted SQLSERVER and SQL Server Agent
Added port 1433 in firewall's Inbound rule
Restarted PC number of times
Even Registered Local Server in SQL Server Management tools
I can open SQL Server Management tools
It was working fine and now its not. However I am able to login , then I cannot do any work on it, it gives me an error as :
Tried all the steps mentioned in the accepted answer HERE
I have some other application accessing same SQL Server and they are working fine.
My Connection string :
public SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Database=RMS_EXPRESS;Integrated Security=True;User Id=sa;Password=xxxxxx");
I also tried with the following connection string
Data Source=.;Database=RMS_TS1;Integrated Security=False;User Id=sa;Password=xxxxxxx
It gave me an error. "Login Failed for User 'sa'"
My application and Database are on the same PC
So , please help.
Thanks
You can not setup in your connection string both Integrated Security=true and User Id=sa;Password=xxxxxx
Integrated Security = true means it is using windows credentials (of the user the application is running into). A database connection cannot use both windows AND SQL Server authentication.
You should either:
Use Integrated Security=true and do not specify User Id nor password. This would use windows authentication.
Use Integrated Security=false or remove it althogether and specify both User Id and Password. This would use SQL Server user/password authentication.
Besides that, there was an adittional problem, originally you put Data Source=.\SQLEXPRESS but had to access default instance via Data Source=. which caused that error.
Allow Remote Connections enabled under Connections in SQL Server Properties.

Why can't I connect to the SQL Server database when I create setup file in Visual studio?

I create application using C# windows forms which uses local SQL Server database server to store / read data using this connection string:
SqlConnection cn = new SqlConnection("Data Source=localhost;Initial Catalog=mydb;Integrated Security=True");
After that I created a setup file (exe) then I installed the setup file in same PC and the application works well and can read data from the SQL Server database.
Now the problem came when I went to another PC I installed SQL Server and I manually attached the same database (mydb) and installed my application and it did not work. The error is shown in the screenshot:
I have different SQL Server name in the other PC but I specified in the connection string that the SQL Server is Localhost so I don't know why it didn't work. Please help me how to fix this error. Thank you
Make sure Sql Server is set to allow Tcp/Ip connections and that it's set to allow integrated security logins. Then, make sure the user on that machine is granted the correct access to the database. You may have better luck using Sql authentication over Windows Authentication here, if you want to be able to distribute this application and have it "just work".
Finally, if Sql Server here is meant to be a simple datastore for a typical local desktop application, it's probably overkill. Full Sql Server (including Express Edition) is a server engine. It works best when it's the only thing running on the machine and can use up all of the resources on the machine in order to cache data and handle requests from many remote machines. If you just want a local data store for a typical desktop application, an in-process engine like Sql Server LocalDb, Sql Server Compact Edition, Sqlite, or even MS Access would be a much more appropriate choice.
You need to set up Windows authentication for the user that's logged in on the other computer. Because you are using Integrated Security, it will attempt to connect to SQL Server using the windows login of the current user. This will be a different login on different computers, so the SQL Server on the other computer needs to have that user added.
You need to start SQL Server Browser Service. It lets your app connects to SQL Server:
SQL Server Browser listens for incoming requests for Microsoft SQL
Server resources and provides information about SQL Server instances
installed on the computer.
To enable it:
In SQL Server Configuration Manager, go to Properties => Service tab => Start Mode = Automatic.
Or
This computer => Manage => Services and Applications => Services => SQL Server Broswer
Note: You need a sql specific user for connect to it, you can not go with Integrated Security for every machine.
Create a Sql Server user and allow it to access the Database:
--//Creates the login AbolrousHazem with password '340$Uuxwp7Mcxo7Khy'.
CREATE LOGIN AbolrousHazem
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
GO
--//Creates a database user for the login created above.
CREATE USER AbolrousHazem FOR LOGIN AbolrousHazem;
GO
Reference

ASP.NET SqlException when publishing in IIS Web Server

I've just start working on an ASP.NET Web Application in Visual Studio 2015 and SQL Server 2014. Somewhere, I need to connect to my local database and I use this:
ConnStr = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=my_db;Integrated Security=True";
It works fine when I run the application through VS in my browser. I can access the db and do whatever I want to do. But, when I publish my application in IIS Web Server, and then I open it in browser, it still works OK until I have to access the db. At that moment it throws SqlException:
System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. .
Maybe it is a server name problem and I should use an IP and a Port instead of that name, but I'm not sure because I don't have experience on this.
You are correct: You should use server name and/or IP in your connection string.
Using something like "local" or "localhost" means that your code is not portable. Another option would be to store your connection strings in two separate config files - one for your local copy (for development and troubleshooting) and one for your server (for portability). I have two config files in my solutions:
Web.config
WebServer.config
Then, when I deploy to the server, I just delete Web.config and rename WebServer.config to Web.config. It's totally portable and you'll never have connection string troubles again!
Also noteworthy: you're not including credentials in your connection string, which means that you're using windows authentication when connecting to SQL server. When debugging through visual studio, the application will run as you - and if you have the needed permissions, it will work. However, when running in IIS, it won't be running as you (at least, it SHOULDN'T be) - so you could run into issues there, as well.
EDIT
This link might be useful for you: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
Your connection string should look like this:
Data Source=192.168.1.10,1433;Initial Catalog=YourDatabaseName;User ID=SqlUserName;Password=SqlPassword;Connection Timeout=60; Max Pool Size=3000;
(you can set max pool size and connection timeout to whatever you want - or omit them entirely.
Also, regarding your windows issues - you need to make sure that the windows account IIS is using has permissions to traverse your network and reach your SQL Server instance. That said, I suggest that you use a SQL account instead of windows authentication.
Since you are using integrated security in connection string you will have to modify the Identity of App pool under which your application is running.
The Identity will be your windows username and password.
To change the username and password you need to go the advance settings of the app pool and process model you can see identity where you can add your windows credentials
Hope this helps
There are two problems in you connection string:
"Integrated Security" means you are using the native windows system for authentication. Similar to opening SSMS on the database using your Windows password. IIS is now trying to connect to the database, and connection string is telling to use the process that IIS is running under.
You can create a non-windows user in SQL Server and put the credentials into the connection string. Or you can grant the IIS user DB privileges. Or you can a lot different things here, but theses are the easiest to get you moving.
THe second problem in the connection string is the data source. Is there SQL Server on you local machine? If so that's why it's not working. Try to run your app in VS but against the remote SQL Server. That should be your next step.
The problem was that I thought that SQL Server was installed automatically with VS or at least with SQL Server Management Studio. BUT NO. So, as far as I understand, till know I have not worked with a real SQL Server. When I checked SQL Server Configuration Manager there were nothing running at SQL Server Services and so I realized that I was missing something.
Then, I installed SQL Server Express and build my db there. Now it is working fine even when I publish it. The connection string is
Data Source=.\\SQLEXPRESS;Initial Catalog=my_db;User ID=username;Password=pass
It can also be:
Data Source=localhost\\SQLEXPRESS;Initial Catalog=my_db;User ID=username;Password=pass

Connecting to SQL from C#

I have built a C# Project with SQL Server database
The connection string is
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\GadoLab\GadoLab.mdf;Integrated Security=True;Connect Timeout=30
I have put it on another computer for testing yesterday with SQL Express installed and put the program on the specified path as connection string but the program when i open it tells me that it can't connect to the database.
I also noticed that the SQL agent service isn't running and I can`t start it
what's the solution please?
The SQL Authentication mode is windows type
Few reasons of connection failures:
1. Wrong Connection String.
2. Lack of database existance.(Database does not exists)
3. Login Problems to database. (Wrong ID and password to database authentication)
4. Database is present on remote server and server is turned off.
There can be many more, but which one to apply in your case depends upon your code and exact situation of database.

Categories

Resources