How to verify connection string in App.config? - sql-server

I am brand new to Entity Framework and I am attempting to set up this tutorial:
https://github.com/entityframeworktutorial/EF6-DBFirst-Demo
In the readme, it asks me to first open the project in Visual Studio 2017, I used 2019 because that's what is installed on my system so hopefully this is not an issue.
Second, it asks to "Open MS SQL Server 2012 and attach SchoolDB.mdf (included in EF6DBFirstDemo folder)" this took me a few days to figure out because I had several versions of MSSQL server 2012 installed so i removed them all and installed a single version.
Also, I placed the folder with all the files into my desktop under my current user nested a bit down (next to all the other applications I am managing). Unfortunately, by doing this, I could not navigate to the .mdf file in MSSQL Management Studio so I had to copy this file over into a location that was visible to the management studio which turned out to be 'C:/Program Files/Microsoft SQL Server/MSSQL11.SQLEXPRESS/MSSQL/DATA', Anyhow I eventually got the database installed and I can see the tables and such now.
The third step says to "Verify the connection string in App.config in Visual Studio and make sure that it is pointing to your local DB server." Having absolutely no idea how this is done, I crossed my fingers and clicked the go icon in visual studio. The application of-course immediately blows up.
My question is, what exactly do I need to change in the App.config file to make it point at my particular local database. Here is a copy of what that file has currently:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="SchoolDBEntities"
connectionString="metadata=res://*/School.csdl|
res://*/School.ssdl|
res://*/School.msl;
provider=System.Data.SqlClient;
provider connection string=
"data source=.;
initial catalog=SchoolDB;
integrated security=True;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I have a feeling the reason it's not working is because the code exists within my users directory and the database it is trying to reach was installed from C/Program files/whatever, but this is just a hunch.
Any ideas?

For data source specify the same server name you used when you connected via SSMS. Since you are using Express edition (as suggested by the file path), the local named instance specification should probably be data source=.\SQLEXPRESS.

Related

How to create a test page to check the SQL Server database connection on online hosting site (plesk)

I want to make sure that my database is connected with my site or not. I created this project in ASP.NET MVC. My project is working fine on my local machine, but after I deployed my project to the hosting site, there are two problems occurring:
Login and registration page is not loading
I think it is due to database connection or connection string problem.
Here is the Home Page
In the Home page menu, there is an item My accounts. In "My accounts" option there are Login Link and Registration link
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=IP address\.MSSQLSERVER2012;Initial Catalog=StarBuy;Integrated Security=SSPI;"
providerName="System.Data.SqlClient"/>
<add name="StarBuyEntities1"
connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=IP adrees\.MSSQLSERVER2012;initial catalog=StarBuy;user id=abc;password=****;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Try to run your local application with connection string to the remote database and see if it is working. This should help to know if the problem is with connection string.

How to transfer ASP.NET MVC Database from LocalDb to SQL Server?

