LocalDB - New code-first databases no longer being created on default folder - c#

I'm using Entity Framework's Code-First and LocalDB, with the following connection string:
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyApp;Integrated Security=True;
Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true;
The instance and its database files were properly created inside this path:
C:\Users\Me\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB
But I was messing around and I renamed then deleted the MSSQLLocalDB through Visual Studio's "SQL Server Object Explorer" and its files. Now that I created it back, all databases generated via EF Code First are being created inside my %USERPROFILE% folder, i.e. C:\Users\Me.
In "SQL Server Object Explorer", if I right click and "Add New Database", it shows the right path. Right clicking the instance then properties shows that "Default Database Location" is correct.
The registry is correctly configured:
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Microsoft SQL Server\UserInstances\{9F44D466-A9BA-40E3-9DEA-21E0638C80A2}]
...
"DataDirectory"="C:\\Users\\Me\\AppData\\Local\\Microsoft\\Microsoft SQL Server Local DB\\Instances\\MSSQLLocalDB"
I tried to create a new instance through SqlLocalDB Utility with a different name, but it behaves the same way. Also tried rebooting, before and after deleting the instance, no success.
I also tried reinstalling. I uninstalled Visual Studio (Web and Desktop), MS Data Tools, MSSQL Compact and MS LocalDB, then reinstalled VS, but no success.
I don't want to change my connection string and point it to the correct path, since the project is shared and maintained by other developers.
How do I revert this behavior? I'm using Visual Studio 2015 Express.

You can set the path here (in registry):
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Microsoft SQL Server\UserInstances]
The path is not a part of your connection string, so do you really have a problem?

Related

Can't access LocalDB on other computers, through application

I have made an application which uses a LocalDB, to refer to some predefined values as part of some mathematics that it does.
I have created an Installer project so that when the application gets installed, a copy of the DB is sent to [ProgramData][ProductName], which is mapped as the pathway for the ConnectionString.
When I install it and run the application on my computer (out of Visual Studio), it runs exactly as I want it too - and there are no errors, warnings or messages in the code.
However when I installed it on to someones else's computer (so they can play with it and point out any errors that they come across), this is where the problem comes about.
On their computer, whenever the code refers to the LocalDB they get the below Exception Message:
"A network-related or instance specific error occurred while trying to establish a connection to SQL Server" System.Data.SqlClient.SqlException (0x80131904).
The error goes on to say that the LocalDB instance does not exist.
I've double checked the ProgramData folder, and can confirm that the LocalDB did get copied there during the install - and I have confirmed that the code is looking at the correct folder when trying to connect to it - I just can't figure out what is happening.
I have checked that the user has read/write access to the folder, and is a LocalAdmin on their computer.
Is anyone able to help guide me to a solution with this, please?
ConnectionString is below, if it helps:
AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Application_Name"));
ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
You actually can connect to a localdb instance from other machines. It's a perfectly valid configuration. (Although, if you're really running it like a service, you'd be better off with SQL Server Express Edition instead).
First, you need to make sure that the localdb instance is fired up. That can be your application, or it can be via the SqlLocalDB Utility. See here: https://learn.microsoft.com/en-us/sql/tools/sqllocaldb-utility?view=sql-server-2017
Second, you need to make sure that TCP is enabled. Details of setting up a shared instance are described here: https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/sql-server-express-localdb?view=sql-server-2017
Hope that helps.

Visual Studio Install - Post-install where should I point local database connection string?

