How to change SQL Server 2005 from Windows Authentication to SQL Authentication? - c#

I have installed SQL Server 2005 in Windows Authentication, now I want to change it to SQL Authentication.
However, I cannot reinstall SQL SERVER and Management again, because it will lose the data in it.
Also I want to know what changes do I need to make in my Connection class to open connection, as my current is
public SqlConnection con= new sqlConnection("server=.\\SQLEXPRESS;database=Restaurant;integrated security=sspi");
Just need to ask one more thing, I can see my database in WIndows Auth and in SQL auth, so how can i change, so that any other user need to login before it peeps into my database. thanks

Using SQL Server Management Studio
*To change security authentication mode*
In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties.
On the Security page, under Server authentication, select the new server authentication mode, and then click OK.
In the SQL Server Management Studio dialog box, click OK to acknowledge the requirement to restart SQL Server.
In Object Explorer, right-click your server, and then click Restart. If SQL Server Agent is running, it must also be restarted.
To enable the sa login
In Object Explorer, expand Security, expand Logins, right-click sa, and then click Properties.
On the General page, you might have to create and confirm a password for the login.
On the Status page, in the Login section, click Enabled, and then click OK.
Using Transact-SQL
To enable the sa login
In Object Explorer, connect to an instance of Database Engine.
On the Standard bar, click New Query.
Copy and paste the following example into the query window and click Execute. The following example enables the sa login and sets a new password.
ALTER LOGIN sa ENABLE ;
GO
ALTER LOGIN sa WITH PASSWORD = '<enterStrongPasswordHere>' ;
GO
You can pass below sample(change appropriate UID & PWD) connection string in your connection object
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

To use SQL Server authentication, change the line:
public SqlConnection con= new sqlConnection("server=.\\SQLEXPRESS;database=Restaurant;integrated security=sspi");
to
public SqlConnection con= new sqlConnection("server=.\\SQLEXPRESS;database=Restaurant;user id=#USERID#;password=#PASSWORD#;Trusted_Connection=False");
Where "#USERID#" and #PASSWORD# are the specific User ID and Password respectively

To change the server security type:
You just need open SQL Server Management Object Explorer, right click the server, go in Properties, Security page, under server authentication, select the mode you want.
To modify the connection string:
1. You need to have a SQL user first. Still in the SQL Server Management Object Explorer, right click on user which under Security node, click new, then you can create one.
2. add the "User ID" and "Password" segment to the connection string.

Related

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# Connection String Without Windows Authentication Mode

