SQL Server error with tying my database to Form controls - c#

I am using Visual Studio 2012 Professional with SQL Server 2012 Express. I have created a new Windows Form (C#) project and started out by creating a new data connection and named it MyShop.mdf. From there I created two tables: Customer and Order.
I manually populated the customer table with 6 records and from the data sources tab, dragged it to my form and watched the tool strip appear at the top along with the labels and controls based on the data types I established with the table data.
When I build and run, none of the data I entered into the customer table shows up - it acts as though the table is empty, yet if I go back into 'Show Table Data', everything I entered still remains. Secondly, when I attempt to add a new record via the form, the following error appears:
An attempt to attach an auto-named database for file c:\users\darden\documents\visual studio 2012\Projects\MyShopForm\MyShopForm\bin\Debug\data\MyShop.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Any thoughts to what I am missing? Thanks for your help.

My error on this question...I should have known better: after properly researching this website, I found the error resolution with the following:
"An attempt to attach an auto-named database" error

Related

SqlException:System.Data.SqlClient [duplicate]

I have created a web service which is saving some data into to db. But I am getting this error:
Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'.
My connection string is
Data Source=.\SQLExpress;Initial Catalog=IFItest;Integrated Security=True
Well, the error is pretty clear, no? You are trying to connect to your SQL Server with user "xyz/ASPNET" - that's the account your ASP.NET app is running under.
This account is not allowed to connect to SQL Server - either create a login on SQL Server for that account, or then specify another valid SQL Server account in your connection string.
Can you show us your connection string (by updating your original question)?
UPDATE: Ok, you're using integrated Windows authentication --> you need to create a SQL Server login for "xyz\ASPNET" on your SQL Server - or change your connection string to something like:
connectionString="Server=.\SQLExpress;Database=IFItest;User ID=xyz;pwd=top$secret"
If you have a user "xyz" with a password of "top$secret" in your database.
Either: "xyz\ASPNET" is not a login (in sys.server_principals)
Or: "xyz\ASPNET" is set up but not mapped to a user in the database test (sys.database_principals)
I'd go for the 2nd option: the error message implies the default database is either not there or no rights in it, rather than not set up as a login.
To test if it's set up as a login
SELECT SUSER_ID('xyz\ASPNET') -- (**not** SUSER_SID)
If NULL
CREATE LOGIN [xyz\ASPNET] FROM WINDOWS
If not NULL
USE test
GO
SELECT USER_ID('xyz\ASPNET')
If NULL
USE test
GO
CREATE USER [xyz\ASPNET] FROM LOGIN [xyz\ASPNET]
I had this problem and what solved it for me was to:
Go to the Application pools in the IIS
Right click on my project application pool
In Process Model section open Identity
Choose Custom account option
Enter your pc user name and password.
For me the database was not created and EF code first should have created it but always endet in this error. The same connection string was working in aspnet core default web project. The solution was to add
_dbContext.Database.EnsureCreated()
before the first database contact (before DB seeding).
The best solution for the login problem is to create a login user in sqlServer. Here are the steps to create a SQL Server login that uses Windows Authentication (SQL Server Management Studio):
In SQL Server Management Studio, open Object Explorer and expand the folder of
the server instance in which to create the new login.
Right-click the Security folder, point to New, and then click Login.
On the General page, enter the name of a Windows user in the Login name box.
Select Windows Authentication.
Click OK.
For example, if the user name is xyz\ASPNET, then enter this name into Login name Box.
Also you need to change the User mapping to allow access to the Database which you want to access.
Most times, it's not a login issue, but an issue with creating the database itself. So if there is an error creating your database, it would not be created in the first place. In which case if you tried to log in, regardless of the user, login would fail. This usually happens due to logical misinterpretation of the db context.
Visit the site in a browser and REALLY read those error logs, this can help you spot the problem with you code (usually conflicting logic problems with the model).
In my case, the code compiled fine, same login problem, while I was still downloading management studio, I went through the error log, fixed my db context constraints and site started running fine....meanwhile management studio is still downloading
This Works for me.
Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
In newly opened screen of Login Properties, go to the “User Mapping” tab.
Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed.
Click OK.
Read this blog.
http://blog.sqlauthority.com/2009/08/20/sql-server-fix-error-cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user-nt-authoritynetwork-service/
It also happen when you type wrong name of DB
ex : xxx-db-dev to xxx-dev-db
Sometime, it's just a stupid mistake . I take about more than 1 hours to find out this :( because i just try alot of difficult thing first
The Issue
The error presents itself as a message similar to this:
Cannot open database "DATABASE NAME" requested by the login. The login
failed. Login failed for user XYZ.
The error cannot usually be rectified by a simple Visual Studio or full-computer restart.
The error can also be found as a seemingly locked database file.
The Fix
The solution is laid in the following steps. You will not lose any data in your database and you should not delete your database file!
Pre-requisite: You must have installed SQL Server Management Studio (Full or Express)
Open SQL Server Management Studio
In the "Connect to Server" window (File->Connect object explorer) enter the following:
Server type : Database Engine
Server name : (localdb)\v11.0
Authentication : [Whatever you used when you created your local db. Probably Windows Authentication).
Click "Connect"
Expand the "Databases" folder in the Object Explorer (View->Object Explorer, F8)
Find your database. It should be named as the full path to your database (.mdf) file
You should see it says "(Pending Recovery)" at the end of the database name or when you try to expand the database it won't be able to and may or may not give you an error message.
This the issue! Your database has crashed essentially..
Right click on the database then select "Tasks -> Detach...".
In the detach window, select your database in the list and check the column that says "Drop Connections"
Click OK.
You should see the database disappear from the list of databases. Your problem should now be fixed. Go and run your application that uses your localdb.
After running your application, your database will re-appear in the list of databases - this is correct. It should not say "Pending recovery" any more since it should be working properly.
The source of the solution: https://www.codeproject.com/Tips/775607/How-to-fix-LocalDB-Requested-Login-failed
I tried to update the user, and it worked. See the command below.
USE ComparisonData// databaseName
EXEC sp_change_users_login #Action='update_one', #UserNamePattern='ftool',#LoginName='ftool';
Just replace user('ftool') accordingly.
I had this problem when I created a WPF .NET Core + Entity Framework Core project and then cloning it on a a new laptop.
Using:
update-database
in the package manager console simply solved it.
To open package manager console go to:
Tools-> Nuget Package Manager -> Package Manager console
I used Windows authentication to connect to local database .mdf file and
my local server was sql server 2014.
My problem solved using this connection string:
string sqlString = " Data Source = (LocalDB)\\MSSQLLocalDB;" + "AttachDbFilename = F:\\.........\\myDatabase.mdf; Integrated Security = True; Connect Timeout = 30";
In my case it is a different issue. The database turned into single user mode and a second connection to the database was showing this exception.
To resolve this issue follow below steps.
Make sure the object explorer is pointed to a system database like master.
Execute a exec sp_who2 and find all the connections to database ‘my_db’. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.
USE MASTER;
EXEC sp_who2
Alter the database
USE MASTER;
ALTER DATABASE [my_db] SET MULTI_USER
GO
I ran into this issue when attempting to write to the default database provided in the asp.net mvc template. This was due to the fact that the database hadn't been created yet.
To create the database and make sure that it is accessible follow these steps:
Open up the Package manager console in Visual Studio
Run the command "update-database"
This will create the database an run all the necessary migrations on it.
I have not seen this mentioned in the previous issues, so let me throw out another possibility. It could be that IFItest is not reachable or simply does not exist. For example, if one has a number of configurations, each with its own database, it could be that the database name was not changed to the correct one for the current configuration.
NB: If using a windows service to host the webservice.
You have to insure that your webservice is using the right Log on account to connect to SQL Server.
Open services(I assume the windows service has been install)
Right click on the service and goto properties.
Click on "Log On" Tab
Click on "This account" radio button
Click "Browse"
Enter Pc user name in Text Field and click "Check Name" Button to the right.
Click on text in Text Field, press "OK" button
enter login password and Apply
Inspired by cyptus's answer I used
_dbContext.Database.CreateIfNotExists();
on EF6 before the first database contact (before DB seeding).
If you haven't created the database in your server you will get the same login error.Make sure that the database exist before you login.
it's not a login issue most times. The database might not have been created. To create the database, Go to db context file and add this.Database.EnsureCreated();
The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.
I found that I also had to set the UserMapping option when creating a new login and this solved the problem for me. Hope that helps anyone that also found themselves stuck here!
Edit: Setting the login as db owner solved the next problem, too
Some times this trouble may appear if you open this db in another sql server (as example, you launch sql managment studio(SMS) and add this db), and forget stop this server. As result - you app try to connect with user already connected in this db under another server. To fix that, try stop this server by Config. dispatcher sql server.
My apologies about bad english.
Kind regards, Ignat.
In my case the asp.net application can usually connect to database without any problems. I noticed such message in logs. I turn on the SQL server logs and I find out this message:
2016-10-28 10:27:10.86 Logon Login failed for user '****'. Reason: Failed to open the explicitly specified database '****'. [CLIENT: <local machine>]
2016-10-28 10:27:13.22 Server SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.
So it seems that server was restarting and that SQL server whad been shutting down a bit earlier then ASP.NET application and the database was not available for few seconds before server restart.
Even if you've set the login as DB owner and set the user mapping for the database that will use the login, check that the actual DB user (not just the login) has the role of 'owner'.
In my case, I was running a Windows Service under "System" identity. The error was:
System.Data.SqlClient.SqlException (0x80131904):
Cannot open database "MyDbName" requested by the login. The login failed.
Login failed for user 'MYDOMAINNAME\HOSTNAME$'.
The problem is that the error is very misleading. Even after I added 'MYDOMAINNAME\HOSTNAME$' login to the database, and granted this login sysadmin access and added a user for that login on my target database, and made that user dbowner, I was still getting the same error.
Apparently I needed to do the same for 'NT AUTHORITY\SYSTEM' login. After I did that, I was able to login without a problem. I don't know why the error message complains about 'MYDOMAINNAME\HOSTNAME$'. I deleted that login and the corresponding user and everything still works.
When using EF Code First, make sure the database exists. You could run the update-database command first.
If none of the above solution is working.
I encountered with the same error message but my issue was completely different. I had just restore my database and the database was in restoring mode. So if your database is in rstoring mode just apply following query.
RESTORE DATABASE MyDatabase
FROM DISK = 'pathToYourDbBackup\MyDatabase.bak'
WITH REPLACE,RECOVERY
I had this happen to me when I deleted the DB and forgot to recreate it. It happens sometimes, since Database folder needs refresh.
If you didn't have any problems before and you get this error only in the package manager console, you don't need to do anything special. Just open the sql server object explorer window and connect and run the command again in the console.

c# SQL) unable to open physical file(MS localdb .mdf) after attaching the .mdf file which was created in another computer(server)

I'm developing Windows Desktop appication(C# WPF) with Microsoft localdb(.mdf) and I want that users of my software can carry their localdb (.mdf) file when they move to other places(computers). The localdb (.mdf) file is created on the first computer.
To test my application, I copied my localdb file from computer A to computer B and attached with below code successfully.
string attach_greendbnameQuery = string.Format(#"EXEC sp_attach_db #dbname = N'greendb_{0}', #filename1 = N'{1}\greendb_{0}.mdf'", textBoxGreenLogin.Text, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString());
SqlCommand attach_greendbnamecomm = new SqlCommand(attach_greendbnameQuery, check_datadbinmasterConn);
attach_greendbnamecomm.ExecuteNonQuery();
And I could read and write data into the moved localdb file.
However, when I run backup command on this database, exception occurs like,
'Unable to open physical file, Operating system error 32, process cannot open the file because the file is in use by another process'
If I enter Server Management Studio- Security-KayLee-PC\KayLee- User Mapping,
the users of all other localdb are 'dbo' but only the user of manually moved database is KayLee-PC\KayLee and only 'public' is checked and all other database roles are not checked including db_owner. (I always start(login) Windows(O/S) with KayLee-PC\Kaylee account)
I tried to make all roles checked to database roles even to server roles but failed.
Even, I tried to drop the user KayLee-PC\KayLee through below code but the exception message show as,
'User 'KayLee-PC\KayLee' does not exist in current database'
If I click the database in Server Management Studio, the current database status is not changed to clicked database and subtree nodes(like Table, Security and so on) are not displayed with message 'cannot access to the database' eventhough if I click other databases, the current database status is changed to clicked database.
Also, I tried to change the owner of the localdb(database) through below code but it seems the execution failed with result '-1' with 'sa' and when trying with 'KayLee-PC\KayLee' which I always login to Windows O/S, error message is like 'KayLee-PC\KayLee is already an owner(exist) of this database'
SqlConnection dbownerchange_Conn = new SqlConnection();
dbownerchange_Conn.ConnectionString = dbownerchange_ConnectionString;
dbownerchange_Conn.Open();
SqlCommand dbownerchange_comm = new SqlCommand();
dbownerchange_comm.Connection = dbownerchange_Conn;
dbownerchange_comm.CommandText = "EXEC sp_changedbowner 'sa'";
dbownerchange_comm.ExecuteNonQuery();
dbownerchange_Conn.Close();
Simply, If we need to move(copy) Microsoft localdb file to another place(computer), how can I do this successfully?
Must we detach before move the localdb file? If so, I'm worried there're always people who don't follow guideline by running detach function.
I've tried several scenarios to understand how SQL server is working. The conclusion is we need to detach first and re-attach to same or different machine(computer). Then, I could have been successful to move to another computer.
However, a single process of backup and restoring localdb to another machine(computer) doesn't work. Furthermore, if we detach localdb(database file .mdf) first, SQL server no more recognizes the localdb database and we cannot run backup command for the localdb.
Conclusively and simply, if we want to move localdb (microsoft database .mdf file) to other local server(computer, machine), we're needed to just detach the localdb from master database in computer A and copy the files and re-attach to another master database of computer B.
Hope this helps someone else..

The database cannot be opened because it is version 839. This server supports version 782 and earlier. A downgrade path is not supported

I made a C# project that contains a local database (Microsoft SQL Database Server) (mdf) in my pc that works totally fine. but whenever i use my laptop to run it, it gives me this error:
The database 'C:(the path)\CALENDER.MDF' cannot be opened because it is version 839. This server supports version 782 and earlier. A downgrade path is not supported.
this error appears every time i try to refresh server explorer. i need it to work in my laptop because i use it to make a class presentation.
After a long researches and tries i figured how to solve this issue. its a bit complicated. i converted the mdf database to and access(mdb) and import data from the mdb to a new mdf database.
these are the steps:
Create an empty access (mdb) database.
using SQL Server 2016 CTP3.0 Import and Export Data: import data from database which is calander.mdf in my case to the new access database (mdb).
now in the destination pc, create a new vs form and add a new empty mdf database.
using Microsoft SQL Server Management Studio ( Databases > right click new database > type database name and click OK.)
Right mouse click on your database name and hover to Tasks and then select the Import Data.
select the data source Microsoft Access (Microsoft Access Database Engine) and browse to the access database and click next.
in Destination select Net Framework Data Provider For SqlServer and type the connection string for the new empty created mdf database. then click next and finish.
Copy the new mdf database To your project file
now you got the new database filled with data and all is left is go to your main project and delete the database and then add new existing item and browse to the new database and log file and clock ok. and the database should work
WORKED WITH ME !!!!!!

Trying to import an existing database to VS using Entity framework

So, Im trying to learn a lot of database related programming since there seem to be a lot of job openings doing that sort of programming. I've spent som time with MS SQL Server and now I've moved on to trying to learn the Entity Framwork. I have created a small database with MS SQL Server and now I want to use it in a Visual Studio project.
The problem is that when I add a new "ADO.NET Entity Data Model" to my project and select "Generate from database" I have to select a data connection. In every single tutoral they can just choose from a drop down list, but my list is empty. I've tried to create a "New connection..." but I have no idea which option to choose. "Microsoft SQL Database File" seemed logical, but when I do that and then select my databasefile it says that I don't have the rights to access it(I'm the admin). I've also tried selecting "Microsoft SQL Server" as my data source. Then I can add my server name from the drop down list but the "Select or enter a database name" drop down list is empty and if I enter my database name manually I get some connection error
So yea, basically I need help with setting up a new data connection in the Entity Data Model Wizard
Enter the Server Name and have a try with "Test Connection". If it throws an error, either the MS SQL Server is not at the specified location or you have to specify login credentials (Use SQL Server Authentication).
Enter exact server name that you use for log-in into SQL Management Studio.
Then It will show list of database. Select your database and try "Test Connection".

Can't create a database in SQL Server 2012

I have recently installed SQL Server 2012 on my machine. When I try to create a database in SSMS by right clicking on Databases and selecting New Database, it prompts me for various items in order to create the database. After entering the name of the database and clicking OK, I get an exception:
"Create failed for Database 'aaaa'. (Microsoft.SqlServer.Smo)
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
A file activation error occurred. The physical file name 'aaaa.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors. (Microsoft SQL Server, Error: 5105)"
It seems the problem is only with the wizard because when I execute Create Database query it successfully creates the database.
I figured it out that when Database is created from wizard, a file path is to be provided in Path column. If it is blank by default then it means there is no path specified in Database settings.
In Object Explorer, right-click a server and click Properties.
In the left panel, click the Database settings page.
In Database default locations, view the current default locations for new data files and new log files. To change a default location, enter a new default path name in the Data or Log field, or click the browse button to find and select a path name.
We can change the file path while creating Database.
The actual database file permissions were set to read_only,please try unchecked the read_only checkbox on the file permissions.
I also had this problem and I can in this link where I've created any string values (DefaultData and DefaultLog) in regedit in this path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer.
In this "string values" you must put the path where your SQL data and log must stay.
As you realized there is a Path column in the grid view for each file (.mdf and .ldf).
This is set to <default>.
At the first usage of the server this default path may not be set, so the full-path of the new database cannot be computed.
Solution:
Based on this article you can set it via the interface of SSMS. You just need to:
right click on your server name (e.g.: (LocalDB)\v11.0),
select Properties,
select Database Settings,
Fill up all 3 entry of Database default locations with valid directory paths. (Defining top 2 paths: Data and Log is enough to create databases.)
This will create the right registry entries for you, without touching regedit.exe.
What path to choose?
Either the location that is proposed along installation:
C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data
Or the location of system databases:
C:\Users\[UserName]\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\v11.0
Or better choices for non-system databases are:
C:\Users\[UserName]\My Documents\Databases
C:\Users\[UserName]\My Documents\SQL Server Management Studio\Databases
Note 1: [UserName] can be "Public" to make it common data (please correct me if this causes multiple copy of the database, but I think it won't).
Note 2: I don't know whether latter is deleted along uninstallation of SSMS.

Categories