I have a major, two day head damaging question. I have a localDB for a desktop application coded in C#. The .mdf database file resides in the root directory for the application. When debugging in development this worked fine (using EF6). My connection string is as follows:
(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\LocalStorage.mdf;integrated security=True;connect timeout=30
Yet when i build an installer and point my application as the 'Project Output' something happens whereby I receive the error upon successful install...
An attempt to attach an auto-named database for file C:\Program Files\Company Name\Program\LocalStorage.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
It seems my database does not install to the location (it simply isnt there). I suspect the '|DataDirectory|' in conn string does not point to an internal.exe location? Help Please, im at my wits end.
Most cases like this are dealt with by having a dialog in the application that describes things about the database. That includes the security connection (Windows Integration or not) and perhaps the db name and location. I'd ask about that in a SQL forum rather than an installation forum. Although some installs sometimes ask users for that kind of thing in a dialog, most users would rather get the install finished and then worry about the configuration.

build connection string at runtime and save the same in application setting on c# windows app

I am building a C# windows application using sql server 2005 and visual studio 2008.
To deploy the application on clients computer. I do this this in this order
I install the sql server 2005 with the same user/pass (ie sa/pass) i made in my app.
I run my windows application msi file. It install my databasae in sql server 2005.
when I try to run the application I fail due to different machine name and sql server instance name on my clients computer. i am getting error in connection string. i need a way to extract the target computername and sql server instance and save the same in my application setting during deployment (using in my c# code so that i can make a connection string at runtime.)
To resolve the problem what i am doing is I am installing visual studio on my client's computer and editing the source code to change the machine name and sql server instance. Then my windows application runs. I don't want to resolve my problem this way but rather need a way where i can set my parameters at deployment time or leave it up to you to suggest a better way.
I would request you to help me.
Google will give you lot of options. Have you followed the right steps while copying a database.
Follow these links http://blogs.msdn.com/b/sreekarm/archive/2009/09/11/move-a-database-from-one-server-to-another-server-in-sql-server-2008.aspx
and this will answer yours DBA Stack Exchange
Also post the Exact error message you get.It ll be useful to figure out the issue
Using SQL CE will require a lot of rework.
The full install order is:
Install Windows Installer 3.1 (if its not installed)
Install .Net 2.0 (if its not installed)
Check if SQL is NOT already installed:
HKLM "SOFTWARE\Microsoft\Microsoft SQL
Server\${instance_name}\MSSQLServer\CurrentVersion" "CurrentVersion"
Then you need to install SQL Server:
${installer_path}\SQLEXPR.exe -q /norebootchk /qn
reboot=ReallySuppress addlocal=all INSTANCENAME=${instance_name}
SAPWD=${password} SECURITYMODE=SQL SQLBROWSERAUTOSTART=1
SQLAUTOSTART=1 AGTAUTOSTART=1 ASAUTOSTART=0 RSAUTOSTART=0
DISABLENETWORKPROTOCOLS=0 ERRORREPORTING=1 SQMREPORTING=0 ENABLERANU=0
ADDUSERASADMIN=1
To connect to the SQL Server instance use your data link properties dialog. You will need to give clear instruction to your users how to connect to the instance. eg
If you use the .\Instance_Name syntax where the "." dot represents the client PCs name that should solve the problem. Also use this in your connection string.
So, if I understand you correctly, you have hardcoded your connection string inside your source code. And of course, you have discovered at your expense how this is really a bad idea.
You need to have that connection string saved in your app.config file. In this way, when you install your application to your customer, you need only to change the config file and your code is ready to go.
To insert your connection string in your app.config:
right click on your project and select Properties, then go to the
Settings page. This will create a settings.settings file for your
project and will open a GUI editor for your properties.
Now insert a string in the column name (for example
testConnection)
Select from the Type column the ConnectionString type
Insert, in the value column, a connection string valid for your
development machine
Now if you open the app.config you will notice a new section called ConnectionStrings that will look like this:
<connectionStrings>
<add name="ProjectName.Properties.Settings.testConnection" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\mytemp.mdb;User Id=admin;Password=;" />
</connectionStrings>
Now it is time to fix your code once and forever.
In every place where you have an hardcoded connection string replace that code with something like this
string constring = ConfigurationManager.ConnectionStrings["ProjectName.Properties.Settings.testConnection].ConnectionString;
And while we are here, check if the LocalDB version of SqlServer Express 2012 could be used to remove also the need to install SqlServer.

Setup a test environment on my local machine using Visual Studio

What is the easiest way to setup a test environment on my local machine using Visual Studio 2008 with a website that that has a mssql database, which is hosted through a webhost?
I am web designer and I am re-skinning a live website that is built in .NET C#. I have access to the files and when I run it in Visual Studio (localhost) only the static files are obviously pulling up , which is problematic for testing. I need to be able to run the entire website on my local. I am not going to be messing with the database at all, but I know that I am going to need it to be able to have a local copy that works. I am not extremely savvy on these types of things. I was hoping that someone could either point me in the right direction (ie. search terms, keywords) or give me some instructions on how to make this work. Any help is appreciated.
Thanks.
You should set up MSSQL server first. You can take backup from your production database using
RMC on DB -> Tasks -> Backup..
Then you use the generated .bak file on your local server to insert the copy of the database into your SQL Server instance like this:
RMC on Databases -> Restore Database -> Path to your backup..
At this step your instance should contain the database with all the tables and data. Next thing to do would be to change your web.config file connection string (or any place else, where the "Connection string" is set pointing the website to the database) accordingly to your instance. If it's MSSQLSERVER instance name, you can just use following connection string:
Data Source=(local);Initial Catalog=<database name>;Integrated Security=True;
After this compiling and running your source codes should be returning you the site in its fullest.

ADO.Net - Why isn't the insert happening?

I went through MSDN pages to learn ADO.Net using Commands. I am able to read using the sample code posted there.
But when I tried to use the modification code below, the insert is not happening. I am not ale to figure out why. Can someone please tell me what is wrong with this code?
string connectionString = "A_VALID_CONNECTION_STRING";
string commandText =
"INSERT INTO Contacts (FullName, Mobile) VALUES ('Pierce Brosnan', '1800-007')";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
SqlCommand command = new SqlCommand(commandText, connection);
Console.WriteLine(command.ExecuteNonQuery());
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Edit
No exception is thrown.
The ExecuteNonQuery() which is supposed to return the no. of rows affected is returning 1.
Environment: Visual C# 2010 Express | SQL Server 2008 Express | Windows 7 Ultimate 32-bit.
Update
Previously I was using a MDF file present in the project. It was, I guess, automatically attached to the SQL server instance each time the project ran. This is when I had the problem. The connection string had some info about attaching a database file.
I removed the SQL Server 2008 Express that I installed along with Visual C# 2010 Express. Also removed the MDF file from the project.
I Separately downloaded and installed SQL Server 2008 Express along with Management Studio Express.
Created a new database in management studio.
Used a different type of connection string to use the database in the server.
Now INSERT is working!
P.S. I guess I should have mentioned that I had an attach database file scenario. Really sorry for that.
My suspicion is that you had the following scenario:
Database.mdf file was present in the project with the table structure created in it
Your connection string looked something like this Server=.\SQLExpress;AttachDbFilename=database.mdf;Database=dbname; Trusted_Connection=Yes;, i.e. loading the database in the connection string.
What was happening was, when you built/ran your project, your application was compiled and the database.mdf file was copied along with it to ApplicationProjectFolder\bin\Debug, so that when the application was run, the file database.mdf was present. This means that everytime you ran your project, the "empty" database.mdf file was copied from ApplicationProjectFolder\database.mdf to ApplicationProjectFolder\bin\Debug\database.mdf, hence the data "disappearing". Also, the file database.mdf probably had "Copy Always" set on its properties in the project.
So, the "INSERT" was working, it was just being "reset" everytime you ran your application.

Categories

Resources