How do I set an ADO.NET Entity Framework connection string via the Windows Azure (Preview) Management Portal? - entity-framework

In the Windows Azure (Preview) Management Portal you can change the configuration options for web sites (see http://www.windowsazure.com/en-us/manage/services/web-sites/how-to-configure-websites/#howtochangeconfig).
I currently set the connection string for my ADO.NET Entity Framework connection via Web.Release.Config, but I want to set it via the Management Portal, but no matter what I use, I always end up with the following error:
The specified named connection is either not found in the
configuration, not intended to be used with the EntityClient provider,
or not valid.
It does work for regular connection strings, ie without the metadata key defining metadata and mapping information (csdl, ssdl, msl).
Here's what I do:
I go to https://manage.windowsazure.com/#Workspaces/WebsiteExtension/Website/[MY-STAGING-SITE-NAME]/configure
Under "connection strings" I have a key named "ApplicationServices" that looks like this:
Server=tcp:xxxxx.database.windows.net,1433;Database=xxxxx;User
ID=xxxxx#xxxxx;Password=xxxxx;Trusted_Connection=False;Encrypt=True;Connection
Timeout=30;
This one works.
I have another key for the Entity Framework connection. Let's call that one FooBarContext. It looks like this:
metadata=res:///Models.FooBarContext.csdl|res:///Models.FooBarContext.ssdl|res://*/Models.FooBarContext.msl;provider=System.Data.SqlClient;provider
connection
string="Server=tcp:fooserver.database.windows.net,1433;Database=foobar;User
ID=myname#fooserver;Password=xxxxxxxxxx;Trusted_Connection=False;Encrypt=True;Connection
Timeout=30;"
This one causes the error described above. It is copied from the working value in Web.Release.Config, with the " replaced by a ".
I have tried other variations: with the " untouched, with metadata appended at the end, but to no avail. I have reproduced the problem with a second website.

The solution for my problem was selecting "Custom" instead of "SQL Azure" from the "SQL Azure / SQL Server / MySQL / Custom" selector for the Entity Framework connection string, even though the database does run on SQL Azure.
[Edit] From a popular comment by #matthew-steeples below:
I would add to this for anyone else having the same issue is that
sometimes the config file will have " instead of ", and the Azure
Websites needs those to be changed to "

Replace
"
with
"
In the connection string.

Not only did I have to use double quotes (or single quotes) instead of " (and select Custom for the type) but I also had to make sure there was a dummy value in my transform config. I was replacing the entire connectionStrings node, but decided to keep that and add this:
<add xdt:Transform="Replace" xdt:Locator="Match(name)" name="FooBarEntities" connectionString="temp" providerName="System.Data.EntityClient" />
Without this, I was getting the following error:
The connection string 'FooBarEntities' in the application's configuration file does not contain the required providerName attribute.

Beside answers above, there are 2 very important things:
You should remove "name=" from "name=connectionString"
in constructor:
public MyEntities(string connectionString)
: base($"name={connectionString}")
{
}
You should leave "duplicate" of connection string in app.config, but
replace connection string with dummy text, correct connection string
will be loaded from Azure. That's needed for providerName part.
Please read:
https://mohitgoyal.co/2017/07/05/update-connection-string-for-entity-framework-in-azure-web-app-settings/comment-page-1/

I had the same problem. I solved, putting in the web.config this connectionstring:
<add name="eManagerTurModelConnection" connectionString="metadata=res://*/ORM.eManagerFinanceModel.csdl|res://*/ORM.eManagerFinanceModel.ssdl|res://*/ORM.eManagerFinanceModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=<server>.database.windows.net;Initial Catalog=eManagerTur;Integrated Security=False;User ID=<user>;Password=<Password>;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
And after I removed the connectionstring of my website, worked, because it was not getting the connection string that I added in my web.config.
English bad... =)

Related

mongo-csharp-driver 2.0 / nservicebus.mongodb 2.1 can no longer connect to Mongo

