Can't access SQL database - c#

I'm working on a project and now I had to switch account on the computer from local to a account on a domain and thus the windows authentication changed. So I made a new login and it works on the account that is on the domain, but when I change the connection string from
Data Source=productie3;
to
Data Source='MEVO/productie3';
//tried with either \ or /
//direct connection (using SQL Server Management Studio) to the database using the
//windows authentication works fine
I tried it without the single quotes as well,
But it still doesn't work.
I've used this to allow remove access
USE [DB name];
GO
EXEC sp_configure 'remote access', 0 ;
GO
RECONFIGURE ;
GO
But it still won't allow it to connect, if anyone knows what I'm doing wrong please tell me. I'm using Microsoft SQL Server Management Studio for the database.

Try connecting with a backslash. You are putting in a forward slash.
Data Source='MEVO\productie3';

Related

VS C# Sql Client unable to connect to SQL Server, uses Windows auth instead of SQL Server auth

I have two desktop clients with VS 2017. I inherited a C# .NET app that connects to a SQL Server in the next room. We generally use SQL Server authentication (as opposed to Windows authentication) when we perform SQL queries.
I use a connection string that looks something like this ...
"Data Source=DR101; User Id = DR_DATA; Password = CD7504st; Integrated Security=SSPI; TransparentNetworkIPResolution=False"
... which works like a charm from the first desktop. From the second desktop it always fails to access the database, giving an error indicating a Windows login failure ...
... threw an exception.
System.Data.SqlClient.SqlException: Login failed for user 'SDAR\SdarAutoSvc'
I have compared everything I can think of between these two systems. As far as I can ascertain, they are identical in most every way ... both use the same Visual Studio (Help > About, and compared the long list of module versions. Identical on both systems), the same System.Data.dll module, the same App.config, C# source code, input data, etc.
The failing system only fails via this visual studio app - i.e., I can reach the database server from that desktop via SMSS, using the SQL Server credentials (not Windows authentication).
I am out of ideas as to how this second machine might be unable to access the database, and why it apparently uses Windows auth rather than the sql userId/password from the connection string.
If you want SQL server Authentication then remove Integrated Security=SSPI; from the connection string.
Try with this connection string -
"Data Source=DR101; User Id = DR_DATA; Password = CD7504st; TransparentNetworkIPResolution=False"

How to avoid connections against empty/null database by Entity Framework

