How do handle EF database connections in Azure Functions V2? - c#

I am converting a WebJob to Azure Functions. I am using Azure Functions version 2. My issue is connecting to my database. The classes inside the Azure Function project do not talk to the database but they do reference classes that do talk to the database. When I run this as a webjob I simply call the configuationmanager and get the setting for the connectionstring. I made adjustments to get the string from a different location for Azure Functions but I still get the following error:
Azure Function The ADO.NET provider with invariant name 'System.Data.SqlClient'
I put the connection string into the Application Settings:
local.settings.json: Values:{"myconnectionstring"..... )
I then access this value using this:
Environment.GetEnvironmentVariable("myconnectionstring");
I can step through the code and see it as expected in the watch window. That part is figured out. But what should the connection string actually look like to work.
The one that looks like the following:
"metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=\"Server=tcp ……………………
Or
connection string="Server=tcp:somthing.windows.net,1433;Database=mydb;User ID=myid;
Or is there another style to the connection string I need to use for this to work.
Entity Framework 6.2 in the Core classes that do the work (.net 4.6.3)
The Azure Function is .netStandardv2

Related

Accessing DataVerse data and running SQL statements against it from C# code on .NET 6 (Azure Function)

I'm working with Dynamics365 CE in the cloud. I'm trying to run some rather involved queries that I've built up as SQL scripts (using the wonderful "SQL-4-CDS" plugin for the XrmToolBox).
Now I know I can connect to the Dataverse data store through the TDS endpoint (if enabled - it is in my case), and from SSMS, it works just fine:
Server Name = myorg.crm4.dynamics.com,5558
Authentication = Azure Active Directory - Password
User Name = my company e-mail
I can connect to Dataverse, and run my queries - all is great.
Now I'd like to do the same from C# code (running on .NET 6) that I'm writing, that should end up being an Azure Function in the end - so it's a "server-to-server", behind-the-scenes, no interactive login context kind of scenario.
I can connect to Dataverse via the TDS endpoint using this connection string - as long as I'm running the app interactively - as me, in my user context:
Server=myorg.crm4.dynamics.com,5558;Authentication=Active Directory Password;Database=my_dbname;User Id=my_email;Password=my_pwd;
However - this won't work with a server-to-server "daemon"-style setup.
Since I'm using .NET 6 (for the Azure Function), and since I want to run some custom SQL statements, I cannot use the "CRM XRM Client" tooling (with the IOrganizationService classes) - I need to use straight ADO.NET - any idea would I could define an ADO.NET compatible connection string, that would use a Client ID and Client Secret (which I both have at my disposal)?
I've tried a great many values for the Authentication=...... setting - but none have worked so far. Any place I can find a complete list of the supported values for this connection string parameter?
Thanks for any help or pointers!

ASP.NET and C#: connection string in web.config vs connection string stored on Azure

I have a web form developed in ASP.NET and C#. I am storing the connection string to a database in the web.config file like this:
<connectionStrings configSource="MySecrets.config" />
This points to a local file in the same directory as the solution. Debugging locally works, however it is not advisable to commit this file to source control to avoid exposing these secrets.
This article mentions that it is possible to store connection strings on Azure - in the Configurations section of an App Service. The article also says that it's possible to retrieve the connection strings in the code by doing:
dbConn = System.Configuration.ConfigurationManager.AppSettings("myConnStringName")
The article also mentions that "if the application setting(s) happen to already exist in your web.config file, Windows Azure Web Sites will automatically override them at runtime using the values associated with your website. Connection strings work in a similar fashion.
(This assumes that your connection strings are explicit in the web.config file, and if committed to source control, they would be exposed.)
However, in my code, I already have a line with:
dbConn = WebConfigurationManager.ConnectionStrings["myConnStringName"].ConnectionString
Questions:
1) How am I supposed to reconcile these two lines without declaring the same variable (dbConn) twice?
2) How can I not commit MySecrets.config to source control, but at the same time use it when I debug my app locally, while using the connection string stored on Azure when working with the published app?

encrypt database connect string for azure website

seems there is no good way to encrypt database connect string for azure website (not cloud service), i already view the solution here
but, i can't store the database first entity framework connect string in the azure website setting, which will get below error, anyone knows how to make data base connect string secure in azure website using database first entity framework?
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: 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. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
You don't have to include the connection string in the web.config for your site. You can manage the connection string in your azure account at:
App Services>[your_app_name]>Settings>Application settings
Under Connection strings section, you can set the key/value pair which is the connection name and the db connection string.
After you set those values, in the screen, the connection string will be hidden for display.

Azure Mobile Services - Connection string not found after publishing

