Connectionstring in web.config wont work. Not even with absolute path - c#

I've created a local database in Visual Studio with entity framework. But I can't get it to work. I get the "The underlying provider failed on Open."
I've tried with relative path to the database and absolute path but it wont work.
The project is MVC and the database is in an other solution in the project. (DataAccess > Logic < MVC)
The error I get when I run with absolute path. The error is the same with relative path:
"An attempt to attach an auto-named database for file ~D:\\Visual Studio Projects\\Esport\\Esport.Domain\\Context\\Database\\esportDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."}"
My web.config in MVC:
<connectionStrings>
<add name="esportDatabaseEntities" connectionString="metadata=res://*/Context.Model.esportDatabaseModel.csdl|res://*/Context.Model.esportDatabaseModel.ssdl|res://*/Context.Model.esportDatabaseModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=~D:\Visual Studio Projects\Esport\Esport.Domain\Context\Database\esportDatabase.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
My App.Config in DataAccess layer:
<connectionStrings>
<add name="esportDatabaseEntities" connectionString="metadata=res://*/Context.Model.esportDatabaseModel.csdl|res://*/Context.Model.esportDatabaseModel.ssdl|res://*/Context.Model.esportDatabaseModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Context\Database\esportDatabase.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
EDIT: I moved the project to C: to get read and write and now it works with the absolute path. The problem is that I can't run it with absolute path. I need it to be relative. Any ideas how to do that? |DataDiretory| points to App_data and my database is not in app data..
EDIT2: When I run the relative path, |DataDiretory|esportDatabase.mdf I get this error:
{"An attempt to attach an auto-named database for file C:\\Esport\\Esport\\App_Data\\Context\\Database\\esportDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."}
But the database is not located there. Its located at: C:\Esport\Esport.Domain\Context\Database\esportDatabase.mdf.

I have found that using code based configuration for EF is much easier to work with.
To gain complete control over what goes on with the connection string, you can create a special constructor for your DbContext derived classes that takes a connection string argument, and then use your constructor with a connection string every time you instantiate your DbContext classes.
The EF templates generate the DbContext derived classes as partial classes, which means you can add this constructor away from the auto-generated code.
It is fully explained here:
http://www.programmersranch.com/2013/11/c-ef-setting-connection-strings-at.html
FYI, you can manipulate DataDirectory like this, though you should be careful about how it could affect other parts of your application:
string AppDomainDataDirectory
{
get
{
object obj = AppDomain.CurrentDomain.GetData("DataDirectory");
return obj != null ? obj.ToString() : "";
}
set
{
AppDomain.CurrentDomain.SetData("DataDirectory", value);
}
}

Related

Entity Developer/EntityFramework - The specified named connection is either not found in the configuration

