Entity Framework - Database first - Intercepting DbContext - c#

I am developing a Web API that uses Entity Framework 6. The Connection String for Entity Framework is encrypted with a company standard encryption. (sql server 2014) I can decrypt the connection string just fine, but I have not been able to figure out how to intercept DbContext to set the decrypted connection string. (Before the Web.config had an encrypted connection string, I was able to run the API just fine, and all database calls works appropriately)
The code below shows how I have circumvented the issue thus far. I have created a partial class for my context class, since the Peliquin.Context.cs class is generated code. I am decrypting the connection string, which as I've verified, looks exactly correct, then passing it into this class. The previous code was :base("name=ConnectionName")
The error message seems as if DbContext cannot have an actual connection string passed into it. But if I pass in the connection name, it runs into an issue with the connection string being encrypted.
I have searched and have been unable to find the solution to this seemingly simple problem. Any help would be appreciated.
The web.config connection string, before I decrypt it at runtime:
Side note: This website will get deployed to several client sites, each that have their own database credentials. At the time of the installer installing the API and UI web applications onto the server, another application runs that updates the web.config file to the proper client database connection. This entire process is to have no user interaction. If anybody can think of a better method of changing the web.config connection string, then encrypting it, all without human interaction, please feel free to suggest an alternate solution to me.

Well, I seemingly fixed the problem myself. In the dynamically generated code Peliquin.Context.cs, I pass in the decrypted connection string, and it all works fine. What I don't like about this solution, is that the next time the edmx file is updated with the latest database changes, this file will dynamically be generated again, wiping out my changes, which will cause havoc in the future. Having another class take the constructor, still seems like a better solution.
public PeliquinDbContext(string connection):base(connection)
{
}

Related

Error 28P01 - Password authentication failed

recently I have started my adventure with databases.
I have managed to install postgreSQL and create simple database.
I've tried to create simple app which will allow me to view data from DB.
I'm using VS 2017. I have managed to configure DataSource in my WindowsForm (NetFramework) project. Test connection was successful.
When I try to fill my ListBox with data from table I'm recieving error 28P01 (it seems to mean that I'm using wrong password / username).
It is impossible - im using default account (postgres) and passsword which allowed me to populate DB in datagrip.
Can anyone help me to understand what is going on?
Guys I have managed to work it out. The thing that I did bad was configuration of connection in VS DataSource configuration. I had choosen NOT to include sensitive data into connection string - I had to put it in my code or change setting to INCLUDE it.
I feel so dumb

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.

Maintaining both on-line (Azure) and off-line version of a website

Note: Not sure if the question is asked the right way. This is how I perceive the issue but it's fully possible that the problem is addressable form a totally different angle, which I'm unaware of due to the ignorance.
Question
Is there a built-in database available for an out-of-the-box, MVC solution? If so, how do I find out its connection string?
Current string is for Azure and looks like this (frankly, it scares living excrement out me because I don't understand most of it).
<add name="DefaultConnection" connectionString="
Data Source=(LocalDb)\v11.0;
Initial Catalog=aspnet-Plong-20141107210818;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnet-Plong-20141107210818.mdf"
providerName="System.Data.SqlClient" />
Background info
I'm developing a site and publish it to the Azure. It has some connections to the database and I'm using Code First and Entity Framework. Everything works great (maybe except the fact that it takes a few seconds to upload and initialize the page prior showing, which is annoying if I've only made changes to the markup of Razor).
In fact, all's been set up pretty much automagically, and I didn't have to configure much at all. Now, it's biting my in the sitting device because of the following.
I need to be able to run my site on the local host (using F5, if you will) because I'll be going off-line (or at the very least under a very lousy connection). I can do that right now, except for the page that contacts the database reference, where I'm getting the error below.
I get what the problem is - no local DB set up using code first. I wonder if there's a lazy man's solution to it (using some built in DB and code-first-able). If so, where do I set it up? I prefer to keep the reference to default connection string as intact as possible but if I need to edit it (or, most likely, add a new one and reference it), how do I learn the correct connection string?! (Yes, I know, this is the price I pay for taking an easy way out letting Azure configure everything for me. Head down in shame.)
{"Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations."}
As far as I know that's not a connection string to SQL Azure, but for a local (development) database. It will create a .mdf file in your App_Data folder. You can find connection strings to SQL Azure somewhere in the Azure dashboard. I switch between dev en production using for example:
public MyContext : DbContext
{
public MyContext()
#if DEBUG
: base("development")
#else
: base("production")
#endif
{
}
}
However, you could also use XML transformation of the web.config, web.debug.config and web.release.config. Note that web.debug.config is not really used when you run your application locally, so put your development connection strings in web.config and publish your application in release mode so the XML transformation of web.release.config takes place.
Edit: Get the SQL Azure connection string
Got to the management portal and click on SQL Databases. Click on the database and go to Dashboard. On the right side you see "Show connection strings". It looks something like this:
Server=tcp:xxx.database.windows.net,1433;Database={your_db_name};User ID={your_user_id};Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;

Updating Connection String in DLL from Winforms - Linq to SQL

I developed a class library that uses Linq To Sql to communicate with a database.
When I added this I used Server Explorer to add a database and all the tables I want to talk to.
It then built a .dbml file for me.
In the "Designer" file I can see:
public TPDataContext() :
base(global::TPAPI.Properties.Settings.Default.TruePotentialConnectionString, mappingSource)
{
OnCreated();
}
If I update the "Linq to SQL" it regenerates a new designer.cs file
It stored the connection string in Settings.settings with the scope of "Application".
All functions just fine.
But, I have then added a winfoms project that needs to change this setting. So I added the following code:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString = txtConnectionString.Text;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
This updates the connection string in the dll but it only takes effect when the application is shutdown and restarted.
When I am upgrading clients it overwrites what the user had already entered when using it previously.
I cannot seem to work out the best way to:
Not overwrite previous user defined connection string when the app is upgraded.
Be able to save the new connection string and use it without having to stop/start the app.
Having had a read of other threads it appears that the dll shouldn't really have any "local" settings in it (?) and they should all be sent by the winforms app. But, I am unclear on how use Linq to Sql in the dll without it automatically looking/adding it's own connection string.
Can anyone help please?
Thanks
I have decided to rewrite all my DataContext calls to accept the connection string parameter.
I had to amend and test about 40 functions but now the connection string is stored in the winforms application as a user setting and overrides the default connection string generated by Linq to SQL.
So, now in my dll it now looks like
TPDataContext db = new TPDataContext(connStr);
HTH

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

Categories