Changing Connection String in C# programmatically - c#

I need to make a connection setting in my system (changing the connection string in run time). I mean the user can set up and connect to any server they want. My question is, how can I retrieve the last connection string the user made in the connection setting and use it when the user re run the program?
So far this what I've made :
connect = "Data Source=" + Class1.DS.ToString() + ";Initial Catalog=" + Class1.IC.ToString() + ";Integrated Security= True;pooling=false;Connection Timeout=0;";
MessageBox.Show("Connection Made!");
this.Close();`(this is for the settings form)
frmSettings settings = new frmSettings();
connectString = frmSettings.connect.ToString();
dbconnection = new SqlConnection(connectString);
dbconnection.Open(); //<--(and this is where I call the connection string after the set-up)
What will I do to retrieve the last connection string the user made? Any suggestions please help me..

I assume you are using WinForm. There are many options about saving settings such as registry, custom ini...etc. The easiest one I always try before going elsewhere is config file.
Add "System.Configuration" into your project reference. Right click your project and "Add New Item", search for "config", you will see "Application Configuration File", add it. Now you have a App.Config.
You can add items into the file like:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="Config1" value="Foo" />
<add key="Config2" value="Bar" />
</appSettings>
</configuration>
And to use it, you can do:
Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var conf = configManager.AppSettings.Settings;
string val1 = conf["Config1"].Value;
You can play with the OpenExeConfiguration call to look for different locations depending on your YourApp.exe.config file, but you get the idea...

Related

Why is my Connection String only working in Dev?

See DGibbs answer below.
I can't have the config file saved with the EXE, as this is present on each user's desktop, so it seems I am unable to store the password in the config file and will have to come up with some other solution.
I have an app that needs to run a CMD command as an administrator. To achieve this, I stored the password in a connection string in app.config:
<connectionStrings>
<add name="mypw" connectionString="PASSWORD" />
</connectionStrings>
I am then able to call this in my Cmd class as a SecureString:
private static SecureString pw()
{
string connectionString = ConfigurationManager.ConnectionStrings["mypw"].ConnectionString;
SecureString ss = new SecureString();
foreach (char c in connectionString)
{
ss.AppendChar(c);
}
return ss;
}
When I run the app from VS on my machine with debugging (F5), it works fine and the password is retrieved. However, when running it in a development environment I see the exception Object Reference not set to an instance of an object, and from my own debugging I can see that this is happening at this line:
string connectionString = ConfigurationManager.ConnectionStrings["mypw"].ConnectionString;
Can anyone please explain why the app is able to retrieve the connection string on my machine but not when deployed elsewhere? Does the app.config file change when publishing the app?
Few things, don't use <connectionStrings>, this is typically used to store credentials for a db connection, it doesn't make sense here. Try using AppSettings within the App.config file e.g
<appSettings>
<add key="mypw" value="password" />
</appSettings>
You can retrieve the value like this:
string pw = ConfigurationSettings.AppSettings["mypw"];
Finally, make sure you have the config file deployed, it should be [ApplicationName].exe.config and not App.Config. If it doesn't appear, check the Copy to output directory setting, make sure it's set to Copy Always.

How do I create a runtime envrionmental variable from a build time environmental variable?

I am not sure this is possible but I want to create a runtime environmental variable that gets evaluated at build time.
The idea being that three developers can use different servers for testing and not have to change it every time the project is checked out.
This is in C# .net
I do stuff like that sometimes.
<connectionStrings>
<add name="BobServer" connectionString="bob's connection string" />
<add name="MaryServer" connectionString="mary's connection string" />
<add name="JimServer" connectionString="jim's connection string" />
</connectionStrings>
string
ConnectionName = Environment.UserName + "Server",
ConString = ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
}
If Environment.UserName is Bob, it will use the BobServer connection string. If it's Mary, it will use MaryServer. You'd probably need to make some modifications, but this should help put you in the right direction.

C# Winform Application

I am creating a winform application which connects to a ms-access database. The problem is with my connection string as i can access the database locally but if i run from my usb stick or from any other pc it would give me error. How can i modify my connection string so that i can run my application on other pc without any trouble.
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Aakash\Documents\Visual Studio 2013\Projects\Industrial Foundry\record.accdb";
using (OleDbConnection con = new OleDbConnection(strConnect))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("select * from Industry ", con))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Perhaps this would be a good start:
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx
Since your title indicates you have a WinForms application, you may also want to consider adding a "Browse" button to locate the database and then using a connection string builder to build your connection.
I hope this can help you.
Create a winform where you can input parameters like "server", "password", etc., etc
After that, update your connection string with the parameters:
Friend Principal As New SqlClient.SqlConnection("data source=" & My.Settings.Server & ";INITIAL CATALOG=" & My.Settings.DB & ";UID=" & My.Settings.User & ";PWD=" & My.Settings.Password & ";workstation id=" & My.Settings.PC & ";packet size=4096")
Your connection string points directly to a path on your C: drive.
There are a number of ways that you could fix it; you could just prompt the user for the file location, and/or store it in a user configurable settings file.
I think simple way for you would be use App.Config file (Application Configuration File), you can add your database key in config file, when app launch you can check if key value is null than you should force user to choose database path, and you can set that database path to your config file. You can read your key value something using..
Code for Read Key
System.Configuration.ConfigurationSettings.AppSettings["DBKey"];
Code for Write Key
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("DBKey", "DBPath");
config.Save(ConfigurationSaveMode.Modified)
Thanks
Suresh

ConfigurationManager.ConnectionStrings.ConnectionString Issue

I am trying to pull in data from a Microsoft Access database file, in order to populate several textboxes. (The textboxes are all done in XAML.) I'm quite sure I'm missing something, because the database file isn't accessed.
Here is my code:
DataTable tblVFWPostManagers = new DataTable();
string connString2 = ConfigurationManager.ConnectionStrings**/*["\\Documents\DatabaseFile.accdb"]*/**.ConnectionString;
string query2 = #"SELECT Manager ID, Manager FName, Manager LName, Manager Address, Manager City, Manager State, Manager Zip Code,
Manager Home Phone Number, Manager Cell Phone Number, Manager Email FROM tblVFWPostManagers";
//Fill the VFWPostManagers Set with the data
using (SqlConnection conn2 = new SqlConnection(connString2))
{
SqlDataAdapter da2 = new SqlDataAdapter(query2, conn2);
da2.Fill(tblVFWPostManagers);
}
Note: I'm sure the bolded is incorrect. However, I'm not really sure what goes in those brackets. I assumed, at first, that it was where the filepath went. When I commented that section out, the error disapperead though.
How can I pull in the data from my database using the above method? What am I missing?
A couple of errors in your code:
ConfigurationManager.ConnectionStrings references a specific section of your app config where are stored the informations to access your databases (one or more). The Section contains lines like these
<connectionStrings>
<add name="MyDataBase" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\myFolder\myAccess2007file.accdb;
Persist Security Info=False"/>
</connectionStrings>
(To create a valid connectionstring for your app look at www.connectionstrings.com)
So your code refers to these section voices using the 'name' key with
string connString2 = ConfigurationManager.ConnectionStrings["MyDataBase"].ConnectionString;
Said that now the text of your query will fail because you use extensively columns names with spaces. In this case every column name should be enclosed in square brackets.
string query2 = #"SELECT [Manager ID], [Manager FName], [Manager LName], .....
In your app.config or web.config file you have a ConnectionStrings section :
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="..."/>
</connectionStrings>
...
</configuration>
You can access it in your code :
string connString2 = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

SqlDependency.Start An attempt to attach an auto-named database for file failed

iv'e got copy of NORTHWND.mdf along with NORTHWND.LOG in my App_Data folder
MY CONNECTION STRING :
<add name="northwind_connection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|NORTHWND.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
when i attempt to open and close the connection everything works out fine.
string connStr = WebConfigurationManager.ConnectionStrings["northwind_connection"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand command = new SqlCommand("Select * From Products");
command.Connection = conn;
conn.Open();
SqlDataReader reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
now beside this code i want to add SqlCacheDependency to the page
when i place the code : Shown in msdn
SqlDependency.Start(connStr);
I GET THE FOLLOWING ERROR :
An attempt to attach an auto-named database for file C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\NORTHWND.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
any ideas why this happens , what do i need to configure for the SqlCacheDependency to work.
thanks in advance
eran.
in addition i would like to add that if i change my connection string to a specific one
<add name="northwind_connection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\NORTHWND.MDF; Integrated Security=True" providerName="System.Data.SqlClient" />
everything works as it should but that seems wrong since i don't expect users to change the connection string to their path , that's why i would like to put it in App_Data
or at list give a relative path to .\SQLEXPRESS
which also doesn't work :
<add name="myConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=NORTHWND;Integrated Security=True;" providerName="System.Data.SqlClient"/>
please shed some light on this issue there must be some configuration that makes this possible .
thanks in advance.
eran.
I don't think you can use SqlCacheDependency with an auto-attach (SQLEXPRESS) type connection string.
You need to attach the database in Management studio, and change your connection string to look like:
server=(local);database=Northwind;Integrated Security=SSPI;
Then you need to execute ALTER DATABASE NORTHWIND SET ENABLE_BROKER
If you need to provide this kind of setup for users then you can write a SQL Script that will do it for them.

Categories