How do I set a default connection string in a console application? - c#

In my MVC projects with a web interface, I'm used to setting the Connection String in the Web.Config file.
However, now I'm making a bog standard console application - also with a database hook, but how do I set the connection string globally for the application?
At the moment, I am setting
var dbIndex = new DBContext();
dbIndex.Database.Connection.ConnectionString =
"Data Source=USER-PC;Initial Catalog=TextProject.DBContext;" +
"Integrated Security=True;MultipleActiveResultSets=True";
but I have to set this connectionstring property every time, in all function calls. Is there a way to set a global connection string when I don't have a web.config?

So I think what your saying is that Entity Framework (I assume that is what you are using) looks for defaultConnection connection string.
You can try putting it in the app.config file as suggested by others, but I'm not sure if this will be automagically picked up by EF.
What you could do, if it doesn't work, is to create new class which inherits DbContext -
public class MyDbContext : DbContext
{
public MyDbContext() : base()
{
var cs = ConfigurationManager.ConnectionStrings["defaultConnection"]
.ConnectionString;
this.Database.Connection.ConnectionString = cs;
}
}

App.config is the equivalent to a Web.config for console or .exe programs.
Add a reference to System.Configuration on any project that you want to use the ConnectionStrings of the app.config
Add a AppConfig to your entry point project. This is the project that is executed. (e.g. console .exe)
Add the connection string in the <connectionStrings></connectionStrings> section of the app.config
Now place the connection string in your app.config
string connStr =ConfigurationManager.ConnectionStrings["ConnName"]
.ConnectionString;
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnName" connectionString="Data Source=USER-PC;Initial Catalog=TextProject.DBContext;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>
</configuration>

As others have said put your connection string in the App.config file.
Regarding Entity Framework. If you are using Entity Framework (EF) version 6.2.0 perhaps earlier EF will automatically look for a connection with the same name as the class that inherits from DbContext.
If your class is
public class MyDatabaseContext : DbContext
{
// other code
}
EF will look for a connection string with a name like this
<add name="MyDatabaseContext" ...
You can also set the name in the constructor like so
public class MyDatabaseContext : DbContext
{
public MyDatabaseContext() : base ("name=defaultConnection")
{
// other code
}
// other code
}
In this case your connection string name can be <add name="defaultConnection" ...

You can put the same element in a App.config file for the console application and access it the same way you would a Web.config.
Related: What is App.config in C#.NET? How to use it?

The solution is very simple and easy. Just right click and set the project as start-up project. entity framework by default picks the start-up project and uses the connection string inside of App.config or web.config
Please refer to this:

Related

Correctly storing db connection strings in environment variables ASP.Net MVC Apps

I am trying to move my 2 database connection strings to environment variables for security reasons. Everything works fine when I include the 2 connection strings on web.config like so:
<connectionStrings>
<clear />
<add name="DefaultConnection" connectionString="Data Source=xxxxxx" providerName="System.Data.SqlClient" />
<add name="RDSContext" connectionString="Data Source=xxxxxx" providerName="System.Data.SqlClient" />
</connectionStrings>
I then removed the 2 connection strings from web.config and created 2 environment variables as follows:
setx CUSTOMCONNSTR_DefaultConnection "Data Source=xxxxx"
setx CUSTOMCONNSTR_RDSContext "Data Source=xxxxx"
Although I now get the following error when I startup IIS and visit the web app
Server Error in '/' Application.
Cannot attach the file 'C:\Users\xxx\xxx\App_Data\BookingSystem.Models.RDSContext.mdf' as database 'BookingSystem.Models.RDSContext'.
Can anyone tell me what I am doing incorrect?
Simply naming your environment variable in a certain way doesn't mean that MVC will pick them up. You may be assuming a little more magic is happening than there actually is.
When you do ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString you're only retrieving the connection string from your web.config file, or machine.config if you happened to have defined it there. There's nothing there to tell your app to grab it from anywhere else.
Instead, you might consider creating a class to represent your configuration:
public class MyApplicationDatabaseConfiguration
{
public string ConnectionString { get; set; }
}
Any class that needs to obtain this connection string can do so by depending on an instance of that MyApplicationDatabaseConfiguration.
public class MyDatabaseRepository
{
readonly MyApplicationDatabaseConfiguration _dbConfig;
public MyDatabaseRepository(MyApplicationDatabaseConfiguration dbConfig)
{
_dbConfig = dbConfig;
}
public void DoSomethingWithTheDatabase()
{
using(var connection = new SqlConnection(_dbConfig.Connectionstring))
{
//now you can use the connection
}
}
}
Then you can load your config however you like. Ex:
MyApplicationDatabaseConfiguration dbConfig = new MyApplicationDatabaseConfiguration();
dbConfig.ConnectionString = Environment.GetEnvironmentVariable("MyApplication_MyConnectionString");
Now the MyDatabaseRepository doesn't care how you load the database config, it simply says "I need the database config". This is extremely powerful, it allows you to change out the configuration by simply changing a line of code. Need to change back to using web.config? It's as simple as dbConfig.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
Microsoft has taken this one step further in Microsoft.Extensions.Configuration library, which is meant for .NET Core but targeted to .NET Standard, so you can use it in your .NET Framework library if you'd like.

