Azure database works on localhost, but not when used with azure service app - entity-framework-core

So I've been trying to publish my first project to azure. I've got everything set-up, a service app and a sql database.
My initial page loads properly(It's the standard view for a .net core web application).
The first thing I need to do is register a new user. Whenever I try through my azure app (myapp.azurewebsites.net) it fails and the logs says it's db related.
However I try the same thing by running the application on my machine in production environment, again connected to the azure sql server and everything works perfectly. I can register users, I can create posts, I can edit them. The allow access to azure services option is turned on. This error is from the eventlogs. I have not included the stacktrace.
Category: Microsoft.EntityFrameworkCore.Query EventId: 10100 RequestId: 800001be-0000-ba00-b63f-
84710c7967bb RequestPath: /Identity/Account/Register SpanId: |1e5a93ae-43f424904f38ea9f. TraceId:
1e5a93ae-43f424904f38ea9f ParentId: ActionId: c3430236-e61c-4785-a3c3-4f60ba115b6e ActionName:
/Account/Register An exception occurred while iterating over the results of a query for context type
'MyApp.Data.ApplicationDbContext'. Microsoft.Data.SqlClient.SqlException (0x80131904): Server
name cannot be determined. It must appear as the first segment of the server's dns name
(servername.database.windows.net). Some libraries do not send the server name, in which case the
server name must be included as part of the user name (username#servername). In addition, if both
formats are used, the server names must match.
Those are the different ways I tried to add the connection string to the appsettings.json file. (Server name, catalog, user and password have been replaced, they are written correctly in the appsettings file)
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user#server;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Data Source=tcp:server.database.windows.net,1433;
Initial Catalog=db;User Id=#server.database.windows.net;Password=password;

Alright so after a day and a half, I finally managed to fix it. The solution is rather simple and it is most likely my newbie mistake, that caused so much trouble.
I was following a tutorial for setting up the application and database connection after that. In the tutorial, the connection string that was being used, was the default one, found in the "myApp -> Configuration -> Connection strings", the format was:
Data Source=tcp:server.database.windows.net,1433;
Initial Catalog=db;User Id=#server.database.windows.net;Password=password;
This one was working in the guide, but not for me. So what I did, was go to my "sqldb -> connection strings" and copied the one provided there. I then went back to the app configuration and added it as a new configuration string using SqlServer as the Type.
This string was in the format:
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
After that, the app started working properly.

Related

Newbie help - how to connect to AWS Redshift cluster (currently using Aginity)

(I'm afraid I'm probably about to reveal myself as completely unfit for the task at hand!)
I'm trying to setup a Redshift cluster and database to help manage data for a class/group project.
I have a dc2.large cluster running with either default options, or what looked like the most generic in the couple of place I was forced to make entries.
I have downloaded Aginity (Win64) as it is described as being specialized for Redshift. That said, I can't find any instructions for connecting using it. The connection dialog requests the follwoing:
Server: using the endpoint for my cluster (less :57xx at the end).
UserID: the Master username for the database defined for the cluster.
Password: to match the UserID
SSL Mode (Disable, Allow, Prefer, Require): trying various options
Database: as named in cluster setup
Port: as defined in cluster setup
I can't get it to connect ("failed to establish connection") and don't know if I'm entering something wrong in Aginity or if I haven't set up my cluster properly.
Message: Failed to establish a connection to 'abc1234-smtm.crone7m2jcwv.us-east-1.redshift.amazonaws.com'.
Type : Npgsql.NpgsqlException
Source : Npgsql
Trace : at Npgsql.NpgsqlClosedState.Open(NpgsqlConnector context, Int32 timeout)
at Npgsql.NpgsqlConnector.Open()
at Npgsql.NpgsqlConnection.Open()
at Aginity.MPP.Common.BaseDataProvider.get_Connection()
at Aginity.MPP.Common.BaseDataProvider.CreateCommand(String commandText, CommandType commandType, IDataParameter[] commandParams)
at Aginity.MPP.Common.BaseDataProvider.ExecuteReader(String commandText, CommandType commandType, IDataParameter[] commandParams)
--- Inner Exception: ---
......
It seems there is not enough information going into Aginity to authorize connection to my cluster - no account credential are supplied. For UserID, am I meant to enter the ID of a valid user? Can I use the root account? What would the ID look like? I have setup a User with FullAccess to S3 and Redshift, then entered the UserID in this format
arn:aws:iam::600123456789:user/john
along with the matching password, but that hasn't worked either.
The only training/tutorial I have been able to find/do on this is the Intro AWS direct you to, at https://qwiklabs.com/focuses/2366, which uses a web-based client that I can't find outside of the tutorial (pgweb).
Any advice what I am doing wrong, and how to do it right?
Well, I think I got it working - I haven't had a chance to see if I can actually create table yet, but it seems to be connected. I had to allow inbound traffic from outside the VPC, as per the above snapshot.
I'm guessing there's a better way than opening it up to all IP addresses, but I don't know the users' (fellow team members) IPs, and aren't they all subject to change depending on the device they're using to connect?
How does one go about getting inside the VPC to connect that way, presumably more securely?

SQL Azure EF Database First Connection String in Azure Management Portal

I have a site running n Azure, which uses EF Database First model.
If I embed the connection string in the web.config and deploy all is rosy.
<add name="MyEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string='Data Source=my.database.windows.net;Initial Catalog=myTest_DB;User ID=***;Password=***; MultipleActiveResultSets=False'" providerName="System.Data.EntityClient"/>
But, I don't want the connection string in the web.config because it contains credentials.
So I moved it to the connection string area in Azure Properties.
First issue I hit is getting metadata invalid keyword error.
I solved that by changing the type from SQL Database to Custom.
However, I now get this error:
The connection string 'MyEntities' in the application's configuration
file does not contain the required providerName attribute."
I've trawled the web and tried many variations of the connection string but not yet found the correct one.
Note: I guess I could make this an app setting and move the initialisation of the string to code, but even if only for curiosity sake I would like to know how to do it via the portal.
The problem is not the connection string, but the inability to specify the providerName from the portal.
Try publishing with a local or dummy connection string in place, and overwriting it as you have in the Azure Application Settings. See this answer: https://stackoverflow.com/a/18964294/94853

Failing to get EF connection string to work when setup in Azure's management portal?

I am using ASP.NET MVC4 deployed on WebApps, EF6, Azure SQL Database
I have two connectionstrings, one direct to the DB and one that is needed as I am using Entity Framework. If I setup the first via Azure and leave the EF string in web.config, all works fine. Once I try to move the EF connectionstring to Azure, it breaks.
I have tried to follow all the posts on how to setup an EF connection string in Azure Management Portal, and the advice seems to be to use the following:
In Management Portal:
Name:
EFConnectionString
Value:
metadata=res://MyModel/model.csdl|res://MyModel/model.ssdl|res://MyModel/model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=tcp:myserver.database.windows.net,1234;Initial Catalog=mydatabase;User ID=Admin#myserver.database.windows.net;Password=12345678"
SQL Database:
Custom
Note:
" is replaced by " in the Azure string.
In Web.config I still need the following:
<add name="EFConnectionString" connectionString="" providerName="System.Data.EntityClient"/>
I have changed certain details in the connectionstring for security reasons, but the true string does work fine in Web.config.
However when I do attempt the above, I get :
The page cannot be displayed because an internal server error has occurred.
Further Log error message:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
Any help appreciated. I am trying to do this to enhance the security of stored passwords for accessing DB on Azures, as I understand that setting them up via the portal encrypts them.
Thanks.
First check your deployment. I've run in a similar problem, and after a couple of hours struggling I found out that I was deploying without actually sending connection strings, falling back to whatever was in the portal config... the others keys in the we.config were being sent over, but the conn strings weren't... after I properly set it up on the portal, everything went back to normal...

How to handle EF code-first migrations from my local machine when deploying to Azure?

I finally figured out how to get web.config transformations working, so that locally I have one connection (the one in my default web.config), and then when I publish to Azure, the "debug" transformation is applied so that an Azure-SQL database connection string is used.
That much is working, but now I'm running into a problem with database migrations.
In my Configuration:
protected override void Seed(MG.Context.MentorContext context)
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<MentorContext, Configuration>());
if (!WebSecurity.Initialized)
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"User", "UserId", "Username", autoCreateTables: true);
}
Now, when I'm running locally and want to update my local database, I open up Package Manager Console and type in 'update-database' and everything works wonderfully.
Sometimes I want to update the remote Azure-SQL database though - so in the past I've done this:
Update-Database -ConnectionString "azure connection string here" -verbose
which was working when I was manually updating my local web.config. Now that I'm using the above transformations, even though I specify a connectionString, DefaultConnection in my Seed method resolves to the un-transformed connection string (my local db), so the Membership tables never get created on the Azure database.
This can be solved by manually updating the default web.config, but that defeats the purpose of using these transformations.
How can I have these transformations applied so that the Seed method of my EF migrations uses the Azure connection strings - OR - how can I tell update-database to use the azure connection string?
I'm trying to avoid manually swapping the connection strings if I can.
You mention a Web.config and "publishing" to Azure; are you using Azure Web Sites?
If so, look at this article. In short, if you configure a connection string on the K/V store of Azure Web Sites with the same name as your connection string, the value you set on Azure will automatically take precedence:
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.
This should ensure that you Seed method attempts to connect to the right database.

Using SQL Server CE 4.0 with Entity Framework on Windows Azure

I am using SQL Server CE 4.0 with WebApi on Windows Azure Websites. I have been successfully able to deploy SQL Server CE. The weird problem I am facing is that my site is able to log me in using the same DB but I am not able to use any of the controllers to fetch the data.
I am using same connection string for both. The only difference is that for logging in I am using WebSecurity as I have enabled OAuth on the site.
Can someone throw some light on how to debug and fix this issue? The error I am getting for the calls is
Format of the initialization string does not conform to specification
starting at index 0.
However the same string works for authentication, change password, adding OAuth connections etc.
Thanks in advance
I connected to the site using FTP. I was not giving the site name as domain name and it was denying me access earlier. On connecting, I got hold of the Web.config file and I found something interesting. While publishing the site, the web.config was modified to add another connectionstring with the name of context_DatabasePublish.
This string had following details connectionString="ContextName_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient"
Also there was a new section called context added to the entityframework section of the config file with all the details for the context to use but again pointing to same connection string. The provider it is using is sql and not sqlce. I believe that is the reason it was failing.
I uploaded my normal config file and the site started working. I need to explore more on to why and how the new connection string got added. I will post the details in comments.