How do I encrypt the connection string with EF 4.1 Code First? - winforms

I'm using the Code First RC to build a class library and I would like to be able to encrypt the connection string that I'm using. The consumers of the class library could be ASP.NET or Windows Forms apps, so I need an encryption method that works with both.
It appears that I can pass in a connection string to DbContext by name, but not by value, as shown here, so I don't think I can manually decrypt within my program before passing the string to DbContext. Could anyone point me in the right direction?

You can easily encrypt any .NET configuration section - not just in ASP.NET as many devs seem to think, but absolutely also in other apps.
Check out Jon Galloway's blog post on the topic - excellent read!
With this approach, you could encrypt the <connectionStrings> section - and to make it easier still, you could externalize that section into a separate file, too.
So in your app.config for your Winforms app, you'd have:
<connectionStrings configSource="ConnectionStrings.config" />
and the same would be in your web.config for your web application, and the file referenced would contain just the <connectionStrings> and that could be encrypted. Load the appropriate connection string from your config, and pass it into your DbContext constructor, and you should be fine.

You can pass a full connection string into DbContext:
http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx
Under "Other DbContext Constructor Options":
...
You can pass a full connection string to DbContext instead of just
the database or connection string
name. By default this connection
string is used with the
System.Data.SqlClient provider;
this can be changed by setting a
different implementation of
IConnectionFactory onto
context.Database.DefaultConnectionFactory.
You can use an existing DbConnection object by passing it
to a DbContext constructor. If the
connection object is an instance of
EntityConnection, then the model
specified in the connection will be
used in Database/Model First mode.
If the object is an instance of
some other type—for example,
SqlConnection—then the context will
use it for Code First mode.
...
If this is true, then you can use AES or some other encryption to encrypt the string in the .config file, then decrypt at runtime and feed it into the DbContext constructor.

Related

Hangfire configuration for SQL Server