EF Migrations Database connection string is wrong

When I use update-database -verbose and check the connection string it is wrong, no wonder the command returns with a crazy list of errors. In app.config my conn string is:
dd name="TESTDBConnString" connectionString="data source= .; initial catalog=TESTDB;
integrated security=True" providerName="System.Data.SqlClient"
And in my context class my constructor is:
public class MyContext : DbContext, IContext
{
public MyContext() : base("TESTDBConnString")
{
}
public DbSet<TestModel> TestModel { get; set; }
}
Yet when I run the verbose command I see .\SQLEXPRESS being used as the database source and I cannot even use that in SSMS so can someone show me how to get it to simply take '.'. Thanks!
it looks like your connection string format is invalid.
from the MSDN:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="BloggingDatabase"
connectionString="Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" />
</connectionStrings>
</configuration>
it seems like you need to specify Server and Database for current Entity Framework apps connecting to SQL SERVER
I can't comment that's why i will make a suggestion. In .Net core app you need to have a specific structure in appsettings.json
Like
{
"ConnectionStrings": {
"TESTDBConnString": "server=localhost\\SQLEXPRESS;Initial Catalog=my-DB;Integrated Security=true;Trusted_Connection=True;connect timeout=100;"
}
}
For login-password connection string a little bit different.
In this case in the context for empty constructor you can use like. And all should work when you call Update-Database.

Remove ConnectionString from Web.config using Entity Framework CodeFirst

