I was doing unit test in the Visual Stdio 2010. However, it kept throw to exception 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 was searching to solve this problem, and I knew that it was problems of connection between visual studio and sql server. (Maybe, maybe not.)
I was trying to change "App.config" and "Web.config".
Is it right way to fix this problem? If it is yes, can you give example of xml to fix this problem? If it is no, what should i do for fixing this problem?
It's impossible to tell exactly what's going on without code (please post some), but from your comments, I am guessing it's because you haven't correctly set up the SQL connection string.
Most of the time, you would have a connection string specified in the .config file (although you might have it hard-coded in your code?). If you're using something like Entity Framework, app.config might look like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="MyEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost;Initial Catalog=MyDatabase;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Depending on what your code is doing, it might look different (again, post some code). If you have the code working in an application, but it's failing in the unit tests, you can probably just copy the connection string from the application's app.config file into the unit test's app.config file. If your unit tests don't have an app.config file, just create one.
By the way, the config above is just one example of how you might specify a connection string... your code might require something different.
Hope that helps point you in the right direction...
Update: still would like to see some code, but if it is looking for connection strings out of your database, they typically look something like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=myserver;Initial Catalog=MyDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Hi Every One this is a solution for those who want connect a database with WampServer or Sql Server Management Studio , i try it both and it works both , read carefully , and sorry for my bad english (Tunisian Dev) :
To create a db from classes, using the EF (Entity Framework) Code First method:
**1. First create the Context Common class exmple:
Public class MyClassContext: DbContext
{
Public MyClassContext (): base ("name = ConnStringLinkedForDb") {
Database.SetInitializer (new DropCreateDatabaseAlways <MyClassContext>());
}
Public DbSet <ClassX> ClassXs {get;set;}
}
2. In This second point the tag: ,
Would be in the 2 files "app.config" to the data layer and "web.config" in the web layer,In the following two cases:
2.1. If you want to make a connection with Wamp Server (idUserName = root, pwd = 'empty') and our bd would be on its server:
<ConnectionStrings>
<Add name = "ConnStringLinkedForDb" connectionString = "server = localhost; user id = root; persistsecurityinfo = True; database = db_name_desired; allowuservariables = True" providerName = "MySql.Data.MySqlClient"/>
</ ConnectionStrings>
2.2.with sql Server Management Studio (ServerName (Source) =YourServerNameInSqlServerManegementStudioProprity(onObjectExplorer), pwd = 'empty') and that our bd would be on its server:
<ConnectionStrings>
<Add name = "ConnStringLinkedForDb" connectionString = "Data Source = YourServerNameInSqlServerManegementStudioProprity(onObjectExplorer); Initial Catalog = db_name_desired ;Integrated Security = true" providerName = "System.Data.SqlClient" />
</ ConnectionStrings>
**
I had a similar issue. If you had:
Already created the database
Changed development machine/reinstalled SQL server
Attached your previous database
go to your root project folder:
bin->Debug or
bin->Release
locate your .config file
Open with notepad and edit your connection string there
Next (if you had not), open your project in visual studio and locate App.config in Solution Explorer, edit the connection string there to match your current connection.
Related
I'm using web sockets and SqlDependency to build a game server. An error with the SqlDataReader indicated that I should call SqlDependency.Start. I included the following in my Global.Asax:
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
This line always ends with the SqlException, with message:
Cannot attach the file 'C:...aspnet-ProjectName-11111111111.mdf' as database 'aspen-ProjectName-11111111111'.
I've been trying to fix this for two days. I've started a fresh MVC 4 WebAPI app, with a basic model, context, and seed, and can't get around this error. I've tried the various solutions in the following:
https://social.msdn.microsoft.com/Forums/en-US/ae041d05-71ef-4ffb-9420-45cbe5c07fc5/ef5-cannot-attach-the-file-0-as-database-1?forum=adodotnetentityframework
ASP.NET MVC4 Code First - 'Cannot attach the file as database' exception
EF5: Cannot attach the file ‘{0}' as database '{1}'
No change. I'm running MVC4 API in Visual Studio 2012, SQL Server is 2014.
This is a DB connection problem, right? The .mdf file in my AppData folder (both it and the log file are there in both projects) can't be connected to SQL Server? Also, help?
I encountered the same problem as you.
In your Web.config file, find you connection string, copy and paste it and then remove everything after the 'MultipleActiveResultSets' - apart from the providerName.
So in mine, it changed from this:
<add name="ApplicationName" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ApplicationNameContext-20151023111236; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|ApplicationNameContext-20151023111236.mdf" providerName="System.Data.SqlClient" />
Became this:
<add name="NotificationConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ApplicationNameContext-20151023111236; Integrated Security=True;" providerName="System.Data.SqlClient" />
And as you will notice the connection has a different name.
The connections will still query the same database.
Now modify your connection string name in the Dependency.Start parameter to be your the name of the connection string you just created:
SqlDependency.Start(ConfigurationManager.ConnectionStrings["NEW_CONNECTION_NAME"].ConnectionString);
Remove the Initial Catalog property in your connection string.
You should see this answer: https://stackoverflow.com/a/20176660/161471
Recently started trying to dig into code first approach for Entity Framework. I have crated some database tables following various tutorials but none of them did the trick.
Starting from scratch about 3 to 4 times now because the exceptions get more and more absurd. Last time created the database on first access but wasn't able to connect to the database in a second debug session because of missing permissions (using integrated security - wat?). Apparently the .mdf was blocked by System process and only a restart in safe mode allowed me to get rid of it.
Anyway, anew. I have a class library, which contains the database models and a gateway class for external access. I have a Console project to test the database creation and access. EF is installed in the class library via NuGet, reference to EntityFramework.SqlServer.dll is added to the Console project.
The connection string looks like this in both projects:
<connectionStrings>
<add name="DbConnection"
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\LanguageCreator.mdf;Initial Catalog=LanguageCreator;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
My context class looks like this:
public class LanguageContext : DbContext {
public LanguageContext() : base("DbConnection") {
// Have to set the DataDirectory in code because the wrong one gets set from the config.
AppDomain.CurrentDomain.SetData("DataDirectory", Directory.GetCurrentDirectory());
Database.SetInitializer(new CreateDatabaseIfNotExists<LanguageContext>());
public DbSet<Language> Languages { get; set; }
public DbSet< ... blablabla various other DbSets following, nothing of interest here.
}
This is what my gateway looks like:
public class Gateway {
public void InitializeDatabase() {
using (LanguageContext context = new LanguageContext()) {
context.Database.Initialize(true);
// I did have a configuration class for migration, which seeds some initial data, which is why I'm trying to read the WordTypes here but I left that thing out this time ... will try to add it later on.
IEnumerable<WordType> wordTypes = context.WordTypes.AsEnumerable();
List<Language> languages = context.Languages.ToList();
}
}
}
The call simply looks like this:
class Program {
static void Main(string[] args) {
Gateway databaseGateway = new Gateway();
databaseGateway.InitializeDatabase();
}
}
Now, without absolutely anything special, I recieve the following error on starting a debug session:
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: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
Unfortunately, the Windows Application event log doesn't show any details to that error. Or maybe I'm too stupid to find it ...
What is actually causing this issue and how can I fix this? Everything I found was about access to external SQL Servers but I simply want EF to create an .mdf locally and connect to that.
I'm very new to Entity Framework and databases in general, but I have a couple suggestions that may help narrow down the issue.
"Verify that the instance name is correct and that SQL Server is configured to allow remote connections." See if the problem is with the server by connecting to it with a different program. If you have trouble connecting to it outside of EF, you can eliminate EF as the problem.
If you can, leave out the connection-string or any mention of your SQL database and see if EF will generate a LocalDB for you. I believe this is the default behaviour of EF. If this works, I think this would also suggest that there's something about your SQL server that's giving you trouble.
Again, I'm very new to this, so just thoughts I'd suggest the way I would try to problem-solve this with my limited knowledge. Hope it's helpful!
Okay, I figured it out on accident. I installed EntityFramework via NuGet in the Console project and voilá, Visual Studio created the .mdf on starting a debug session.
As it still worked after uninstallation of EntityFramework I created the project anew and checked for differences. I found out that the EntityFramework entries in the app.config were still present, so I copied them over to the new project and now that worked as well.
So if you're stuck with the same problem try adding these parts in the app.config of your console project (or whatever project type you use to access your database class library):
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<connectionStrings>
<add name="LanguageCreator.data.LanguageCreatorContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyContext.mdf;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
I have MVC app running fine in local. After updating to Azure, it started throwing the error:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project.
I have checked if there is any difference between the local web.config and azure web.config. except the credentials, everything is same. And it read:
<add name="DBEntities"
connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;
provider=System.Data.SqlClient;
provider connection string="data source=xx;initial catalog=xx;persist security info=True;user id=xx;password=xx;MultipleActiveResultSets=True;application name=EntityFramework""
providerName="System.Data.EntityClient" />
I am using EF 6.1.3, MVC5
I ran into the same error message and managed to solve it with the help of this post here on StackOverflow.
In the Azure Management / Web Apps / [Your web app] / CONFIGURE / connection strings , make sure of 3 things :
The connection string has the same name as the connection string in your project.
The connection string Value contains all of the metadata as appears in the connection string in your project. Mine looks like this:
metadata=res://\*/Models.[MyModel].csdl|res://\*/Models.[MyModel].ssdl|res://\*/Models.[MyModel].msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[myDBServer].database.windows.net,1433;Database=[myDB];User ID=[myDBUser]#[myDBServer];Password=[myPassword];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
The third column (default set to SQL Database) is set to Custom
Found a simpler solution than adding all the stuff in the Azure connection string. I just changed the connection string name in Azure. It worked..
I had to deal with the same issue. The solution was
Connect to the website by FTP
Edit web.config
Add following connection string:
add name="NewDatabaseEntities" connectionString="metadata=res:///NewDatabase.csdl|res:///NewDatabase.ssdl|res://*/NewDatabase.msl;provider=System.Data.SqlClient;provider connection string="Data Source=tcp:your.database.windows.net,1433;initial catalog=your;integrated security=False;User Id=your;Password=your;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
Thanks Microsoft for poorly documentation of EntityFramework Database First on Azure.
You need to change this line metadata=res:///NewDatabase.csdl|res:///NewDatabase.ssdl|res://*/NewDatabase.msl;
to
metadata=res://*/;
Given the following connection string:
<add name="PrimaryDBConnectionString" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=10.1.1.101;Initial Catalog=primary;Persist Security Info=True;User ID=myuserid;Password=mypassword;MultipleActiveResultSets=True;Application Name=EntityFramework"" />
I attempt to open a connection in my DAL with the following:
using (PrimaryDBContext ctx = new PrimaryDBContext(ConfigurationManager.ConnectionStrings["PrimaryDBConnectionString"].ToString()))
{
try
{
ctx.Connection.Open();
var result = ctx.sq_newsfeed_GetProfileByID(profileID);
The error I get is:
The underlying provider failed on Open
I have messed around with the EF connection string and replaced all the provider prefix stuff with "metadata=res://*/;" but still no go.
Can anyone shed some light on this please?
Thanks.
-- Update --
Thank you for the response...
I ended up just creating a new db connection from the UI and modifying the connection string to match my needs:
<add name="PrimaryEntities" connectionString="metadata=res://*/PrimaryModel1.csdl|res://*/PrimaryModel1.ssdl|res://*/PrimaryModel1.msl;provider=System.Data.SqlClient;provider connection string="data source=10.99.108.42;initial catalog=primary;user id=dbuserID;password=somepw;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I kept the metadata portion. The trick was to ensure that your .csdl, .ssdl and .msl file name prefix matches your db context.
Are you using Code First/DbContext (your question is filed under entity-framework-4.1)? If so then your connection string should be just a regular connection string - something like this:
<add name="PrimaryDBConnectionString" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=squirtprimary;Persist Security Info=True;Integrated Security=true;MultipleActiveResultSets=True;Application Name=EntityFramework" />
(You also don't have to do magic with configuration manager - you can just provide the name of the connection string to your ctor like this:
"name=PrimaryDBConnectionString"
and it should work)
On the other hand, if you are not using DbContext but ObjectContext (the exception you get would indicate this - you did not get an exception saying that your connection string is wrong or you are missing the providerName parameter). Then you would need to check if you are able to connect to the database without EF. A few hints:
you use an IP address as your Data Source - if this is a remote server are you sure you enabled accepting external clients? (AFAIR this is disabled in Sql Server by default)
you are using user/pwd for authentication - are you sure that these are correct
One of the ways to check the above is to open Sql Server Management Studio on your machine and provide the data you have in your connection string.
The exception you are seeing does not indicate any problems with metadata part. It is specifically about not being able to open the connection to the database.
I have an application (WinForms) which using SQL Server as its database.
Now I am using app.config file to access ConnectionString.
Have a look at my app.config file
<configuration>
<connectionStrings>
<add name="dbConnectionString"
connectionString="Data Source=abc-79f1f531c9f;Initial Catalog=ItemStockInParth;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
You can see that Data Source=abc-79f1f531c9f.
Here ==> abc-79f1f531c9f is server name which is running on my (Developer's) PC.
Now when application is being installed at client's site, the server name should be changed to the server name which is running on the client machine or server name which will client machine use.
Then what should be the best criteria for handling this situation?
Means I have to create one new form which asking user to enter their Server Name and as per that I creating our ConnectionString?
Or dynamically getting the servername?
Or just hard-code the Server Name of client machine (or server name which will client machine use) inside our App.config file?
please help.....
You will probably want to provide a place where the user can enter the name of the server, or if you are clever, provide a list of available servers on the network (for example by using the code referenced by #user350374). Then you can generate an appropriate connection string as you need it using the SqlConnectionStringBuilder class:
var builder = new SqlConnectionStringBuilder();
builder.DataSource = ##SERVER NAME FROM USER##
builder.InitialCatalog = "ItemStockInParth";
builder.IntegratedSecurity = true;
builder.Pooling = false;
string connectionString = builder.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
// use the connection here for your code
con.Close();
}
This would take the place of requesting the connection string from your configuration class, i.e., where you would normally say ConfigurationManager.ConnectionStrings['dbConnectionString'].ConnectionString.
Since you can programmatically read the list of connectionstrings defined in the app.config, I suggest you create a list of connection strings and ask the user which one to use:
foreach(ConnectionStringSettings setting in ConfigurationManager.ConnectionStrings)
{
...
}
It's better than to ask for the server name, as you can give a nice name to a connectionstring entry.
Is this what you are looking for
http://krishnapyrmca.wordpress.com/2010/11/23/get-sql-server-name-using-c/
<add key="Connectionstring" value="Data Source=.;
AttachDbFilename=|DataDirectory|\AppData.mdf;
Initial Catalog=Appdata;Integrated Security=True"/>
<add key="Connectionstring" value="Data Source=.;
AttachDbFilename=|DataDirectory|\AppData.mdf;
Initial Catalog=Appdata;Integrated Security=True"/>
Simply add this code in the app.config file and attach your database to the setup file.
It automatically takes the database from the setup file of your project.