Using Devart Entity Developer with Entity Framework 6. I have my main class library project. I had a different Winform project altogether that uses Entity Developer/Entity Framework that I developed to do some database work with Sql. I decided to add this secondary Winform project to the main class library.
First I tried adding the Winform project to the solution. That did not work well. Even though I added a reference to the exe of the Winform project it seems not to find it ok. I removed that project from the solution.
As a second attempt. I copied the classes from the Winform project (two of them) to the main class library project and recreated the Entity Developer/Entity Framework stuff. Now when I run the project everything runs (including the new form) but I cannot connect to the database. I get the error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
The line that has the error is the line calling base:
public SWPDMEngVaultEntities() :
base(#"name=SWPDMEngVaultEntitiesConnectionString", "SWPDMEngVaultEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
My connection string is in the app.config file and looks like this:
<connectionStrings>
<add name="SWPDMEngVaultEntitiesConnectionString" connectionString="metadata=res://*/DataModel1.csdl|res://*/DataModel1.ssdl|res://*/DataModel1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=XXXXXX\SQLEXPRESS;Initial Catalog=XXXXXX;Integrated Security=False;Persist Security Info=True;User ID=XXXXXX;Password=XXXXXX""
providerName="System.Data.EntityClient" />
</connectionStrings>
All of the XXXXXX's in the above string have been confirmed as correct. Also, Entity Developer has a "Test Connection" and the test connection connects just fine. Entity Developer also gets the database information OK so I know it is able to connect without issue. The problem is at runtime on the solution.
I have looked at other posts about this error and they all seem to be saying make sure your connection string is good. What else should I check?
The answer to this issue came from Devart. Class libraries do not use app.config files for settings. By default the connection string in the Devary generated templates are stored in the app.config file. There is a place to turn this off when the model is generated.

ADO.NET Customer Error System.Data.SqlClient.SqlException (0x80131904)

I've created an application that works perfectly on my PC using C# and SQL Server 2014.
My connection string is:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Youssef\Desktop\gone\gone\gone\gestion_incidents.mdf;Initial Catalog=BG_ONE;Integrated Security=True
I know that the connection string is the problem but how can I create a connection string that works on all computers?
Replace your database file path to a generic path that automatically get the location of the project data folder and it will not cause problem when you move project to another location. Follow below steps:
Step 1: First Add App_Data folder in your project and add database file there.
Step 2: Change your connection string replace path before the database file with |DataDirectory|
Example:
<connectionStrings>
<add name="ConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\nwind.mdb" providerName="System.Data.OleDb" />
</connectionStrings>
If you follow the above steps then your connection replace C:\Users\Youssef\Desktop\gone\gone\gone with |DataDirectory|. See modified connection string as below:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Youssef\Desktop\gone\gone\gone\gestion_incidents.mdf;Initial Catalog=BG_ONE;Integrated Security=True

Visual Studio Online Build - web.config connection strings configSource

My project Web.config has connection strings defined in a separate file using the following construct:
<connectionStrings configSource="ConnectionStrings.config">
</connectionStrings>
This is handy when collaborating on a project or when deploying the project. However, I was unable to get the VSO Build working as it shows me the following error:
C:\Program Files
(x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets (4105,
5) Could not copy the file
"C:\a\1\s\MyProject\ConnectionStrings.config" because it was not
found.
The connection string must be already defined in the web.config and the connection string name must be the same as the connection string name you set in Azure. Then the connection string can be updated by Azure. Refer to the description from Azure:
Connection strings work in a similar fashion, with a small additional
requirement. Remember from earlier that there is a connection string
called “example-config_db” that has been associated with the website.
If the website’s web.config file references the same connection string
in the configuration section, then Windows Azure
Web Sites will automatically update the connection string at runtime
using the value shown in the portal.
However, if Windows Azure Web Sites cannot find a connection string
with a matching name from the web.config, then the connection string
entered in the portal will only be available as an environment
variable (as shown earlier).
And
Remember though that for Windows Azure Web Sites to override a
connection string and materialize it in the .NET Framework’s
connection string configuration collection, the connection string must
already be defined in the web.config. For this example website, the
web.config has been updated as shown below:
For more information, please see this link: https://azure.microsoft.com/en-us/blog/windows-azure-web-sites-how-application-strings-and-connection-strings-work/
I know you already mark your question answered but I think I should post my solution here for anyone's having same issue.
I create a transformation for the connectionStrings section in other environment with a dummy connectionstring value like this:
<connectionStrings xdt:Transform="Replace">
<add name="Your_ConnectionString_Name" connectionString="dummy_value"
providerName="System.Data.SqlClient" />
</connectionStrings>
so that I can keep the configSource attribute in my local machine and when I deploy to other environments, I have some dummy connectionstring for Azure to replace.

Formatting MySQL initialization string? [duplicate]

I have an ASP.Net MVC application which runs fine on my local development machine. But when deployed to IIS7 gives the following error when trying to log in:
Format of the initialization string does not conform to specification
starting at index 0
Most people who post this error resolve it by changing their connection string in some way. However my connection string on the local and deployed application are the same. The connection string is like this:
<add name="ApplicationServices" connectionString="Data Source=*server*\*instance*;Initial Catalog=*database*;Integrated Security=True;"
providerName="System.Data.SqlClient" />
What is causing this error in my case?
Format of the initialization string does not conform to specification
starting at index 0
Web.config :
<connectionStrings>
<add name="TestDataConnectionString" connectionString="Data Source=.\SQLExpress;Initial Catalog=TestData;User ID=satest;Password=satest"
/>
</connectionStrings>
In aspx.cs Page the code must be written in the below format :
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["TestDataConnectionString"].ToString());
Web Deployment tool created wrong line in config when I checked Enable CodeFirst Migrations check-box.
In my case I accidentally wrote "password:" instead of "password=" in my conn string
Check to make sure the credentials are correct for the connection string in Web.config. Mine was missing the password for the account with permissions to the database.
I encountered the same error. In my case it was the config transform not working properly.
There is an issue with config transforms when it comes to connection strings.
Some reference:
MSBuild web.config transforms not working by drneel
Replaceable token issue with config ConnectionString transforms by Francis
Also one can write the code in the aspx.cs page as
using (IDbConnection dbConnection =
new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
// TODO: Write SQL Stored Procedures or SQL Statements using Dapper
}
For those who would like to find out more about Dapper.
Hope this helps.
If you have been using the Visual Studio Publish Wizard for deployment and checked the Execute Code First Migrations check box in Settings, a new ConnectionString is automatically added to the Server Web.config file, similar t to the 2nd line below:
<add name="LCWeb3Context" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=LCWeb3;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\LCWeb3.mdf" providerName="System.Data.SqlClient" />
<add name="LCWeb3Context_DatabasePublish" connectionString="LCWeb3Context_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient" />
First, notice the added connection string contains "ConnetionString": I think it should be "ConnectionString"! But that's not the solution.
To avoid the "Format of the initialization string does not conform to specification starting at index 0" error, do the following in the Publish Wizard:
In the Settings, select Configuration: Release
In the Settings,don't forget to paste your Connection String in the
"Remote Connection String" field
In the Settings, check Execute Code First Migrations
When doing the above, the connection string added to the Server Web.config reads:
<add name="LCWeb3Context_DatabasePublish" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LCWeb3.mdf;Initial Catalog=LCWeb3;Integrated Security=True" providerName="System.Data.SqlClient" />
and the "Format of the initialization string does not conform to specification starting at index 0" error no longer occurs.
I has the same issue, when I use command: "Update-Database" in Package Manager Console.
To Fix, make sure set startup project to the project which you want to do update.
E.g. I got Db project and Web project, make sure set startup project on Db project, when run "Update-Database", otherwise, it will try to search inside Web project.
The permissions on the SQL server were not correctly set up. I have now resolved this by properly setting up the server permissions.

ConfigurationManager keeps getting Machine.config connection string

I have a c# assembly that uses the app.config to store its database connection string. When debugging the application I noticed that the connection to the database kept failing because the ConfigurationManager kept returning the machine.config connection string:
data source=.\SQLEXPRESS; Integrated Security;....
I added <clear/> before my connection string in the app.config and it fixed the issue on my dev machine. The problem returned when I deployed it to production. Can someone tell me how I can stop the machine.config connection string from being used?
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
<connectionStrings>
<clear/>
<add name="VersionConnectionString"
connectionString=" Data Source=localhost;Initial Catalog=VersionInfo;User ID=user;Password=password"
providerName="System.Data.SqlClient" />
</connectionStrings>
UPDATE
The following still gives me the machine.config connection string?!
Configuration appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
string dllConfigData =
appConfig.ConnectionStrings.ConnectionStrings[0].ConnectionString;
When using connection strings in a DLL, you need to add them to your exe's app.config as well, using the exact same name for the setting. Then, you can change the connection string in the exe's .config file and the DLL will pick it up automatically when loaded.
This is probably the only way you can have working custom connection strings in the app.config file when your DB persistence layer is implemented in a separate DLL. Don't even ask me how much time it took me to research and debug this.
I know this is an older question, but I was having the same problem today. The problem was that the app.config that I added to my project wasn't being copied to the output directory. To fix this, right click on the app.config and select Properties. Then change Build Action to Content.
Hope this helps!
Try getting an instance of your app.config file as a Configuration object:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var myConnString = config.ConnectionStrings["VersionConnectionString"].ConnectionString;
This bypasses the machine config file completely.
You should be getting your connection string by NAME instead of INDEX - that will ensure you're getting what you're asking for.
Try
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["VersionConnectionString"].ConnectionString);

Categories