We recently updated our NserviceBus.MongoDb package from 2.0.3 to 2.1. This also updated the mongo-csharp-driver package from 1.10 to 2.0.1. We now see the following exception when the service starts:
2015-07-08 11:29:16,589 [1] WARN NServiceBus.MongoDB.Internals.MongoHelpers [(null)] <(null)> - Mongo could not be contacted using: server201.localco.test:27017.
If you are using a Replica Set, please ensure that all the Mongo instance(s) server201.localco.test:27017 are available.
To configure NServiceBus to use a different connection string add a connection string named "NServiceBus/Persistence" in your config file.
Reason: System.InvalidOperationException: There is no current primary.
at MongoDB.Driver.MongoServer.Ping()
at NServiceBus.MongoDB.Internals.MongoHelpers.VerifyConnectionToMongoServer(MongoClientAccessor mongoClientAccessor) in d:\Development\NServiceBus.MongoDB\src\NServiceBus.MongoDB\Internals\MongoHelpers.cs:line 50
The only relevant line in our nservicebus endpoint config is:
configuration.UsePersistence<MongoDBPersistence>();
and our connection string is:
<add name="NServiceBus.Persistence" connectionString="mongodb://server201.localco.test/?replicaSet=rs0" />
If I uninstall/rollback 2.1/2.0.1 to 2.0.3/1.10 (nservicebus.mongodb/mongo-csharp-driver) the error goes away.
Update: I see that the database itself (with a TimoutData collection) is actually created in Mongo...
Change your connection string from
<add name="NServiceBus.Persistence" connectionString="mongodb://server201.localco.test/?replicaSet=rs0" />
to
<add name="NServiceBus/Persistence/MongoDB" connectionString="mongodb://server201.localco.test/?replicaSet=rs0" />
or leave it like above and set the name to
config
.UsePersistence<MongoDbPersistence>()
.SetConnectionStringName("NServiceBus.Persistence");
Latest version of the package from Github/Nuget has addressed this issue. See bug report

Mobile Services (.Net backend) using incorrect connection string