We use entity framework to read from an existing database.
This is a simplified version of our code.
using (my context context = new mycontext())
{
if(context.Database.Connection.State == System.Data.ConnectionState.Closed)
{
_logger.Info(" Opening the connection to the database");
context.Database.Connection.Open();
}
context.Configuration.LazyLoadingEnabled = false;
IQueryable<mymodel> people;
people = context.People.OrderBy(x => x.Firstname);
_lstContacts = people.ToList();
if (context.Database.Connection.State != System.Data.ConnectionState.Closed)
{
context.Database.Connection.Close();
context.Database.Connection.Dispose();
_logger.Info(" Connection to the database Closed");
}
}
It works 100% of the time, but...
On our UAT environment we can see failed connections to the Microsoft SQL server with the error:
Login failed for user "my user". Reason: Failed to open the explicitly
specified database "null". Client my IP.
For us, these are ghost connections because at the time when we see the errors in the SQL server, our code is not executed.
Initially we didn't close and open the connection explicitly, we just added it trying to control when EF open and closes the connection, but it didn't fix the issue.
Our connection string is using the following format:
<add name="MYCN" connectionString="metadata=res://*/CVs.Cvs.csdl|res://*/CVs.Cvs.ssdl|res://*/CVs.Cvs.msl;provider=System.Data.SqlClient;provider connection string="data source=myserver\;initial catalog=mydatabase;Integrated Security=;User ID=myuser;Password=XXXXXXX;MultipleActiveResultSets=True;App=EntityFramework"/>
As you can see, we are specifying the database in the connection string and our user only have access to our database, so we understand the error when EF doesn't include the database in the connection string, but we don't understand why it's trying to perform these connections.
We know the connections are coming from our application, because we are the only one using that specific user, the IP is the IP of our server, and because the logs in SQL server tell us that the application is "EntityFramewrok"
I didn't personally see the error before, but researched for you and seen that many people suffered from the same problem discussed here: https://blogs.msdn.microsoft.com/sql_protocols/2006/02/21/understanding-login-failed-error-18456-error-messages-in-sql-server-2005/
I read all the messages in the website specified, and here are the solutions offered and at least one other user confirmed that it worked. You might not use 2005 as you didn't specify your version in your question, some solutions I believe will still work for you. Try the list below.
Solution list:
1) Please check the state number of this error and search solution by the state number in addition to the message, might give your more accurate solution proposals. Most common states are listed:
All state-error descriptions you can find here: https://sqlblog.org/2011/01/14/troubleshooting-error-18456
2) Make sure the username and password are correct.
3)
Logon to SQL Server using windows authentication.
Right click in the query window that appears and select "Open Server in Object Explorer"
Go to object explorer and open the "Security" folder and then the "Logins" folder.
Double-click the "sa" user and change the password. Also, like another user mentioned above, untick the "Enforce Password Policy" in
addition to resetting the password.
4) Try to change the password and turn off the policy, and try with new password.
exec sp_password #new = ‘sqlpassword’, #loginame = ‘sa’
alter login sa
with password = ‘sqlpassword’ unlock,
check_policy = off,
check_expiration = off
5) Run your application/browser and SSMS (if you work on it) in administration mode.
6)
Open Windows Services
Configure Microsoft Single Sign-on Service to use the proper account
Open Central Administration >> Operations >> Manage settings for single sign-on
Configure properties to use the same account used for Microsoft ‘Single Sign-on Service
7) Go to Sql server configuration manager and Enable TCP/IP and named pipes
8)
go to sql server
right click on server, choose properties
click on security
on server authentication, enable SQL Server authentication
These might help:
https://www.wikitechy.com/errors-and-fixes/sql/login-failed-error-18456-severity-14-state-38-reason-failed-to-open-the-explicitly-specified-database
https://dba.stackexchange.com/questions/90445/login-failed-for-user-error-18456-severity-14-state-38
I think this is just an access issue for myuser in the UAT environment. Just make sure myuser has access in the UAT environment for UAT database and you should be good.

C# creating a database programmatically with SMO

I am trying to create a database, but once created, I cannot connect to it.
The server is Microsoft SQL Server 2008 and using .Net 4.5. We're creating the database with SMO, but we're usually using Dapper to connect and query the database.
This is the code I have so far, which works :
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connectionString);
Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(con));
var database = new Microsoft.SqlServer.Management.Smo.Database(srv, dbName);
database.Create(false);
database.Roles["db_datareader"].AddMember(???);
database.Roles["db_datawriter"].AddMember(???);
database.Roles["db_backupoperator"].AddMember(???);
srv.Refresh();
Noce the ??? ? I have tried
System.Environment.UserDomainName + "\\" + System.Environment.UserName
and
System.Environment.UserName
but it fails (update) with the error Add member failed for DatabaseRole 'db_datareader'. with both values.
The problem is that when I create the database, I cannot coonect to it for some reason (using Dapper), from the same program. (update) I get the error message : Cannot open database \"<database_name>\" requested by the login. The login failed.\r\nLogin failed for user '<domain>\\<username>' (where <database_name> is the database name, <domain> my logon domain, and <username> my Windows logon).
Am I missing something? Am I doing th right thing? I've tried searching the web, but it seems no one creates database this way. The methods are there, it should work, no?
** Update **
If I comment the database.Roles["..."].AddMember(...) lines, and I add a break point at srv.Refresh(), resuming the program from there solves everything.
Why a break point solves everything? I can't just break the program in production... nor break the program when creating the database everytime.
It sounds like the Dapper connection issue is a problem with SQL Server doing some of the SMO operations asynchronously. In all likelihood, the new Database is not ready for other users/connections immediately, but requires some small time for SQL Server to prepare it. In "human-time" (in SSMS, or a Breakpoint) this isn't noticeable, but "program-time" it too fast, so you probably need to give it a pause.
This may also be the problem with the Role's AddMember, but there a a number of things that could be wrong here, and we do not have enough information to tell. (specifically, does AddMember work later on? and are the strings being passed correct or not?)
This is happening because you've created the user, but no login for that user. Though I don't know the exact syntax, you're going to have to create a Login. You'll want to set its LoginType to LoginType.WindowsUser. Further, you'll likely need to set the WindowsLoginAccessType to WindowsLoginAccessType.Grant and you'll need to set the Credential by building one, probably a NetworkCredential with the user name you want.
To put a visual on this, the Login is under the Security node for the Server in Management Studio whereas the User is under the Security node for the Database. Both need to exist for access to the SQL Server.