Transform web.config won't work well for Entity Framework CodeFirst because the connection string is added dynamically after transform when publishing. We have a dynamic connection settings being set in code for CodeFirst when releasing to different environments.
I have tried the correct removal method but the published results ends up with the connection string in the web.config.
Are there any work arounds for this? Putting connection info in our web.configs isn't an option. Adding the connection info dynamically at runtime works well.
The problem is when publish adds the connection info in the web.config the app gets a 500 error because codefirst is attempting to use an invalid connection string for the environment that is not sandbox where it was created.
We are changing that at runtime here and that is working.
public MyAppDataContext()
{
this.Database.Connection.ConnectionString = OurDynamicConfigSettings.GetSetting("MyAppConnectionString");
}
The codefirst though is attempting to use what is in web.config before we set it dynamically. The fix is to remove the connection info from the web.config.
It all works except when building on build server or publishing, codefirst inserts the connection info back into the web.config every time we publish. Having to remember to remove this each time is not good practice and prone to errors if you forget.
Code for removing connection string in our transform file should work but doesn’t.
<connectionStrings>
<add xdt:Transform="Remove" xdt:Locator="XPath(configuration/connectionStrings[#name='MyAppConnectionString'])" />
</connectionStrings>
Your transform should be:
<connectionStrings>
<add xdt:Transform="Remove" xdt:Locator="Match(name)" name="MyAppConnectionString" />
</connectionStrings>
But, I have to ask.. are connection strings stored in your database or something? Why do you need to do them in code?
You could just do this:
public class MyDataContext : DbContext {
public MyDataContext(string connectionString) : base(connectionString)
...
}
Then when you create you contexts, you do this:
using(var context =
new MyDataContext(OurDynamicConfigSettings.GetSetting("MyAppConnectionString"))) {
...
}
public partial class MyContextEntities : DbContext
{
public MyContextEntities(string ConnectionString="[Your Entity Connection String Here]")
: base(ConnectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
Replace " with ' (single quote) in connection string

How to separate connection string and get connection string from a class in C#

I'm newbie in C#. I want to ask, how can I separate the connection string config into a class?
Because every time I want to write code, I need to re-write the connection string and test the connection. So, I need to make a class so that every time I make a connection to the database, this class will test the connection first. Then after it works, the class will send the connection string to my coding.
Besides, if I want to change my source data, I just need to change in the class only. No need to search all my coding
So if I can make a class, how do I call and get the connection string from class?
Can it be like that?
This is my current coding for connection string in C#
FileInfo file = new FileInfo(Application.StartupPath + "\\conn.txt");
if (file.Exists)
{
StreamReader r = File.OpenText(Application.StartupPath + "\\conn.txt");
connString = r.ReadToEnd();
r.Close();
// Open SQL connection
SqlConnection openCon = new SqlConnection(connString);
try
{
Cursor = Cursors.WaitCursor;
openCon.Open();
}
catch
{
MessageBox.Show("Error to established connection\nPlease check Data Source");
openCon.Close();
Cursor = Cursors.Arrow;
}
else
{
MessageBox.Show("File config is missing");
}
}
Hope you can teach me as a newbie in C#. Thanks for the help. And sorry for bad english.
You should store connection strings in your configuration file. If you don't have a configuration file, add one by right-clicking the project and 'adding new item...' If you are writing a web app it will be a web.config file; if you are writing a client app it will be an app.config file.
You add a connection string to the configuration file in the connectionStrings node, normally at the top of the file.
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!-- add a string -->
<add name="MyConnectionString"
connectionString="Data Source=localhost; ... // etc
providerName="System.Data.SqlClient" />
</connectionStrings>
// and keep all the other configuration in the file
And then you simply refer to the configuration file using the ConfigurationManager class - you'll need to add a reference to System.Configuration if you don't already have one.
ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
You're trying to reinvent the wheel here. The .Net framework already include some simple techniques to handle this. If you're creating a Windows form project, you can store the connection string in App.Config using the connectionString attributes. If this is a web app, then you store it in web.config, here is how it would look like:
<connectionStrings>
<add name="Prod" connectionString="Server=myServer;Database=DB1;user=sa;password=myPassword;Trusted_Connection=false" providerName="SQL" />
</connectionStrings>
Then, in your code, you read the connection string from web.config as follow:
string connString = System.Configuration.ConfigurationManager.
ConnectionStrings["Prod"].ConnectionString;
You're asking a very basic question here and it indicates that you're trying to bully your way into learning c#. My advice to you is to grab a good C# book and go through it cover to cover to learn things the right way.
Instead of putting the connection string into a separate file, store it in your app.config or web.config file. .NET configuration files van contain a section that allows you to store connection strings:
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
You can retrieve this connection string using the following code:
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
I think Poster's question is pretty much valid. Although we can write connection string in Web.config or app.config once and use it in whole project, but there is a drawback of using this technique.
Connection string in web.config or app.config is never safe. These two files are ultimately like text files. There are ways to get the password from them. The security could be broken. So its better to use the connection string in a separate class file and get it in your whole project.
you could create a class which returns a sqlConnection...
public class DBConn
{
private string ConnectionString = "123456789Connection";
public SqlConnection getSqlConn()
{
return SqlConnection();
}
}

Changed Database Name -- Datatable Adapters broke

We've recently changed the name of the SQL DataBase our WebApp is using. Now, each of the DataTableAdapters will update to the new ConnectionString.
Our setup is as follows:
1) Interface (WebSite Project)
2) Business Logic (Class Library Project)
3) Data Access (Class Library Project) ---> Contains many DataSet classes
The app.config of the Data Access project contains the only connection string. When creating each of the DataTableAdapters, the wizard points to it correctly. Now, we've had to change the ConnectionString, and all of the existing DataTableAdapters (about ~60) will not work.
Simply changing the ConnectionString has not worked. What am I missing?
Thanks
Make sure the connection string name in your config is the same as the one in the Settings File. Because in the generated code, when it initialzed the connectionstring it setting the connection string as follow :
private void InitConnection() {
this._connection = new global::System.Data.SqlClient.SqlConnection();
this._connection.ConnectionString = global::ConsoleApplication4.Properties.Settings.Default.MyConnectionString;
}
Make sure that in your app config the name of your connectionString is the same. for example
<connectionStrings>
<add name="ConsoleApplication4.Properties.Settings.MyConnectionString"
connectionString="Data Source=MyServer;Initial Catalog=MyDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
The problem was in the Settings.Designer.cs file. Its an auto-generated file that did not update after the normal updating/clean/build process.
Thanks Everyone :-)

Categories