I am struggling to make the .Net backend of Mobile Services use the correct connectionString. When I publish the service I select the correct connection string for "MS_TableConnectionString". If I check the web.config on the server (via FTP) I see what I would expect:
web.config on server:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source=tcp:[ServerAddress].database.windows.net,1433;Initial Catalog=[MyMobileService_db];Integrated Security=False;User ID=[correctUserName];Password=[CorrectPassword];Connect Timeout=30;Encrypt=True" providerName="System.Data.SqlClient" />
In my context it is configured to use a connection string called MS_TableConnectionString:
private const string connectionStringName = "Name=MS_TableConnectionString";
public MyMobileServiceContext() : base(connectionStringName)
{
Schema = "MyMobileService";
}
To see what connection string is actually being used I added this to an example controller:
Example Client Code:
public class ExampleController : ApiController
{
MyMobileServiceContext context;
public ApiServices ApiServices { get; set; }
public ExampleController()
{
context = new MyMobileServiceContext();
}
public async Task<IHttpActionResult> PostExample(ExampleItem item)
{
ApiServices.Log.Warn("ConnectionString: " + context.Database.Connection.ConnectionString);
...
}
And when I look at the Log Entry on Mobile Services I see a different UserName and Password:
[2014-04-15T12:26:33.1410580Z] Level=Warn, Kind=Trace, Category='PostExampleItem', Id=00000000-0000-0000-0000-000000000000, Message='ConnectionString: Data Source=[SameServerAddress].database.windows.net;Initial Catalog=[SameDatabaseName];User ID=[DifferentUserName];Password=[DifferentPassword];Asynchronous Processing=True;TrustServerCertificate=False;'
The different username and password are the same as I see in the original .PublishSettings file that I downloaded under the name of SQLServerDBConnectionString but I have no idea where this is stored on the server?
Because of the different username and password I see the following exception in the log:
[2014-04-15T13:18:11.2007511Z] Level=Error, Kind=Trace, Category='App.Request', Id=d7ec6d25-f3b7-4e88-9024-217be40ae77f, Exception=System.Data.Entity.Core.ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure. ---> System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: Cannot open database "master" requested by the login. The login failed.
Login failed for user '[DifferentUserName]'.
This session has been assigned a tracing ID of '[GUID]'. Provide this tracing ID to customer support when you need assistance.
Any help would be much appreciated as at the moment I am having to hard code the whole connection string in the constructor of the Context to make it work.
Thanks
F
UPDATE: 15th April 2014 15:23
I deleted all my publisher profiles and created a copy of the original .PublishSettings file. From this I deleted all but one profile. I then deleted the SQLDBConnectionString attribute to confirm that it is not because I was sending this that was causing the problem. The result was no change, it is still using the DifferentUserName and Password so it must be reading it from the server somewhere.
We have a hole at the moment in that we pick up the connection string from the portal yet don't expose the ability to set or modify connection strings there.
The work-around is to set an application setting in the portal and then use that in your code using the ApiServices class, something like this (in your controller)
string connectionString = this.Services.Settings["YourConnectionStringAsAppSetting"];
I know it is confusing... we'll make it easier to access and modify the connection strings.
Henrik

connectionString in Entity Framework

I am stuck. I have spent nearly a day to solve but to no avail.
PROBLEM: Connecting to production database using entity framework.
I connect fine on development.
<add name="DefaultConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MONDO;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MONDOEntities" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;Initial Catalog=MONDO;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
Moving to production, I used (from the production web.config file) the existing "DefaultConnectionString" parameters (ID and Password) to edit the MONDOEntities connectionString. (can I do this?) Also, I expanded the metadata in MONDOEntities to include .csdl, .ssdl, .msl and I prefixed it with (guessing, again, can I do this?) MONDO. Bold parts are changes from dev web.config to production web.config. *Note, the connectionStrings below were not created by Visual Studio, I just changed some info myself to try and make it work on the production side.
<add connectionString="Data Source=MPOC\SQLEXPRESS;Database=Mondo;User ID=xxx;Password=xxxxx;" name="DefaultConnectionString" />
<add name="MONDOEntities" connectionString="metadata=res://*/MONDO.csdl|res://*/MONDO.ssdl|res://*/MONDO.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MPOC\SQLEXPRESS;persist security info=True;Database=Mondo;User ID=xxx;Password=xxxxx;MultipleActiveResultSets=Tru e;App=EntityFramework"" providerName="System.Data.EntityClient" />
The error message I get is:
Unable to load the specified metadata resource.
Line 62: /// Initializes a new MONDOEntities object using the connection string found in the 'MONDOEntities' section of the application configuration file.
Line 63: /// </summary>
Line 64: public MONDOEntities() :
QUESTION: Can I simply modify the connectionStrings manually or does it need to run through a compilation process? It is a website project so it compiles, on the fly, the first time after I upload to production. It does not get precompiled on my local dev computer. I guess, bottom line, how do I set up a proper connectionString for an entity connection for a database in production?
I'm on a project where I need to learn an existing website. I'm making my first bug fix and having learned ado.net, I created an entity data model and made some code changes. Everything works smooth in development.
I move the files to production and then I get this error:
"The specified default EntityContainer name 'MONDOEntities' could not be found in the mapping and metadata information.
Parameter name: defaultContainerName"
I googled this error message and based on some findings, I expanded my "metadata" shown below. This was more of a shot in dark for me:
ORIGINAL (auto generated in web.config when I created the entity data model):
connectionString="metadata=res://*
NEW (I edited/added this):
connectionString="metadata=res://*/MONDO.csdl|res://*/MONDO.ssdl|res://*/MONDO.msl;
This seemed to get past the first error and I get to a new error message (as posted in OP):
Unable to load the specified metadata resource.
Line 62: /// Initializes a new MONDOEntities object using the connection string found in the 'MONDOEntities' section of the application configuration file.
Line 63: /// </summary>
Line 64: public MONDOEntities() :
I think that there is a problem with my metadata information. However, given that the original, auto generated connectString only contains "metadata=res://*", I really don't know how to go about correcting this. Actually, I'm not even super sure that this is the root of the problem.
Bottom line, my entity model works smooth in dev but isn't connecting in production. Any thoughts are appreciated ... thanks.
The connection string has nothing to do with compilation, as long as you didn't define some transformation to be performed on it or you have some custom hooks that operate on it.
So yeah, you can modify it by hand.
You probably got those metadata wrong, try and play with them (EG removing the prefix).
Also are you absolutely sure that, in your production environment, the right connectionString is being loaded and used by the MONDOEntities?

Format of the initialization string does not conform to specification starting at index 0

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.

How does one indicate the "default" connection string for Enterprise Library?

I hant to be able to call DatabaseFactory.CreateDatabase(), i.e. with no parameter to indicate which connection string to pull from my config file. I only have one connection string in my config file. The only help I have found on the internet is instructions to indicate the default connection string using the Enterprise Library Configuration tool (by right-clicking on my config file in Visual Studio). But from there, I see no way to "select" a connection string or mark it to be the default.
YOu should define the dataConfiguration section in your config
<configuration>
<configSections>
<section name="dataConfiguration" ...
And then set the value
<dataConfiguration defaultDatabase="ConnectionStringName" />