Deploying MVC 4 CodeFirst to Azure - asp.net-mvc

I'm trying a 90 day free trial of azure. It is super easy to deploy/publish the website and create the database, but for some reason my tables are not being created in the database. I'm using entity framework 4.4(i believe) and code first migrations. I've read that azure uses its own connection string, but I went ahead and changed my connection strings as well. I Spent hours on this and I can't figure out what is wrong and why my tables are not being created. I deploy website, enable-migrations, add-migration, update-database, then publish with checking the checkbox for code-first. Maybe my connection string is wrong? Any help is greatly appreciated.
In 'MyProject.Web' web.config:
<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=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=tcp:n98my***.database.windows.net,1433;Initial Catalog=slutips_db;User Id=****;Password=****;" />
</connectionStrings>
Then in 'MyProject.Data' app.config, where my datacontext.cs is held:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<contexts>
<context type="SeluCmpsTutorials.Data.DataContext">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion">
<parameters>
<parameter value="slutips_db"/>
</parameters>
</databaseInitializer>
</context>
</contexts>
</entityFramework>
Also I noticed even though all my connection strings are changed, when I add-migration and update-database, it still using the ./sqlexpress local database, how is that possible?

key gotcha to be aware of regarding sql azure connections: for userid it actually usually needs to be user id # server name - do would read youruserid#n98my*** in the connectionstring.
Also, not sure if you need the "tcp:" (not using it) and you may also want to add providerName="System.Data.SqlClient"

Does your db user have necessary permissions for database modification ?
How did you set up your user ?
Initially you should create login for Azure sql server, sometihing like this:
(execute following sql on your server master database, replace angle-brackets values with actual values)
CREATE LOGIN [<SomeServerLogin>] WITH PASSWORD=N'<somepassword>'
Then connect to your slutips_db database as admin and execute following sql
CREATE USER [<slutips_db_user>] FROM LOGIN [<SomeServerLogin>];
GO;
EXEC sp_addrolemember 'dbmanager', '<slutips_db_user>';
GO;
EXEC sp_addrolemember 'loginmanager', '<slutips_db_user>';
GO;
'dbmanager' role allows table creation\management.
'loginmanager' role enables creation of another users in current database (your slutips_db_user will be allowed to execute CREATE USER <slutips_db_user1> FROM LOGIN <SomeServerLogin1> clause
Edit1: Also - ensure that your connection string user have user#n98my*** (user#server) format.

If you follow this tutorial: https://www.windowsazure.com/en-us/develop/net/tutorials/web-site-with-sql-database/ It'll show you how to connect Visual Studio (2012 in the example, not sure if works for any others) with Azure - basically you want to log into the portal, and download the publishing credentials. This will contain your database connection string, which you can then use to push code first migrations up to Azure.
What it looks like you've done is manually added in properties to the app.config yourself. The way the publish works, it defines a local version in your .config file like thus:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
Then, when you publish, VS will auto-magically insert the required stuff into your .config - if I go and FTP to my web site and look at the generated .config file, you see this:
<contexts>
<context type="Web_App.Models.TrackSafeDb, Web App">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[Web_App.Models.TrackSafeDb, Web App], [Web_App.Migrations.Configuration, Web App]], EntityFramework, PublicKeyToken=*******************">
<parameters>
<parameter value="Web_App.Models.TrackSafeDb_DatabasePublish" />
</parameters>
</databaseInitializer>
</context>
</contexts>
So I'd try removing the extraneous stuff from your local app.config and re-publishing

Try adding encryption to your connection string...
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=tcp:n98my***.database.windows.net,1433;Initial Catalog=slutips_db;User Id=****;Password=****;Integrated Security=False;Persist Security Info=True;Encrypt=True" />
</connectionStrings>

what i did was go to my azure management portal.
clicked on databases.
went view connection strings and then copied those directly into my relevant config.
in my case its "release" config.
make sure that the web config transformations are enabled and working correctly.
also make sure you've enabled firewall access to each of the db's...
you have to click "enable connection through firewall" or something similar.
its in the db options on the portal.

After seeing this question for a few days, a couple of thoughts. First, is the name of your context is infact DefaultConnection. Entity Framework (in order to be used with the parameterless constructor) likes the connection string name to match the name of the context.
For instance, if your declare a new context variable as such:
var context = new MyEntities();
Then your connection string should be called MyEntities
<connectionStrings>
<add name="MyEntities" connectionString="Data Source=tcp:n98my***.database.windows.net,1433;Initial Catalog=slutips_db;User Id=****;Password=****;" />
</connectionStrings>
Second, are you 100% sure that there are no web.config transformation files and/or that you also properly updated the connection strings in those files?
Third, remember that upon deployment, any configuration file other than the web.config is essentially ignored. The executing assembly is the web application, not the data project or any others. Any configurations relating to EF setup and deployment should be located in the web.config file (like the snippet that you have in your data app.config)