I created a new ASP.NET MVC 5 project in Visual Studio 2013 (Express for Web) and by default, the project uses LocalDb as its database, but how do you transfer or migrate the database to SQL Server?
I want to use SQL Server for the database instead of LocalDb. But how?
Notwithstanding this question is old, the answer didn't help me so I want to share how I solved it for my self.
On Server Explorer, find your ASPNet DB. Then open it using SQL Server Object Explorer.
Then go and hit Schema Compare option
Then on the the Schema Compare window for the Target database, select the SQL Server data base you want the ASPNet DB to integrate to. Then hit Compare button
Deselect all Delete actions for the target database, and leave selected all Add actions for the ASPNet DB, then hit Update button.
Finally, update your connection string so it points to your SQL Server DB
Got it!
Based on #warheat1990's answer, you just have to change the connection string. But #warheat1990's answer had a little too much change. So here's my original (LocalDb) connection string:
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-my_project-20150318100658.mdf;Initial Catalog=my_project-20150318100658;Integrated Security=True"
providerName="System.Data.SqlClient"/>
To connect it to SQL Server instead of LocalDB, I modified the connection string into:
<add name="DefaultConnection"
connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=my_project;Integrated Security=True"
providerName="System.Data.SqlClient"/>
Thanks to #warheat1990 for the idea of simply changing the Web.config. My first thoughts were to identify and use the feature that VS supplies, if theres any. Because Microsoft doesnt have a concise documentation on how to do this.
Change the connectionString in your web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-KlikRX-20141203034323.mdf;Initial Catalog=aspnet-Test-20141203034323;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
to your own database connectionString, for example :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=7.7.7.7\sql;Initial Catalog=TestDB;User ID=sa;Password=sa" />
</connectionStrings>
It sounds like you may want to move the data from your local database to sql server. If so, the easiest way to do this would be to back up your local database and then restore it on the server.
To back up:
https://msdn.microsoft.com/en-us/library/ms187510.aspx#SSMSProcedure
To restore:
https://msdn.microsoft.com/en-us/library/ms177429.aspx
EDIT:
If you need to install an instance of SQL Server:
https://msdn.microsoft.com/en-us/library/ms143219.aspx
Overlord's migration example is spot on. My note at the end was a bit big for a comment, so here are the required changes to the web.config file. An old method on a local drive was to specify
Data Source=".\[InstanceName]
but may not work on newer interfaces, so replace [.\instance] with [ComputerName\instance] if you migrate forward. This is Visual Studio Pro 2017, SQL Server 2014 & Entity Framework 6.0.
1st update the connection string.. replace items in brackets with info needed to connect to your database.
<connectionStrings>
<add name="DefaultConnection"
connectionString="Initial Catalog=[DatabaseName];Integrated Security=True;User ID=[SQLASPNETUserName];Password=[UserPassword];"
providerName="System.Data.SqlClient" />
</connectionStrings>
next update the entity info.. The [InstanceName] used for SQL Server can be found from [SQL Server Mgmt] console - [Server Properties] - [Advanced] - [Filestream Share Name] & defaults as [MSSQLSERVER].
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="[ServerName]\[InstanceName]"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
for cloud or other multi-server database migrations, also review [sessionState] settings in web.config & replace [InProc] with [Custom]. [sessionState] comes between [/roleManager] & [/system.web]
this default for 1 db server
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider"
type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection"/>
</providers>
</sessionState>
& this replacement for mult-server or cloud environments
<sessionState mode="Custom" customProvider="DefaultSessionProvider">
I had the same problem and just solved this...so the main point is default connection string...which you need to modify correctly otherwise it is pointless..and impossible to connect properly. So copy all you aspnetroles...users table to online database( they should look the same as in your local database).
You can compare schema(local db) with real db. It is quit well explained by "Overlord" -> Explanation
But after lets now correctly modify defaultconnection string
That is my default string before modification:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-track_spa-20180502025513.mdf;Initial Catalog=aspnet-track_spa-20180502025513;Integrated Security=True" providerName="System.Data.SqlClient" />
That is my modified default string after modification:
<add name="DefaultConnection" connectionString="Data Source=servername,portnumber;Initial Catalog=AttendanceTrak;Integrated Security=False;User Id=****;Password=*****;Encrypt=True;TrustServerCertificate=False;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
servername - should be your server.
portnumber - should be your server port
It took me ages to finally get it working properly...but this small trick with default string just made it!
Hops this helps
In relation to OverLords answer, it worked perfectly for me thanks!
If anyone is struggling with the connection string use:
<add name="CONNECTIONSTRINGNAME" connectionString='data source= DATABASE SOURCE initial catalog="DATABASE NAME ";user id="USERID";password=PASSWORD;MultipleActiveResultSets=True;' providerName="System.Data.SqlClient" />
I had a similar problem, wanting to export from a local db to remote db-server and encountered an error message I couldn't find any information on, but the answer came to me when reading this post, so I'm submitting my answer here in case anyone else has the same problem.
I set up a solution with Individual User Accounts. VS conveniently creates a db (mdf-file under App_Data) and a connectionstring in the web.config.
In all my wisdom I thought: "Why not move this to a remote server?" So I did.
I restored the mdf file on the remote server, expanded it with some simple tables for my web site, created a new connection to the db and added a new ado.net edmx-file, removed the "DefaultConnection" in the web.config and updated the reference to my new connection in the ApplicationDBContext.
Pressed play, and... no sigar (when trying to log in).
The entity type IdentityUserLogin is not part of the model for the current context.
Turns out the IdentityDbContex prefers the "DefaultConnection" with the providerName="System.Data.SqlClient" so adding a new edmx-file with the providerName="System.Data.EntityClient" is no good.
Solution: As warheat1990 suggested, I updated (put back) the DefaultConnections and it's connectionstring value.
One might argue that I should have two seperate db's (one for users) and one for business stuff, but that's an other discussion.
This works for me..
Change the connection string in the web config file pointing to the database server, then run the application and register a user. Once registered successfully, go to SSMS and refresh the database and then the identity tables should appear.
Regards

2 DNN filesystems pointing to the same database