Cannot Connect to Sql Server Enterprise On Local Machine

I have SQL Server 2008 Enterprise edition, and C# code that should connect to said server. It's a local server on my computer and when I try to log on I get this error:
Cannot open database "Clients" requested by the login, the login failed.
Login failed for user crmsys.
This user has the right permissions, this server is even configured to allow remote connections and through the management studio I can access as this user.
Here's my connection string:
Data Source=./; Initial Catalog=Clients;user ID=crmsys;Password= Password;
In your snippet of configuration settings in your initial post there is a space between the equals sign and the first character of the password - is this correct?
i'm not sure "./" is a valid datasource. I always use "localhost" or ". \ [instancename]"
just an idea.
Make sure you dont have a firewall blocking you; the windows one does by default... If thats all ok check remote connections are enabled: From management studio Check Properties, Connections, and check "Allow Remote Connections To This Server" is checked.
If that is checked then restart SQL Server and try again; if it still fails check that TCP/IP is enabled and the settings using the Configuration Manager.
Are you sure the crmsys user has permission to connect to the database?
If you right-click the "Clients" database entry in SSMS, then go to "Properties" -> "Permissions", then select the "crmsys" user from the "Users or roles" pane, and then click the "Effective" tab, can you confirm that the "CONNECT" permission is there?
Edit: it should look like the image below:
alt text http://img42.imageshack.us/img42/4696/ssms.png
Have you tried Server=.\sqlexpress;Database=Clients;Uid=crmsys;Password=Password;Integrated Security=false
Solved it!!!!!! that was very weird but guess it turned out to be a conflict in the db properties, it's mixed out with the previues user which was crmsys(on the first computer) and when i restored it into my computer i made allready a user name crmsys - delete the user from the DB, deleted the Login crmsys, restored it and then opened a new user with the same permissions, and that it! Thanks you all for helping me figuring it out!

Error connecting to Oracle from Visual Studio

I am not able to connect to Oracle using connection string and the correct password. I've tried the same parameters in SQL developer and sqlplus(commandline) and they are working. I even tried changing the password but no use.
Any ideas what might be wrong or where should I start looking?
The exact Oracle error is :
invalid username/password password, logon denied
and after trying a few times account is getting locked with
the account is locked
When I've run into this, it has ALWAYS been an issue with my connect string.
What is your connect string? It should be something like "User Id=[ID]; Password=[PWD]; Data Source=[DB]"
Of course, you'd replace [ID], [PWD] and [DB] as appropriate.
Is it just your computer that exhibits the problem, or are others seeing it as well?
Can you test your connection in the ODBC Data Source Administrator? Does that work?
Try to install the Oracle Developer Tools for Visual Studio. It's free but you need to register, also free.
You need to unlock the account.
(From above referenced site)
SQL> ALTER USER username ACCOUNT LOCK;
SQL> ALTER USER username ACCOUNT UNLOCK;
Actually the problem was with cache on the computer. Even though I am giving "server='correctdb'" visual studio was taking "server='olddb'" as input and hence I am not able to connect. Pathetic but that's what happened.

Categories

Resources