Getting a connection string - c#

The program I'm writing accesses a database. So when I use the SqlConnection() class, I hard code the actual connection string as a parameter. Eventually I'd like o deploy this program to different users. So my question is:
When a user installs a program on their computer, how does the new connection string get created, where is it stored, and how can I access it?
Thanks for the help

You need to out it in a configuration file and load it from there. For an ASP.NET application it would be in the web.config file;
<connectionStrings>
<add name="MyConnection" connectionString="MyConnectionString" />
</connectionStrings>
and then use
string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString
in your application.
The for each installation it would be configured for the local requirements.
For a desktop application the details are different but the principle is the same.
See references in answer from Luis Sagasta

As explained in MSDN, you should save the connection string in the configuration file:
MSDN: Connection Strings and Configuration Files
In the same article you will find information about encrypting the configuration section:
MSDN:Encrypting Configuration File Sections Using Protected Configuration
Regards.

Related

Change the Connecting string of the C# windows form application to it in another computer

I have a C# windows form application and I connect it to the SQL server in my computer. Now I going to deliver the software to a user. So, what can I do to change the connection string to the user SQL server? Is there any way to do the connection string computer independent? Kindly help me
Regards.
I'm assuming you're hard-coding connection strings into your code. You need an application config file.
Or you could use connection string like this (if database (SQL server) is on same machine as app using it and database name is the same) :
Server=localhost\instanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
instanceName could be "nothing" (default instance) or named instance (SQLEXPRESS).
Or do it as #Xavier J suggested - store connection string in app config or INI file.
application config files are one idea, but because they are managed through the IDE means have to change manually for deployment.
Better to use the registry (cleaner too - no need to post-edit the file), and the installer can get conditional on where it's deployed, alternatively ask the user during installation, skip if the registry entry already exists.), confirm the connection string at install time. database path/host/name exists...
You can store it in the app.config of your project. Then if you wanted the user to give credentials you could make a form and save the string to the value of that configuration.
<appSettings>
<add key="connectionString" value="Connection string goes here"/>
</appSettings>
Then call it and set it using the ConfigurationManager
ConfigurationManager.AppSettings["connectionString"] = "Your Value";
Or you could just replace the connection string yourself in the file once its on the users computer

How to Override a Value in Web.config Programatically

I am developing a web app with a group of people and we all have different connection strings to our database.
The connection string is stored in our web.config which is source controlled, and sometimes people check in their web.config with their connection string which messes up my environment.
I want to use an environment variable that if exists will override the connection string in my web.config. How can I do that?
As others have noted in your comments there is no easy way to stop people from changing any file that is under source-control. However, what you could do is change your web.config file to have:
<connectionStrings configSource="Configs\ConnectionStrings.config" > </connectionStrings>
Then have a folder called Configs and in there a file named ConnectionStrings.config with content like:
<connectionStrings>
<add name="YourVersionHere" ... />
</connectionStrings>
That way you can check the web.config file in / out without it altering your connection string (it is now held in a separate file). Of course, this doesn't get you out of jail because they can then overwrite the ConnectionStrings.config file but it does allow you to break your config out so you can always be up to date with all the settings but never do a GET on your ConnectionStrings.config file.
The same applies to AppConfig etc. Basically allows you to manage your config in smaller chunks rather than all in one place.
You can get more information here: http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx
Is it possible for you to move your connection strings from your application-level web.config down to your system-level machine.config file?

Need changable App.config file in WPF

I have a desktop WPF application which uses Entity Framework 4.1 Code First approach to manage data.
EF adds a connection string to the App.config file and I wan't to be able to change this connection string at runtime.
Scenario is like this:
When I deploy the application it has a default connection string in the App.config file. The user runs the application and since the connection string will probably be invalid for the user (because of server name, user id and password) I will display a server configuration window.
Here user will enter the valid information about his connection and press OK. I will then be able to change the App.config file and save the user's new valid information to the file.
Problems:
If I change it using ConfigurationManager, the changes will be temporary meaning that the file is not saved, changes are made in memory.
If I read the App.config file into a stream, make required changes in the memory, delete physical file and save the in memory stream as App.config again, Windows will not let me make changes to files under ProgramFiles folder.
What is would be the best approach here?
EDIT: Problem Again!
After I modify the App.config file with this method:
private void ApplyChangesToConnectionString()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
config.Save(); // This line throws an exception
ConfigurationManager.RefreshSection("connectionStrings");
}
config.Save(); method call throws an error saying
"Access to "C:\Program Files (x86)\MyCompany\MyApp\MyApp.exe.config"
is denied."
I know that files under "Program files" are immutable, so how can I handle this?
I couldn't modify ConfigurationManager.ConnectionStrings["key"] object, because it is readonly.
So I decided to add a new connection string to my App.config file so it looks like this:
<connectionStrings>
<add name="SomeUniqueName" connectionString="Data Source=(local)\SQLExpress;Initial Catalog=MyDb;User Id=sa;Password=password; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
and then changed my DbContext constructor to take newly added connection string like this:
public MyContext()
: base("name=SomeUniqueName")
{
}
Here, the value of name attribute at connection string and constructor must match.
Then to change this newly added connection string at runtime I used a method like this:
private void ApplyChangesToConnectionString()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
App.config is not the proper place to do this since it's a global configuration used by the application.
I recommend you to save the settings per user. See this related question : c# - approach for saving user settings in a WPF application?
App.config is the correct approach in my opinion, however I wouldn't rely on writing the file physically yourself. Instead, allow the framework to do the heavy lifting for you.
Check out the sample here.
EDIT: Glad Sandeep's comment above has helped you. Feel free to check out that link too if you want a bit more information!