I tried a lot but couldn't solve this problem. I want just my connection sql in c# by sql server authentication mode. I don't want windows authentication. When I enable windows authentication mode then my application does not work. What can I do?
This my connection string:
SqlConnection con = new SqlConnection(#"Data Source=myservername;Initial Catalog=mydatabesename;User Id=myuserId; Password=mypassword;Integrated Security=True");
If I change my password in code it works. Also when I delete Integrated security=true then shows me the following error:
Login failed for user
Did you enable the mixed mode authentication?
Did you grant to the user the access to the DB?
you can do it using SQL Server Management Studio (SSMS)
Did you restart SQL services after changing the mixed mode authentication?
Some of the server level properties takes only after a SQL restart , one such is authentication modes.
Start - > View Local Services -> SQL Server(SQLEXPRESS) > restart it
OK guys ı solved when ı add new login also tick the sysadmin new login in sql server and use it on conenction string in c# ı think this error by the user ıd 'sa' ı change new user name and password then it works thnks all people who try help me
You just need to edit your connection string to include the user name and password as below:
Scaffold-DbContext
"Server=DatabaseServer;Database=DbName;Trusted_Connection=false; User Id=ServeruserName; Password=ServerPassword;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DB

Connection string method wrong. Login failed for user

I have a connection string:
public static string str = "Data Source=SAI-7FD4677573D\\SQLEXPRESS;Integrated Security=True;Initial Catalog=Libary;";
But getting an error:
Cannot open database "Libary" requested by the login. The login failed.
Login failed for user 'SAI-7FD4677573D\Administrator'.
How can I write a connection string?
public static string str = "Data Source=SAI-7FD4677573D\\SQLEXPRESS;Integrated Security=False;User Id=SAI-7FD4677573D\Administrator;Initial Catalog=Libary;";
Please help what should I try?
It might be a typo. shouldn't be Library instead of Libary?
SQL Server can support two kinds of user authentication:
Windows based authentication & user/password authentication.
* Windows based authentication (also called "Integrated security)) is using your Windows login as medium of athentication. In this case you shouldn't proveide "User Id" and "Password" fields in the connection string and the "Integrated Security" param must be set to "true".
* Username/Password based. If you want to use explicitely defined username & password to access SQL Server database, "User Id" and "Password" fields in the connection string have to be specified and the "Integrated Security" param must be set to "false".
Bottom line - Your connection string contains both "Integrated security=true" and "User Id" param provided, which is an error. In case you need Windows authentication - remove User Id, otherwise add "Password" param and set "Integrated security" to false
Based on your data source, you seem to be using SQL Server Express. What you will need to do in order to use integrated security is to use SQL Server Management Studio to setup a login for your Windows user account and then create a "user" account for that login on your database.
What user account did you use to install SQL Server Express on your computer? It was probably a local administrator. So, log off, and log back on as that local administrator (or any local administrator or user who is in the "Administrators" group on your PC), and run SQL Server Management Studio (alternatively, you could hold down the shift key, right-click on SQL Server Management Studio, and select "Run as different user", and then enter your local administrator account). Then go to the "Security" > "Logins" section in "Object Explorer", right-click and select "New Login", then click "Search" and enter the local user account.
Next, select "User Mapping" under "Select a page" on the left-hand side, and put a checkmark next to your database in the list. In the database role membership below that, you can configure the base roles that your user will have, if desired.

How to get the connection String from a database

I have created a database with SQL Server Management Studio, I would like to now use it in my C# application. I need the connection string?
Where can I find the connection string, and where is my database stored?
Do I have to publish it or something like that, or is it in my documents somewhere?
using (var conn = new SqlConnection("your connection string to the database"))
How do I obtain the connection string? Where can I find the connection string to copy paste into the above section?
How to I publish my database so that Visual Studio can pick it up? Then I can just pull the connection string of there?
The easiest way to get the connection string is using the "Server Explorer" window in Visual Studio (menu View, Server Explorer) and connect to the server from that window.
Then you can see the connection string in the properties of the connected server (choose the connection and press F4 or Alt+Enter or choose Properties on the right click menu).
Advanced connection string settings: when creating the connection, you can modify any of the advanced connection string options, like MARS, resiliency, timeot, pooling configuration, etc. by clicking on the "Advanced..." button on the bottom of the "Add connection" dialog. You can access this dialog later by right clicking the Data Connection, and choosing "Modify connection...". The available advanced options vary by server type.
If you create the database using SQL Server Management Studio, the database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.
I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express / localDB installed on your machine for this to work.
A very simple way to retrieve a connection string, is to create a text file, change the extension from .txt to .udl.
Double-clicking the .udl file will open the Data Link Properties wizard.
Configure and test the connection to your database server.
Close the wizard and open the .udl file with the text editor of your choice and simply copy the connection string (without the Provider=<driver>part) to use it in your C# application.
sample udl file content
[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;Initial File Name="";Server SPN=""
what you need to copy from it
Integrated Security=SSPI;Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;
If you want to specify username and password you can adopt from other answers.
Tutorial: https://teusje.wordpress.com/2012/02/21/how-to-test-an-sql-server-connection/
Open SQL Server Management Studio and run following query. You will get connection string:
select
'data source=' + ##servername +
';initial catalog=' + db_name() +
case type_desc
when 'WINDOWS_LOGIN'
then ';trusted_connection=true'
else
';user id=' + suser_name() + ';password=<<YourPassword>>'
end
as ConnectionString
from sys.server_principals
where name = suser_name()
If you have installed and setup MS SQL Server and Management Studio, go to Visual Studio (Visual Studio not SQL Server Management Studio).
1] In Visual Studio go to Tools -> Connect to Database.
2] Under Server Name Select your Database Server Name (Let the list Populate if its taking time).
3] Under Connect to a Database, Select Select or enter a database name.
4] Select your Database from Dropdown.
5] After selecting Database try Test Connection.
6] If Test Connection Succeeds, Click Ok.
7] In Visual Studio go to View -> Server Explorer.
8] In Server Explorer window, Under Data Connections Select your Database. Right Click your Database -> Click Properties.
9] In Properties window you will see your Connection String.
On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
on myServerAddress, write the name of your installed instance (by default it's .\SQLEXPRESS for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.
edit
You will need to omit username and password for windows authentication and add Integrated Security=SSPI.
My solution was to use excel (2010).
In a new worksheet, select a cell, then:
Data -> From Other Sources -> From SQL Server
put in the server name, select table, etc,
When you get to the "Import Data" dialog,
click on Properties in the "Connection Properties" dialog,
select the "Definition" tab.
And there Excel nicely displays the Connection String for copying
(or even Export Connection File...)
If one uses the tool Linqpad, after one connects to a target database from the connections one can get a connection string to use.
Right click on the database connection.
Select Properties
Select Advanced
Select Copy Full Connection String to Clipboard
Result: Data Source=.\jabberwocky;Integrated Security=SSPI;Initial Catalog=Rasa;app=LINQPad
Remove the app=LinqPad depending on the drivers and other items such as Server instead of source, you may need to adjust the driver to suit the target operation; but it gives one a launching pad.
put below tag in web.config file in configuration node
<connectionStrings>
<add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
providerName="System.Data.SqlClient" />
then you can use above connectionstring, e.g.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();
The sql server database will be stored by default in the following path
<drive>:\Program Files\Microsoft SQL Server\MSSQL.X\MSSQL\Data\
, where <drive> is the installation drive and X is the instance number (MSSQL.1 for the first instance of the Database Engine). Inorder to provide the connection string you should know what is the server name of the sql server database, where you have stored followed by instance of the database server.
Generally the server name will be like the ip address of the machine where the database is attached and the default instance will be SqlExpress
A connection string contains Data Source name i.e., server name, Initial catalog i.e., database name, user id i.e., login user id of the database, password i.e., login password of the database.
Easiest way my friends, is to open the server explorer tab on visual studio 2019 (in my case), and then try to create the connection to the database. After creating a succesful connection just right click on it and go to propierties. There you will find a string connection field with the correct syntax!...This worked for me because I knew my server's name before hand....just couldn't figure out the correct syntax to run my ef scaffold...
If you created Connection Manager in your project then you can simply pull the connection string from there.
String connection = this.dts.connections["<connection_manager_name>"];
And use this connection in:
using (var conn = new SqlConnection(connection))
Please correct me if I am wrong.
SqlConnection con = new SqlConnection();
con.ConnectionString="Data Source=DOTNET-PC\\SQLEXPRESS;Initial Catalog=apptivator;Integrated Security=True";

can not open database on localnetworks

I write a win app,and i create my database on the server by codes.now every client on local network can't login to my database and this error occured
:"cannot open database "test" requested by the login.the login failed for user "farzane".
the connectionstring for to make my database is:
ConnectionString=#"Data Source=SERVER\SQLEXPRESS;Initial Catalog=master;Integrated security=SSPI;Persist Security Info=False";
and it's my connection string for open my database:
ConnectionString=#"Data Source=SERVER\SQLEXPRESS;Initial Catalog=test;Integrated security=SSPI;Persist Security Info=False";
how can give permission for logining to my database to any client with codes???
thanks in advance for any help.
I would check two things here:
Ensure that your SQL Express install allows remote connections. (Simple to check using SQL Server Studio Manager).
You are using trusted authentication in your connection string. You have to explicitly give users on your domain access on the database. You will have to this in SQL Server.
are you using a domain for the network ?
if yes then make sure that the user name has access to the SQL server
if you're using a workgroup then it won't work... just create a user on the sql server and use the sql server auth at the server and connection string
Points i concluded:
First of all the users who are going to create the database , must be authorized to use master database. So ask your admin to allow permission to farzanne.
If you(farzanne) are admin, set farzanne to create databases permission to true. Or the other users that might create dbs. Also, if you allow all users then it will be difficult to handle, your application, so be alert.
What is the need of the dynamically createing database from application. Is this a part of setup or deployment or you are creating an isolated space that is different user different database.

Categories

Resources