I have setup a local installation of DNN7 using a database residing in another machine (sqlserver 2008).
I've tried to copy all the filesystem to a production server but keep the connection string the same, so use the exact same database.
I get the message
"The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty."
<roleManager>
<providers>
<add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
The application pool and IIS settings are the same in both machines. Any ideas of what am I missing?
You are missing following section in web.config
<connectionStrings>
<!-- Connection String for SQL Server 2005/2008 Express -->
<!-- Connection String for SQL Server 2005/2008
<add name="SiteSqlServer" connectionString="Server=(local);Database=DotNetNuke;uid=;pwd=;" providerName="System.Data.SqlClient" />
-->
</connectionStrings>
The problem had to do with the role membership provider.
For some reason the AspNetSqlMembershipProvider provider falls back at the default one which is in the machine.config (insided the .NET folder).
In dev environments with an SQLEXpress instance running, the machine.config has a connection string named 'LocalSqlServer' which points to the SQLExpress. That's why it worked in my dev environment.
The server on the other hand, doesn't have SQLExpress, so no LocalSqlServer connectionstring exists in the machine.config and therefore the error pops up.
The workaround I found in DNN forums is to add these lines inside the section of the web.config
<remove name="LocalSqlServer" />
<add name="LocalSqlServer" connectionString="Data Source=dbserver;Integrated Security=false;Initial Catalog=dbName;User ID=dbUser;Password=dbPass" providerName="System.Data.SqlClient" />

using login controls with sql server (not express)

I installed Visual Studio 2008 Professional(updated with SP1), then I uninstalled SQL server 2005 Express and installed SQL Server 2005 Standard.
now I am not able to add 'SQL Server Database' to the project - it says
Connections to SQL Server files (*.mdf) require SQL Server Express 2005 to function properly.
Is it not compliant with SQL Server Standard version?
And Login Controls also not working-
Web Administration Tool says
Unable to connect to SQL Server database
Also tried with aspnet_regsql command-line utility.. not working..(actually I dont know what is to be done after creating SQL server database through 'aspnet_regsql command-line utility')
Please Provide a solution for my problem before somebody Closes this question or marks for deletion ;P :)
The functionality to just attach a stand-alone .mdf file as a database is indeed available in the Express editions of SQL Server only.
What you should do in any other case is create the database on the SQL Server instance, and refer to it by its database name - not it's .mdf file name.
In order to create those tables and stored procedures needed for the ASP.NET membership and role subsystem, you need to use the aspnet_regsql utility against your SQL Server instance. You said that didn't work - how does it not work?? Did you get an error ?? If so: what error??
See the MSDN docs on aspnet_regsql for details on how to use it. To create the ASP.NET membership and role subsystem, use:
aspnet_regsql -S (your server name here) -E -A mr
The -E uses integrated security (e.g. your current Windows logon) to connect to SQL Server - that user accounts needs enough permissions for these operations, of course! If you need a specific SQL Server user, there's are the two -U (username) -P (password) parameters to achieve this.
Once you have all of this, you also need to configure your ASP.NET membership and role subsystem to actually use that new database (ASPNETDB) that was created on your SQL Server. By default, they use the aspnetdb.mdf file attached to your SQL Server Express instance. Since you've changed that, you need to update your configuration! See how to do this in detail on MSDN
Step 1: add a connection string to your newly created database
In your web.config or app.config, add a valid connection string to your newly created ASP.NET membership/role database - something like:
<configuration>
<connectionStrings>
<add name="ASPNETDB_Connection"
connectionString="Server=YourServer;database=aspnetdb;Integrated Security=SSPI;" />
</connectionStrings>
Step 2: - add a valid configuration for the ASP.NET membership subsystem and reference that new connection string you've just added in Step 1; something like:
<configuration>
<system.web>
<membership defaultProvider="YourProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="YourProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="ASPNETDB_Connection"
applicationName="MyApplication"
enablePasswordRetrieval="false" enablePasswordReset="true"
requiresQuestionAndAnswer="true" requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
Step 3: do the same for the role subsystem:
<configuration>
<system.web>
<roleManager defaultProvider="YourProvider" enabled="true" cacheRolesInCookie="true" >
<providers>
<clear />
<add name="YourProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ASPNETDB_Connection"
applicationName="MyApplication" />
</providers>
</roleManager>

Elmah not working on IIS7 server

I have Elmah running on my MVC 3 site, and have everything working on my local development machine.
However, now that I've moved my site to my production server, Elmah is not working. I am using the same SQL account (and connection string) on my live server as I'm using on my local machine. The EF4 connection (same as Elmah) works just fine.
I don't see anything in the Even Logs or in SQL Profiler. I don't see any errors in the SQL logs either.
Any ideas on what could be happening, or how I could troubleshoot this?
Thanks in advance.
ELMAH is using a HttpModule to log errors. For IIS6, HttpModules are registered under System.Web in the web.config file. However, for IIS7+, HttpModules should be registered under the system.webserver namespace. The embedded development web server will use the IIS6 config.
IIS6:
<system.web>
<httpModules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
</httpModules>
</system.web>
IIS7:
<system.webServer>
<modules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
</modules>
</system.webServer>

Resources