I am coding a MVC 5 internet application, and am wishing to use Hangfire for recurring tasks.
How can I setup Hangfire to use SQL Server storage without specifying this in the Startup.Auth ConfigureAuth(IAppBuilder app) function.
Here is a resource link for SQL Server configuration: http://docs.hangfire.io/en/latest/configuration/using-sql-server.html
This resource states that:
If you want to use Hangfire outside of web application, where OWIN
Startup class is not applicable, create an instance of the
SqlServerStorage manually and pass it to the JobStorage.Current static
property. Parameters are the same.
The example code is as follows:
JobStorage.Current = new SqlServerStorage("connection string or its name");
I have tried the following code (with my own connection string), yet the dashboard is not available. I have called the code above from a controller function.
Is there something that I have not done correct? How can I setup Hangfire to use SQL Server storage without using the Startup.Auth class?
Thanks in advance.
I think this is your problem:
I have called the code above from a controller function.
You should be setting this up once on application startup - either in the Configuration method of an OWIN Startup class (followed by an app.UseHangFireServer();), or in the Application_Start method of your Global.asax.cs if you really don't want to use OWIN. Either way, the line you're looking for is right there in the documentation you reference:
Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(#"connection string or connection string name");
HOWEVER, as far as I know, if you want to use the dashboard you must configure that part via OWIN along with an authorization filter. See http://docs.hangfire.io/en/latest/configuration/using-dashboard.html
So really, I don't know if any downside of using the OWIN configuration for all of this. It's the more modern platform, and since you mention this is for an MVC5 app it's unlikely that you have legacy concerns.

Read connection string from app.config in my DataAccess library project for dbContext

I am working on a VS2012 solution that has got an ASP.NET MVC 4.0 project and multiple class libraries like my Managers, providers and DataAccess projects. My dbContext class is defined inside the DataAccess project.
My aim is to restrict the connection string info in the DataAccess project's App.Config file. I am trying to avoid specifying the connectionString anywhere else in the project as it is my DataAccess classes that would interact with the DB.
Now if I specify my connection string the my dbContext class by hard coding it, my project works fine and is able to read data from DB.
public MyDbContext()
: base(#"Data Source=MYLAPTOP\SQL2012MAIN;Initial Catalog=MyDB;User ID=sa;Password=*****")
{
}
But if I specify the connection string in app.config file like this:
<connectionStrings>
<add name="MyDBConnection" connectionString="Data Source=MYLAPTOP\SQL2012MAIN;Initial Catalog=MyDB;User ID=sa;Password=*****;Connect Timeout=200; pooling='true" providerName="System.Data.SqlClient" />
</connectionStrings>
and use it in my dbContext classs as follows:
public MyDbContext()
: base("MyDBConnection")
{
}
It doesn't work. I tried using the same connection string in my MVC project's web.config file also, but then again I am getting the same error (attached image):
Can anybody please guide me...
Thanks Hari
I think your fault lies at the pooling, so try
Pooling=True also make sure to remove the single inverted comma that you have, '
There is one more point you might want to research on, I think that Pooling is by default enabled, so setting Pooling=True, while this is explicit, if I remember correctly, it has no effect, whereas Pooling=False does have a effect.
To make it work you can try calling the base constructor like this:
public MyDbContext()
: base("MyDBConnection", backend, metadataSource)
{
}
In this case, backend and metadataSource would be the fields in your MyDbContext class, which hold the configuration of the backend and the configuration of the mapping.
In the Creating OpenAccessContext article, you will find more details about the design of the context.

connection string in ADO.NET entity data model

I have a C# console application (say Project.Console) in which I am using a dll of another project (say Project.Data, which is a class library using ADO.NET Entity Data Model to retrieve data from the DB).
I have added the connection string in Project.Data's App.Config file. When I'm trying to access DB in Project.Console by the classes in dll an error (ArgumentException : 'The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.') is showing.
When I tested by adding the connection string in Project.Console's App.Config file also, its working fine.
Why its so? Is it necessary to pass the connection string in Project.Console's App.Config file since no direct DB interaction is there?
From my learning, its only need to pass the connection string in Project.Data's App.Config file.. Am I right..?
the connection string is properly set in the DLL's app.config file.
// Assumsing
connectionString is your connectionString
ModelEntities context=new ModelEntity(connectionString, Assembly.GetExecutingAssembly());
or like this:
1. The model is inside a folder called Models
2. The name of the library is ClassLibrary1
3. The name of the EF model is ClassLibrary1Model
4. connectionString is your connectionString
If you put the model lets in a folder called Model for example:
ModelEntities context=new ModelEntity(GetConnection("ClassLibrary1", "Models", "ClassLibrary1Model", connectionString));

How to force the Entity Framework 5 DbContext to re-read connection strings from app.config?

I am trying to allow users to type in the data source into a dialog which I am then writing to the app.config for the application. The scenario I am having a problem with works like this:
1) User types the data source into my dialog and the dialog adds or updates the connection string. In this scenario the user typed the wrong data source the first time.
2) The user then opens the dialog that has the EF code (which inits the connection string stuff) and EF throws an exception that it cannot connect.
3) The user goes back into the original dialog and puts the correct data source name in and the app.config is again updated.
4) The user the opens again the dialog that triggers the EF code and EF still has the old data source in there although it is correct now in the app.config.
I have tried
ConfigurationManager.RefreshSection("connectionStrings").
I have tried running
MyEFContainer.Database.Initialize() as well.
Neither seems to work. What do I need to do to have EF refresh the connection string data without forcing the user to close and reopen the app? If they do that then it works.
I would always work with a connection string in memory. Keep it e.g. in a context factory. Initially you read it from the config file, but it may get replaced by a new one. You store the new one in the app.config (when it is valid) for the next run of the application.
Are you instantiating a new instance of the DbContext class after the connection string is corrected? Reusing the DbContext instance that initially failed would be the problem.
For the moment,I think to force EF to reload app.config .After we change the app.config the
ConfigurationManager.RefreshSection("xxx")
is not worked for EF,so you must to restart your application.
The best way to solve the problem:
with NO Connection strings in app.config.
Uses automatic migrations and 2 databases using the same context. The real runtime supplied Connection. Approach.

EFCodeFirst 4.2 and Provider Manifest tokens

I have a library that I have created that depends on EF Codefirst for DB interaction. I am also using EntityMigrations Alpha 3. When I use the library in my main application (WPF) everything works fine and as expected. Another part of the system uses Excel and retrieves information using the same library via an additional COM class in between.
In the Excel scenario, as soon as it tries to connect to the database, it throws up an exception to do with "The Provider did not return a ProviderManifestToken".
I'm really not sure why I'm only getting the error when I go through Excel/COM. In both scenarios I can confirm that the same DB connection string is being used. THe method to retrieve the DB Connection string is also the same - they use a shared config file & loader class.
Any suggestions welcome.
Issue resolved.
I had also created a custom DBIntializer and part of the intialization calls upon EntityMigrations to ensure the DB is up to date. The custom migration calls the default constructor on your context. By convention this will either dynamically use it's own connection string for SQLExpress(I don't have installed) or try to look for an entry in your config file (I don't have this either for the dll - config comes from hosting apps).
This is what is causing the failure when being used from Excel(In my scenario). The Migration will be newing up an instance of the context using the default constructor. This means that a config entry for the connection string is required or it uses the default process(SQLExpress). When being used from Excel in a COM env – no config file exists.
Moving the migration out of the Initialization strategy means I no longer have a problem.

Resources