After I deployed my mobile service to Azure, calls to the service fails because of this error:
No connection string named 'ApplicationEntities' could be found in the application config file.
The error only occurs on Azure side. When I test the service locally, the connection to the remote database works without a problem.
I separated my solution into several projects:
Web Api
Business Logic
Data Access (contains the DbContext, database first)
Common (contains the entities generated by EF)
As I always do, I copied the connection string generated in my app.config of the DataAccess Assembly into the connectionStrings-Element of my web.config (Web Api project).
<connectionStrings>
<add name="ApplicationEntities" connectionString="<the connection string>" providerName="System.Data.EntityClient" />
</connectionStrings>
In the web deploy settings, I selected the connection string for "ApplicationEntities". I tested it with and without the option "Use this connection string at runtime (update destination web.config). I always get the same error.
Then I got curious and logged the connection strings available via the ConfigurationManager with something like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
sb.AppendLine(ConfigurationManager.ConnectionStrings[i].ConnectionString);
}
trace.Info(sb.ToString());
I got two connection strings:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
Data Source=theserver.database.windows.net;Initial Catalog=thedb_db;User ID=theuser;Password=thepassword;Asynchronous Processing=True;TrustServerCertificate=False;
The username and password is strangely different from the username and password stated in the management portal.
Also the EF-Metadata information get lost.
I get this connection strings when testing locally:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
metadata=res://*/DataContext.ApplicationEntities.csdl|res://*/DataContext.ApplicationEntities.ssdl|res://*/DataContext.ApplicationEntities.msl;provider=System.Data.SqlClient;provider connection string=\"data source=theserveraddress,1433;initial catalog=thedb_db;persist security info=True;user id=theusername;password=thepassword;MultipleActiveResultSets=True;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;App=EntityFramework\"
I expect to get the same connection strings when running on Azure. Any idea what's going wrong?
Update:
I just went for remote debugging the service (see here). As I opened the downloaded publish-profile in my text editor, I discovered that there is an attribute SQLServerDBConnectionString - containing the connection string that always gets forced when deployed - with the same username and password I'm not aware of that it exists.
I tried to overrwite this connection string but it did not help. That connection remains the active.
Update 2 / May 29th 2014:
Seems that in the meantime the error has been fixed by the azure mobile team. Still running the same code using the database first approach and it's working now. Thanks a lot!
I have myself tried using DB first approach with dot net backend mobile services & ran into same sort of problems as you. Digging around further, following is my observation :
The azure mobile service with dot net backend must use code first approach only. This generates a specialised connection string with metadata (starting with res:)
The name of the connection string has to be the same as it is when you download the default sample todo app I.e. Ms_TableConnectionString.
There is an option in azure websites to select custom SQL provider to help make a custom connection string, this option, however, is not available for dot net backend mobile service in Azure Management portal.
P.s. Posting as answer because I don't have a enough points to comment..
Just wanted to give an update that I have been looking at this for some time and think I for the first time see it too. I don't know what is going on but wanted to let you know that we are indeed looking at it.
Henrik
(I don't have enough points to comment so having to do this as an answer)
Henrik, I have this same problem. If I ftp on to the box I can see that the web.config has the correct connection string but it fails as trying to use the username in the SQLServerDBConnectionString property (OoWUqr****Login). Is it possible you could let me know in what order it is looking for connection strings and where?
And if it can't stop it using the other user is there a way I can permission them for the correct database through mobile services?
Thanks
F

Using WCF Service to access SQL Server in Entity Framework -- Why does it seem like it's using Integrated Security?

Quick Background
I received code from a third party (contracted software) that I have to move onto my servers. When I run the code using their connections and service references, everything works well. When I debug locally, everything works well. My problem only occurs when I try to run the application/service(s) after I move them onto my server.
The services (or their respective references) are at the heart of what's causing the issues. I created a test client to try to debug the services, and it's accessing the service, but erroring when it tries to connect to the SQL Server inside the service. The code appears to use the Entity Framework which I am admittedly not familiar with yet.
Errors/Issues
When I use my test client to call a function inside the service reference, it errors out when it tries to connect to my SQL database:
using (ApplicationDefinitionDBEntities appDefDb = new ApplicationDefinitionDBEntities()) //ERROR
Here's the error I receive (domain and server names have been made generic):
System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'MYDOMAIN\APPSERVERNAME$'.
I found the app.config that is referenced by the .edmx file (ApplicationDefinitionDB.edmx) and its accompanying files. Here is the connection string (made generic):
<add name="ApplicationDefinitionDBEntities"
connectionString="metadata=res://*/Data.ApplicationDefinitionDB.csdl|res://*/Data.ApplicationDefinitionDB.ssdl|res://*/Data.ApplicationDefinitionDB.msl;
provider=System.Data.SqlClient;
provider connection string="data source=MYDBSERVERNAME;initial catalog=myDBcatalog;
User ID=myUserID;Password=myPassword;integrated security=false;
multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
There is also an old connection string that the third party used which had integrated security set to true and reference SQLExpress, but I commented it out.
Note that I am specifying integrated security to be false (I know it's by default but I wanted to be explicit), and also supplying a username and password to the SQL Server. So why is the error message in the service ref test client saying that it's trying to connect using DOMAIN\APPSERVER$ as though it's using integrated security?
I am using IIS to host my app and SQL Server for database work. I think I have updated and re-generated all Entity Framework stuff for the database reference, but I could be missing something. Can anyone suggest anything that I may be missing to make sure the service reference uses the connection string supplied in it, and NOT the app server domain login? Thanks!
Turns out that connection string conflicted with one above the project level of the service. The project that housed the service uses Silverlight, so I thought the ClientConfig files were the only other configs being used, but there was another one hiding in the project that I published. When I rooted around in that web.config file, I found that there was a connection string with Integrated Security turned on. Once I turned that off it worked fine. That's annoying.

Categories