Connection string for Fluent Nhibernate with MySQL

I've reviewed the post How to configure Fluent NHibernate with MySQL, but I'm relatively new to MySQL and I need to actually set up with connection string itself. I've installed MySQL as part of a WAMP install and need to fill in the actual connection string. Can someone help me by extending the linked answer to actually contain a full connection string example?
Appreciated.
Edit: I've tried several different things and I keep getting the following error message:
Can't load file FluentConfiguration.cs under d:\Builds\FluentNH-v1.x-nh3\src\FluentNHibernate\Cfg.
Check the file permission and the existence of that file.
I installed FNH via nuget, and I don't understand why it's looking at that path, as the d: drive is my CD and not a harddisk. Very confused.
The error you've pasted looks like Visual Studio trying to localise the sources to show you where the exception comes from. This is not the real exception message - you should have it somewhere there and it's probably something about wrong configuration.
If you've installed WAMP with default settings, it is configured to listen on 3306 port and have only local root account without password. So your connection string should look somehow like that:
Server=localhost; Port=3306; Database=[database_name_here]; Uid=root; Pwd=;
(Pwd= part may be not needed at all).
So you need to paste it in your App.config/Web.config's <connectionStrings> section:
<connectionStrings>
<add name="ConnectionString"
connectionString="Server=localhost; Port=3306;
Database=[database_name_here]; Uid=root; Pwd=;"
providerName="System.Data.SqlClient" />
</connectionStrings>
and then use the solution from linked question:
MySqlConfiguration.Standard.ConnectionString(
c => c.FromConnectionStringWithKey("ConnectionString")
)
Alternatively, you can paste the connection string directly in your Fluent's configuration, like this:
MySqlConfiguration.Standard
.ConnectionString.Is("Server=localhost; Port=3306;
Database=[database_name_here]; Uid=root; Pwd=;")
Anyway, this default root/no password configuration can be used only for local development and testing purposes.

How to make the connection string of an Windows form application in C#.net,Computer independent?

As I transfer my Windows form application in C#.net from one computer to another, I have to change the connection string every time as the location of the Database file has changed.
How can I can I prevent this,so that I don't have to change the connection string again and again?
If the service you need to connect is always running on the local machine, you might use the localhost as the server name...
By the way localhost is mapped to the ip 127.0.0.1 in the hosts file.
Have your DB file in the same location of your application exe and then you can use
Application.StartupPath()
to get the path.
*I am assuming that this is a Windows Forms Application.
How has the location of the database changed? Is it not in a central location that all computers/users can access?
If not, you could store the connection information in settings and create a form that allows you to update those as needed. The form could be launched as part of the installer or on first run of the application.
A little more information about what you're doing would be helpful in presenting a real solution.
It's tricky to tell without an example of the type of connection string you're using (or which database you're accessing) but can't you use a relative path and assume that the database is somewhere relative to your app?
If you set your connection sting up like this...
<connectionStrings>
<add name="ConsoleApplication1.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
... then |DataDirectory| will by default resolve to the application's folder. You can, however, change DataDirectory by calling the AppDomain.SetData method. See the following for how to change it...
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/805bfd29-d864-4400-b353-bea13167f046
I've shown how you'd set the connection string in config, but the same holds true if you're setting it in code. If you are building a connection string in code, then may I suggest you look at using a connection string builder...
http://msdn.microsoft.com/en-us/library/ms254947.aspx
I am, of course, assuming a file path in your connection string, but if it's a database then won't localhost also work?

Categories