I had the exact same problem and it was linked to my password containing '%' character.
I checked the resulting web.config on Azure connecting with ftp and the part of my password containing '95%a' turned to '95ยช' ... automagically. That might be a bug in the web deployment feature of azure, because the password was correct in my publish profile locally.
If indeed the resulting password to the DB is corrupted in the resulting connection string, you have to reset it :
From Windows Azure Management, in the SQL DATABASES tab, select the SERVERS list (not the DATABASE list) and click on your server
In the Dashboard, there is a link to reset the admin password
In visual studio, update the password in your publish profile's connectionString (Settings, Databases)
Make a change to the web.config (a real one, not a comment), or it won't be re-published
Publish, and on first use of the database, the migrations will be applied

Related

Store user name and password with neo4j connection string

What is the format (if any) for adding user name and password to neo4j v4 connection strings? So far, I've seen just examples like bolt://localhost:7010 with authentication being added as extra arguments to the connection calls.
Here's why I'm asking:
I have an ASP.NET app which connects to both MS SQL and neo4j DBs. For MS SQL, I can add the connection string to the /configuration/connectionStrings in web.config formatted like this
<add name="MyDB" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyDB;UID=user;PWD=pwd" />
or
<add name="MyDB" connectionString="Data Source=.,1433;Initial Catalog=MyDB;UID=user;PWD=pwd" />
It contains host name, instance name or port name, plus the credentials. I can then encrypt the connectionStrings part of web.config using standard IIS tools.
For ease of management, I'd like to reuse it for neo4j connection strings as well. I could store the string in MSSQL-like format
<add name="MyNeo4jDB" connectionString="Data Source=.,7010;UID=user;PWD=pwd" />
but I don't want to invent my own format.
Thanks

VS 2017 does not opens .edmx files in proper visual designer

