Getting connection string from dll which contains Entity Framework - c#

I am trying to fix an app that references a .dll which contains Entity Framework code (.edmx, etc...). I do not have the source so I cannot determine the connection string the edmx file uses. When I run the app I get exceptions that the data source cannot be reached. I have the correct .mdf file that EF is "supposed" to be using, but since I cannot see the connection string, I can't verify this.
Is there another way(tool) to figure out what the connection string is for this dll?

It is quite weird that this 3rd part dll doesn't use a configuration key to get the connection string: entity framework creates a key every time you add a connection.
If the connection is hard-coded you need to use a tool like Reflector to get the connection string
http://reflector.red-gate.com/download.aspx?TreatAsUpdate=1

You can access the following property:
var connStr = Context.Connection.ConnectionString;
This will show you the connection string being used, minus any credentials. The Connection property differs slightly depending upon the version of EF you're using. In EFCF it's:
var connStr = Context.Database.Connection.ConnectionString;

Related

How to add connection string to once for whole solution to use?

Recently I am working on an .Net project. We used EF to handle SQL, when we make an installer of the program, we realize that app.config is visible which mean that the connection string is not safe.
I am looking for a way to add connection string (or maybe secret code and username) to the EF so that the connection string is not visible.
Something like change old code from this
Using db As ConnectDb.adoSentoEntities= New ConnectDb.adoSentoEntities
'TODO
End Using
to this
Using db As ConnectDb.adoSentoEntities= New ConnectDb.adoSentoEntities(ConnectionString)
'TODO
End Using
But since we used connect code to SQL all over the place, changing every single line of code is not possible. There is a way I only need to add connection string once?
You’d be better off encrypting the connection string section in the app.config. You wouldn’t need to make any changes.
Storing any sort of configuration in an assembly can be read using a hex editor.
It’s been answered on here before.
Encrypting Connection String in web.config
You’d be better off using a trusted connection if you’re using SQL Server. The user running the app would need to have permissions and no username and password is required.
Save connection string is settings of project properties.
Go in project properties.
Select settings.
Add new setting as connection string and save connection string.
Then you can use it for whole project.

What's the proper way to include Entity Framework connection string used in WCF service into a self hosting console application?

I'm doing my homework, a WCF service that uses SQL Server with Entity Framework, hosted through a console application, and using a WPF client.
There are 3 different projects, and the host and the service is in the same solution. I've included the Entity Framework connection string in the console hosts' app.config file from the web.config file from the service. This way the server and the host throw an exception when I try to make a query:
System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.'
The inner exception says:
SqlException: An attempt to attach an auto-named database for file C:\Users\username\source\repos\BlogAppWcf\BlogHost\bin\Debug\BlogDb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
So it basically searches for the .mdf file in it's own project folder, while it's inside the service's App_Data folder.
The original connection string looks like this, I copied this to the host's app.config from the web.config:
connectionString="metadata=res://*/BlogDbEntities.csdl|res://*/BlogDbEntities.ssdl|res://*/BlogDbEntities.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=(LocalDB)\MSSQLLocalDB;
attachdbfilename=|DataDirectory|\BlogDb.mdf;
integrated security=True;
MultipleActiveResultSets=True;App=EntityFramework""
I've tried modifying the AttachDbFilename attribute in the app.config, I gave it an absolute path like this:
attachdbfilename=C:\Users\username\source\repos\BlogAppWcf\BlogAppWcf\App_Data\BlogDb.mdf;
and this way it works like a charm! No more exceptions on queries.
But this isn't the right way to do it, especially because I have to send it to my teacher. I want to give it a relative path, just like this:
attachdbfilename=..\..\..\BlogAppWcf\App_Data\BlogDb.mdf;
but it doesn't work this way.
Has anyone got any suggestions, maybe I'm doing or thinking something completely wrong?
According to your description and the issue you encountered, I think the problem boils down to the fact that the attached database is not properly attached to VS built-in database server instance. For this reason, I think we could configure the EntityFramework with VS built-in database instance string.
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyStore;Integrated
Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And then override the seed method of the DropCreateDatabaseAlways/DropCreateDatabaseIfModelChanges class to provide the seed data.
Feel free to let me know if there is anything I can help with.

No connection string found in App config using external Start-up application

