I'm trying to use Profiles in my program. Creating the necessary tables using aspnet_regsql.exe from the command line worked fine. However, A System.Web.HttpException exception is thrown saying it is unable to connect to the database when I try to run the application. This is strange because I am connected to the database on the Server Explorer in VS 2013. Here is the error message on my application's website.
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
Here's the relevant code in my web config file.
<profile defaultProvider="SqlProvider" inherits="[Namespace].AccountProfile">
<providers>
<clear/>
<add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="[stringname]"/>
</providers>
<properties>
<add name="Rows" type="System.String"/>
<add name="Area" type="System.String"/>
</properties>
</profile>
And here is the code in my application where the exception is thrown
AccountProfile.cs
public class AccountProfile : ProfileBase
{
static public AccountProfile CurrentUser
{
get { return (AccountProfile)(ProfileBase.Create(Membership.GetUser().UserName)); }
}
....
}
Turns out the Membership.GetUser() part of the code was still trying to use the LocalSqlServer connection string found in the machine.config file instead of the database connection string I provided in the web.config. Adding <clear /> in my connectionString configuration helped me figure this out.
<connectionStrings>
<clear />
<add name="..." connectionString="Data Source=...;Initial Catalog=...;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Related
I am trying to connect Visual Studio 2017 to SQL Server 2016 Express using the following code in my app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<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.5" />
</startup>
<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>
<connectionStrings>
<add name="BlogDbContext" connectionString="Data Source=DESKTOP-I3K90LQ\SQL2016;Initial Catalog=CodeFirstDemo;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
I created a sample repository to test in my program.cs file
using System;
using System.Collections.Generic;
using System.Data.Entity;
sing System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Post
{
public int Id { get; set; }
public DateTime DatePublished { get; set; }
public DateTime DateEdited { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
public class BolgDbContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
class Program
{
static void Main(string[] args)
{
}
}
}
I installed Entity Framework into my Console Application using the following command in the Package Manager Console
PM>install-package EntityFramework -version 6.1.3
Then I enable Migration and create the first migration:
PM>enable-migrations
PM>add-migrations CreatePost
PM>update-database
after submitting update-database command I get following error message:
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:-1,State:0,Class:20
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
So my Visual Studio is not able to connect to my SQL Server Management Studio to create a database.
If this work right, my Code First console project should be able to use a Sql instance instead of LocalDb instance to create and update a database from Visual Studio. ###
I have searched google for solutions for hours last night. Some suggest that could firewall issues, that I should create a port 1433 and enable TCP/IP in the Sql Server Configuration Manager to allow VS connecting to SQL. I have all those solutions, but none of them worked for my test project.
If anyone out there have an answer, please help.
Many thanks!
Further technical details
Target Framework: .NET Framework 4.5
Operating system:
IDE: (e.g. Visual Studio 2017 15.4)
Pretty sure by default EF looks for DefaultConnection connection name on your web.config. Someone can correct me if I'm wrong.
You need to override the connection name via :base() on your DbContext class.
public class BolgDbContext : DbContext
{
public BolgDbContext() : base("name=BlogDbContext") { }
public DbSet<Post> Posts { get; set; }
}
FYI, typo BolgDbContext is intentional, copied pasted from your code...
I found solution as Following:
<connectionStrings>
<add name="BlogDbContext" connectionString="Data Source=DESKTOP-I3K90LQ\SQL2016;Initial Catalog=CodeFirstDemo;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=localhost; Integrated Security=True; MultipleActiveResultSets=True"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
So glad I found this and your solution! I'm just posting here to describe how I got the same problem and a bit more detail on how to fix it.
The same in VS2019, with EntityFramework and Update-Database. The same error message, ie A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
I was following a very good tutorial. It had connectionString="Data Source=.;Initial Catalog=FriendOrganizer;Integrated Security=True". This had been working for half of the tutorial, and Update-Database had created and seeded the DB, so I knew the DB was accessible.
After applying some changes in the tutorial it stopped working. I deleted the DB and Migrations, recreated the Migrations How to delete and recreate from scratch an existing EF Code First database, but it sill didn't work, with Update-Database producing this error, after a timeout.
Using the flag '-Verbose' assisted somewhat in tracking it down, but I needed this answer! I went to the Sql Server Object Explorer, right-clicked on the first '(localdb)\MSSQLLocalDB...', and got the Connection string property. I copied this and replaced it in the connectionStrings in the App.config for the data access project. Then Update-Database worked! (When I ran the app it timed out on the connection, as I needed to do the same in the Startup Project App.config, but that may not apply in all cases, depending on whether you have two App.configs).
For my db, FriendOrganizerDb the connection string is...
<connectionStrings>
<add name="FriendOrganizerDb"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=FriendOrganizer;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>
FriendOrganizer is the DB for the tutorial I was following - and highly recommend! (Building an Enterprise App with WPF, MVVM, and Entity Framework Code First)
I've implemented Identity & OWIN authentication to my existing asp.net web form application. I referred to the site:
https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project
I am having problem with connection string for entity framework code first approach. I referred to the site: http://odetocode.com/Blogs/scott/archive/2012/08/14/a-troubleshooting-guide-for-entity-framework-connections-amp-migrations.aspx for help. But none of them is working.
I use VS 2015, SQL Server 2014 & Windows 10 OS.
For SQL Server authentication (Windows authentication) my server name is : DESKTOP-07C2G55.
I changed my connection string as told in the sites but none of them worked. My first connection string is::
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=DESKTOP-07C2G55;Initial Catalog=WebFormsIdentity;AttachDbFilename=|DataDirectory|\WebFormsIdentity.mdf;Trusted_Connection=Yes;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
On using this connection string when I try to register any user I am getting error as:
Directory lookup for the file "c:\users\myPC\documents\visual studio 2015\Projects\RENTAL\RENTAL\App_Data\WebFormsIdentity.mdf" failed with the operating system error 5(Access is denied.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Directory lookup for the file "c:\users\myPC\documents\visual studio 2015\Projects\RENTAL\RENTAL\App_Data\WebFormsIdentity.mdf" failed with the operating system error 5(Access is denied.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Then I run the following commands in my VS console. I get:
PM> Get-Service | Where-Object {$_.Name -like '*SQL*'}
Status Name DisplayName
------ ---- -----------
Running MSSQLFDLauncher SQL Full-text Filter Daemon Launche...
Running MSSQLSERVER SQL Server (MSSQLSERVER)
Running MSSQLServerOLAP... SQL Server Analysis Services (MSSQL...
Stopped SQLBrowser SQL Server Browser
Stopped SQLSERVERAGENT SQL Server Agent (MSSQLSERVER)
Running SQLWriter SQL Server VSS Writer
PM> SqlLocalDb info
MSSQLLocalDB
Then I changed my connection string, chaned the datasource to Data Source=MSSQLLocalDB:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=MSSQLLocalDB;Initial Catalog=WebFormsIdentity;AttachDbFilename=|DataDirectory|\WebFormsIdentity.mdf;Trusted_Connection=Yes;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I get the error
Invalid value for key 'attachdbfilename'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Invalid value for key 'attachdbfilename'.
Again I changed my connection string to Data Source= .\SQLEXPRESS
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=WebFormsIdentity;AttachDbFilename=|DataDirectory|\WebFormsIdentity.mdf;Trusted_Connection=Yes;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I got the error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I can not figure out what is the problem whether the cause of the problem is connection string or any where else in the code. In other solutions, it is mentioned to edit DBContext Class, but in the tutorial there is no such class created. I am not using MVC, simple web form application trying to implement Identity and OWIN module. Please help me.
The output from your PowerShell script shows that you have a default instance (with the "instance" name of MSSQLSERVER) of SQL Server running:
Running MSSQLSERVER SQL Server (MSSQLSERVER)
This means, you can use Data Source=. (or Data Source=(local)) for your server name (you must not define an instance name to connect to the default instance), define the database name in Initial Catalog, and drop that AttachDbFileName crap once and for all (and let SQL Server handle all the file-related ins and outs - don't mess around with .mdf database files yourself!):
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=.;Initial Catalog=WebFormsIdentity;Trusted_Connection=Yes;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I'm getting the error at the bottom when trying to do a Role lookup with a modified version of .NET 's role system.
line of C# code that throws the error 26:
System.Web.Security.Roles.IsUserInRole("blahuser", "blahrole");
This is when I run from localhost. The role system works fine in dev and prod.
Project is set to IIS Express. The other weird thing is this works locally for my boss, but not for any other of the devs here. I am able to connect to the auth database just fine and make edits, in SQL Server Management Studio using my windows creds, or using the connection string user/pass shown below. It is probably a permissions issue, but we dont know which one it might be. My boss has tried all he can think of for now. I forgot to mention I am using the exact same config file as my boss, whos works fine on his local pc.
role manager config is below:
<roleManager enabled="true" cookiePath="/" cookieName="Test" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All" cacheRolesInCookie="true" cookieTimeout="30">
<providers>
<add connectionStringName="DefaultConnection" applicationName="Dovetail.Apps" name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</providers>
</roleManager>
This connects to our auth database and it should be using this connection string in web.config:
<add name="DefaultConnection" connectionString="Data Source=DtiDevSql201.Dovetail.Local;Initial Catalog=blahauthserver;User ID=blahuser_id;Password=blahpass" providerName="System.Data.SqlClient" />
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I have tried all I can from other users who had answers to this question but they didn't work.
Why do you think this is the connection being used? You should have something that looks like this:
<roleManager defaultProvider="SqlProvider"
in your configuration and then later something like this:
<providers>
<add
name="SqlProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlServices"
applicationName="SampleApplication" />
</providers>
Please look for those configuration items. Their contents my help you solve the "mystery".
I configured my SQL Server database using aspnet_regsql.exe. Everything worked great. I then added the new connection string in my web.config file:
<connectionStrings>
<clear />
<remove name="LocalSqlServer" />
<add name="SQLConnectionString"
connectionString="Provider=ProvName;Server=Sname;Database=dbName;Uid=user; Pwd=pWord" />
</connectionStrings>
When I try to access the database from the website I get an error:
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty.
Source Error:
I am running this site on IIS via Visual Studio 10. Any ideas what steps I'm missing?
<add name="LocalSqlServer" connectionString="Data Source=.;Initial Catalog=DBName;Uid=user;Pwd=pWord" provider="System.Data.SqlClient"/>
Something like above should work.
Your code is looking for a connection string named "LocalSqlServer", yet you are adding a connection string named "SQLConnectionString".
Change this to:
<add name="LocalSqlServer" connectionString="Provider=ProvName;Server=Sname;Database=dbName;Uid=user; Pwd=pWord" />
Do a search for the phrase "LocalSqlServer" in all your config and code (.cs?) files. It is being references somewhere else...not just the connection-strings config area.
The "name" attribute is used in other places in the code to look up the actual connection string.
I like Agent Ransack for looking in files for a specific string.
When you find the other reference, you can replace it with "MySuperSpecialConnectionStringName" (as seen below, an alteration of your original code).
I'm using Visual Studio Express 2013 for web and I'm following this tutorial : http://www.codeproject.com/Articles/791740/Using-AngularJs-ASP-NET-MVC-Web-API-and-EntityFram which specifies this connection to connect ot the db:
<add name="MainDb" connectionString="Server=localhost; Database=SimpleTaskSystemDb; Trusted_Connection=True;" providerName="System.Data.SqlClient" />
but when I run Update-Database I get this error:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
I've also finished the Music Store app which is working fine and the connection there is different:
<add name="MusicStoreEntities" connectionString="Data Source=|DataDirectory|MusicStore.sdf" providerName="System.Data.SqlServerCe.4.0"/>
I tried a similar connection string but that didn't work either.
No Entity Framework provider found for the ADO.NET provider with
invariant name 'System.Data.SqlServerCe.4.0'. Make sure the provider
is registered in the 'entityFramework' section of the application
config file.
However the Music Store app.config file does not reference System.Data.SqlServerCe.4.0 but I added it to this app anyway and then I get back to my original error.
Any help would be greatly appreciated.
Here are some of the sample connection strings I have described every connection string with full details
For Local Sql server (BuildIn Sql Server Express into Visual Studio).
For Sql Server instance which comes default with visual studio you can use following connection string
<connectionStrings>
<add name="ConnectionStringName" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=YourDatabaseName;Integrated Security=True"
providerName="System.Data.SqlClient" />
For Sql Server Which Has been installed seperately such as Evaluation Edition etc
<connectionStrings>
<add name="ConnectionStringName" connectionString="Data Source=YourPCName-PC\ServerInstanceName;Initial Catalog=YourDatabaseName;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
For CompactEdition of Sql server you can use provider name as
providerName="System.Data.SqlServerCe.4.0"