EF Database models (.edmx) files are not opening in special VS EF data model designer. Just standard XML editor is working. All happening in VS2017 at win 10 (64).
Here is the declaration of the EDMX file
<Edmx Version="3.0" xmlns="http://schemas.microsoft.com/ado/2009/11/edmx">
This is the line where I have the issue
<Schema Namespace="CodeFirstDatabaseSchema" Provider="System.Data.SqlServerCe.4.0" ProviderManifestToken="4.0" Alias="Self" xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl"`>
I have this problem:
"Severity Code Description Project File Line Suppression State Error Error 175: The ADO.NET provider with invariant name 'System.Data.SqlServerCe.4.0' is either not registered in the machine or application config file, or could not be loaded. See the inner exception for details. SmartStore.Web D:\Dev\HMZ\RC5.0\builds\SmartStoreNET-3.x\src\Presentation\SmartStore.Web\App_Data\EfCache\SmartStore.Data.SmartObjectContext.edmx 5552"
most of the solutions found on the web won't work.
Please, people, help me with this. So terrible, experience. I'm trying to solve this problem 3-4 days.
I tried most of those answers I could find over the web: like updating/re-installing the SQL Compact, editing web.config provider factories, and etc.
Web Config (MVC 5/.NET 4.7.2)
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.111.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
</DbProviderFactories>
<!-- Add the attribute 'codeConfigurationType' to the 'entityFramework' root element to overwrite the global DbConfiguration -->
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
According to the Error you edited above:
'System.Data.SqlServerCe.4.0' is either not registered in the machine or application config file, or could not be loaded.
it can be a good idea to remove the dll for System.Data.SqlServerCe and add it again:
install Microsoft SQL Server Compact 4.0
Right click the References folder and select Add Reference... option.
Go to the Assemblies | Extensions option on the left pane, then scroll to System.Data.SqlServerCe in the right pane. (or through the Browse button go to the installation directory and select the dll)
You might try these 3 solutions:
Firstly, you can use one of the online XML parsers (eg. https://onlinexmltools.com/validate-xml) to make sure the XML is correct. If any errors exist, removing that section will fix the issue and the model will be shown after Clean and Rebuild.
right-click the edmx file-> choose Open with->choose ADO.NET Entity Data Model Designer
You can also fix it by deleting the file and regenerating it again.
On the Visual Studio Installer, Click Modify, Select Individual Components tab, and make sure Entity Framework Under SDKs, libraries, and framework check-box is selected. Make sure you re-start visual studio.

MVC Controllers - Connection String / associations - No Connection String could be found in the application config file

Please excuse me is this is a noob question. I have a MVC project with a number of EF Database first models. When I created them some were created with new connection strings.
I have tried to clean up the project web.config file and commented out the duplicated connection strings,
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=........... />
<add name="DB_A09819_ProductsEntities" connectionString="metadata=........... />
<add name="DB_A09819_PowerDB001Entities" connectionString="metadata=........... />
<!--
<add name="DB_A09819_ProductsEntities_IntranetDownload" connectionString="metadata........... />
<add name="DB_A09819_ProductsPricing" connectionString="metadata=........... />
<add name="DB_A09819_ProductsProjectProposal" connectionString="metadata=.......... />
<add name="DB_A09819_ProductsProposalSystem" connectionString="metadata=........... />
-->
</connectionStrings>
I had thought that MVC would have picked up on the changes and raised errors, however with these changes the project builds and runs on development server.
When I try to add a controller I now get an error that the
---------------------------
Microsoft Visual Studio
---------------------------
Error
There was an error running the selected code generator:
'Unable to retrieve metadata for 'web...............t'.
No connection string named 'DB_A09819_..........'
could be found in the application config file.'
---------------------------
OK
---------------------------
I would like to change the associations and fix the connection string to have a single connection to each of the databases.
There are a number of posts where the solution is to add a connection string, I am trying to clean up my code and remove duplicate connection strings.
How do I change the association to the connection string in the Model and the controllers to ensure that it will run when deployed ?

MVC .Net can't get it to stop trying to recreate tables

I had migrations enabled - however, now I'm moving to the live server, it appears migrations are still trying to update the database, as I get the error:
CREATE TABLE permission denied in database 'secn'.
I have this in a context file in my models folder:
namespace lhts2.Models
{
public class DefaultConnection : DbContext
{
public DefaultConnection() : base("name=DefaultConnection")
{
Database.SetInitializer<DefaultConnection>(null);
}
}
}
...and in my web.config file, my connection string is:
<add name="DefaultConnection" connectionString="Data Source=[servername];
Initial Catalog=secn; Integrated Security=True;" providerName="System.Data.SqlClient" />
I have deleted the Migrations folder too, and republished - but still I get the error above.
I also have this in my web.config file:
<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>
<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>
Do I need to set the SetInitializer in some other place, other than in the context file in my models folder?
Thanks for any advice,
Mark
From here:
...the initializer should have been set in the static constructor of your context. The static constructor is called before any constructors and is executed once. This is what we want. The reason is that in some of your application, you may initialize more than once the context. You do not want to execute all the process to check if the database if ready to be changed or not.
So, you should change your class to have a static constructor that is only called one time.
namespace lhts2.Models
{
public class DefaultConnection : DbContext
{
static DefaultConnection()
{
Database.SetInitializer<DefaultConnection>(null);
}
public DefaultConnection() : base("name=DefaultConnection")
{
}
}
}
I had the same issue. Setting the IIS user to a "sysad" level user allowed the application to work normally. However that is not a secure method of solving the problem.
Further research revealed that the "migrations" table (named dbo.__MigrationHistory) was the culprit. I had given the IIS user access (Select, Update, Delete, Insert, and References) to all the "application" tables, but not the "migrations" table. Consequently when the application runs and attempts to determine if a migration is necessary, the access fails because of the lack of access rights for that user and the application thinks it needs to create the database and tables - which this user clearly should not have rights to do.
By providing normal access rights to the __MigrationHistory table (Select, Update, Delete, Insert, and References) the IIS user was now able to determine that no migration was necessary and therefore did not attempt to conduct a migration.
Example of Permission Settings Here

MVC Entity Framework connection string references other project

I'm doing a Model first approach for a Microsoft MVC application. The solution is named "TutorialPile" divided into two projects, Domain and WebUI. I try to add a controller for the Tutorial object to the WebUI project, and I select the domain class and the DB context. However, I get the error, "Unable to retrieve metadata for TutorialPile.Tutorial. Unable to load the specified metadata resource."
Looking around online it looks like it can't find the edmx object in the connection string in the web.config file. I copied the connection string from the Domain project's app.config file but it still doesn't work. Here are the connection strings from the web.config file.
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="TutorialPileModelContainer" connectionString="metadata=res://*/Models.TutorialPileModel.csdl|res://*/Models.TutorialPileModel.ssdl|res://*/Models.TutorialPileModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=TutorialPileDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="TutorialPileDbContext" connectionString="metadata=res://*/Models.TutorialPileModel.csdl|res://*/Models.TutorialPileModel.ssdl|res://*/Models.TutorialPileModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=TutorialPileDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
And here is the connection string that I copied.
<add name="TutorialPileDBEntities" connectionString="metadata=res://*/TutorialPile.csdl|res://*/TutorialPile.ssdl|res://*/TutorialPile.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=TutorialPileDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Any ideas on what I need to change?
Make sure...
the edmx file's build action is set to EntityDeploy (select the file and go to the properties window).
Your WebUI project references the Domain project
Edit the connection string on your WebUI project to reference the metadata from the other project. Using * means it can come from any dll. BUT, if your edmx file is inside a folder, you have to map the hierarchy.
Eg:
Path to EDMX: TutorialPile.Domain/Model/TutorialPile.edmx
Connection string: res://*/Model.TutorialPile.csdl|res://*/Model.TutorialPile.ssdl|res://*/Model.TutorialPile.msl
Even better:
The documentation suggests you specify the assembly (for performance reasons) using the full name of the assembly (something like: AdventureWorks, 1.0.0.0, neutral, a14f3033def15840). I couldn't make it work. But, using only the name of the assembly works for me. So, if your domain project outputs a TutotialPile.Domain.dll, you can use:
res://TutorialPile.Domain/Model.TutorialPile.csdl|res://TutorialPile.Domain/Model.TutorialPile.ssdl|res://TutorialPile.Domain/Model.TutorialPile.msl

Resources