I am creating a dll project in C# using Visual Studio 2013 .Net 4.5. The project contains an entity model using EF6. My dll will be called as a plugin to an external application, that belongs to a software suite for some hardware products.
I have visual studio set up so that when I press debug it launches this external application (i will refer to as the gateway) which in turn makes calls to my dll, allowing me to debug.
The issue occurs when my dll tries to make calls to the entity model. I get:
InvalidOperationException -- An unhandled exception of type 'System.InvalidOperationException' occured in ENTITYFRAMEWORK.dll
'No connection string named 'Entity' could be found in the application config file.
Now, my config file has, very clearly, the required connection string which was added by VS when I set up the model. I have read all of the similar threads to this issue, and adding the connection string to the config is not the problem.
The gateway does have knowledge of the real DB instance and is given the connection string for that in a configuration. However, the entity connection string and the instance connection string differ, because of the entity jargon that gets added on by VS and EF.
I am able to create a console app which makes calls to my dll, capable of making the enity calls. I had to give the console app a reference to my dll and entity framework as well as add the connection string to the console apps config file.
This has led me to believe that, any app that makes calls into my dll must have knowledge of EF and the connection string.
Is this the case? If so, it would appear to me that I will be unable to use EF for this project because I will have no way to make the gateway aware of EF.
Thanks for your input!
So what I would do in this case is make a new Context which inherits from your current context and in the constructor pass in the connection string.
Alternatively you can also create a connection string that you can then pass into the constructors overload for your context.
public string GetConnectionString()
{
string connectionString = new EntityConnectionStringBuilder
{
Metadata = "res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new SqlConnectionStringBuilder
{
InitialCatalog = ConfigurationManager.AppSettings["SystemDBName"],
DataSource = ConfigurationManager.AppSettings["SystemDBServerName"],
IntegratedSecurity = false,
UserID = ConfigurationManager.AppSettings["SystemDBUsername"],
Password = ConfigurationManager.AppSettings["SystemDBPassword"],
MultipleActiveResultSets = true,
}.ConnectionString
}.ConnectionString;
return connectionString;
}
Can't you compose the Entity connectionstring based on the sql connection string?
Otherwhise have a look at this question: How to have DLL specific config file?
Basicly you are supplying a config for the dll file. So besides of myapplication.exe.config you can have a myddl.dll.config

Using a SQL Server Database File from a Class Library in C#

So I have a basic 3-tier application:
Data Access
Business Logic
Presentation
My Data Access layer is a class library, and I'm using Entity Framework and a SQL Server Database File
Say my solution is structured as such
MySolution
\MySolution.Data
\MySolution.Data\App_Data\MySolutionDB.mdf
\MySolution.BusinessLogic
\Presentation
The problem I am trying to solve is that I need to get a folder relative path to the database for the connection string because this project will not always be deployed in into the same folder structure, therefore it is imperative that the connection string is created dynamically based on the relative path.
Could someone offer some assistance on this. please?
P.S. I tried this, but it's not working:
string.Format("Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\\MySolutionDB.mdf;Integrated Security=True", AppDomain.CurrentDomain.GetData("DataDirectory"))
EDIT: Getting this error message, which may be unrelated to the issue...
Connection to the database failed. The connection string is configured
with an invalid LocalDB server name. This may have been set in
'global.asax' by a pre-release version of MVC4. The default connection
factory is now set in web.config so the line in 'global.asax' starting
with 'Database.DefaultConnectionFactory = 'should be removed. See
http://go.microsoft.com/fwlink/?LinkId=243166 for details
Thanks to wdosanjos for pointing out my stupid mistake.
string.Format("Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\\MySolutionDB.mdf;Integrated Security=True", AppDomain.CurrentDomain.GetData("DataDirectory"))
I did not escape \v11.0; it should have been \\v11.0;

Application should not look for connection string in app.config file

My application is based on entity framework 5, and the connection string is dynamically generated and used in the application. This is working fine. The only problem is if I do not put connection string in app.config file, then it gives an error. That the app.config file should contain the connection string. Is there any way, I can make my process not to find connection string in app.config file. The work around is I can put dummy connection string, but i want it should not look in app.config file for connection string.
Please help. !!
Thanks in advance..
An application does not look at connection strings, it's libraries you use that do that. Luckily your question is tagged with entity-framework, so I guess you somewhere just instantiate a new DbContext(). It would be nice if you could show on what line of code the error occurs.
When you search the web for "entity framework dbcontext pass connection string" and you will find this question which links to the manual somewhere:
public DbContext(string nameOrConnectionString)
So, just supply your valid connection string to the constructor when instantiating your Entity Framework context (not its name, as that again will make it look in the application's configuration).
Thanks CodeCaster for your reply.
I am doing in this way. I have created one class which contains the static method, and in each DAL class i just call this method, and the instance for context is created with the passed connection string.
public static myDBEntities getDBContext(String connectionString) {
myDBEntities DB = new myDBEntities();
DB.Database.Connection.ConnectionString = connectionString;
return DB;
}
My application works fine. There is no issue. I mean it takes the dynamically assigned connection string, But only problem is if I remove the connection string from app.config file, then it gives me error that it expects connection string in app.config. So is there any settings or something, which can lead EDMX not to find connection string in app.config.
Your help will be appreciated. :)

Categories

Resources