So here's the what's up. I just created and "published" a staff management tool in Visual C#. During development, I used a string saved in Properties.Settings.Default to connect to the database I was using for development. Now since the solution is published and ready to go, the boss wants to connect to the real staff database. I was under the impression that connection to the new database would be as simple as changing the connection string in some properties file somewhere. Unfortunately I can't seem to find the proper file/string to connect to the database I want to. Any ideas?
Thanks!
JB
Look here:
Connection Strings and Configuration Files
By using a config file you just have to change the config file connection string once your application has been deployed.
Here's a way of doing what you want:
From http://www.dreamincode.net/forums/topic/70745-connection-string-in-appconfig/
Your config file content:
<connectionStrings >
<add name="YourName"
connectionString="Provider=msdaora;Data Source=MyOracleDB;Persist Security Info=False;Integrated Security=Yes;"
providerName="System.Data.OracleClient" />
</connectionStrings>
Method to get the connection string at runtime:
public static string GetConnectionString(string strConnection)
{
//Declare a string to hold the connection string
string sReturn = new string("");
//Check to see if they provided a connection string name
if (!string.IsNullOrEmpty(strConnection))
{
//Retrieve the connection string fromt he app.config
sReturn = ConfigurationManager.ConnectionStrings(strConnection).ConnectionString;
}
else
{
//Since they didnt provide the name of the connection string
//just grab the default on from app.config
sReturn = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString;
}
//Return the connection string to the calling method
return sReturn;
}
Using the method:
string connectionString = GetConnectionString("YourName");
I've had to change the entry in the Properties.Settings text file, recompile and redeploy to get the new connectionstring to take. In the future consider reading your connection string from your .config file under either the ConnectionStrings or AppSettings node. When you store it there you simply need to change a production text file to switch your database...
Related
So, I'm writing a program that imports excel files to a database, finds matches, non matches, shows the tables, etc.
In the beginning I added manually just my database connection string, but I have to make my program let the connection string change.
In case none is inserted, it will use the last one inserted.
Behind code:
protected void BtnFazerTudo_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
connectionString = connectionString.Replace("{username}", TxtUtilizador.Text);
connectionString = connectionString.Replace("{pwd}",TxtPalavraPasse.Text);
connectionString = connectionString.Replace("{DataSource}", TxtHost.Text);
connectionString = connectionString.Replace("{Initial}", TxtBaseDeDados.Text);
Debug.Write(con);
}
Web Config:
<add name="Db" connectionString="Data Source ={DataSource} ;Initial Catalog=
{Initial};Persist Security
Info=True;User ID={username};Password={pwd}"/>
I already tried the String builder. I was able to output it in the debug window but I have no idea in how I transfer that connection made by string builder to other web forms.
The connection string you're creating needs to be stored somewhere so as all pages of your web application can access it. While there are some choices that let you pass data among pages none of them suits you mainly because (a) the connection string contains security sensitive information such as the password!!! and (b) they do not offer the level of persistence required by your scenario (unless you want the user to fill the textboxes every time he connects to your application).
Having said that, one viable option is to store the connection string in a database and retrieve it every time you need it. You can either store it as a whole string or each user data separately (i.e catalog, user id, password etc). In the latter case, you'd have to re-create the connection string every time you need it.
How you create the connection string has nothing to do with your original question. It is just about string concatenation in C# for which you can use the + or += operators, string interpolation or the String.Format, String.Concat, String.Join or StringBuilder.Append methods.
public void DatabaseConnection()
{
connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source =..\\..\\TaxApp.accdb;Persist Security Info=False");
connection.Open();
}
If you're in a language that allows you to construct the path, such as C#:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
will, by default, give you the path to c:\ProgramData folder, which is shared among all users.
So:
string AccessDbPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"YourAppFolder\\TaxApp.accdb");
Usually you don't store fixed paths in your code. This will make your application very difficult to install on your customers PCs.
Knowing this, the NET framework provides an infrastructure to store this kind of informations in external XML based file (named yourexename.exe.config when you release the application and simply app.config inside your project).
You can store there this kind of information that need to be changed on a customer by customer base.
So you app.config could have a section made in this way
<appSettings>
<add key="DatabasePath" value="C:\programdata\MyApp\Database.accdb" />
</appSettings>
Inside your program you could read and use this value using this code
string dbFile = ConfigurationManager.AppSettings["DatabasePath"].ToString();
connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data source =" + dbFile +
";Persist Security Info=False");
You could even store the whole connection string using the project properties menu and adding a new entry of type ConnectionString in the Settings page.
Again, what you type there will be stored in the app.config file in a specific section
<connectionStrings>
<add name="MyDb" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
Data source=C:\programdata\MyApp\Database.accdb;
Persist Security Info=False";/>
</connectionStrings>
and you can read it with
string myConnectionString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
See ConfigurationManager class on MSDN
I have developed a WinForm C# app that use ADO.NET Entity Framework for storing data.
I would like each user to have a database stored in their appdata\local folder but when I try to add the connection string to the users local app.config file I constantly get the error "ConfigurationSection properties cannot be edited when locked."
After I did some research I discovered the allowExeDefinition section setting.
I tried adding this setting for the connectionString section in the app.config file and at runtime (see code below) but I still get the same error whenever I try to save the configuration.
This is the code I use:
var connectionString = string.Format(ConnectionStringBase, dbLocation);
var exeConf = ConfigurationManager
.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
var connectionStringSettings =
new ConnectionStringSettings(
"DatabaseEntities",
connectionString,
ProviderName);
exeConf.ConnectionStrings
.SectionInformation
.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
exeConf.ConnectionStrings.ConnectionStrings.Add(connectionStringSettings);
exeConf.Save(ConfigurationSaveMode.Minimal);
I have tried to search for a solution for this issue for days but I haven't been able to find anything usefull besides that I am considering storing the connection string in the users settings instead as a workaround but it feels kinda hackish.
Alright, instead of updating the app.config file I decided to create the connectionstring on runtime and pass it to the entity set constructor.
So when I initialize the entity set I use the following code instead:
var connectionString = string.Format(ConnectionStringBase, dbLocation);
var entities = new DatabaseEntities(connectionString);
The only thing to note is that if the connection string contains " you should replace these with single quotes ( ' ).
When I add a database to a program, Visual Studio automatically creates the following connection string:
<connectionStrings>
<add name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString" connectionString="Data Source=|DataDirectory|\PlayerTeam.sdf" providerName="Microsoft.SqlServerCe.Client.3.5" />
<add name="PlayerTeamEntities" connectionString="metadata=res://*/edmPlayerTeam.csdl|res://*/edmPlayerTeam.ssdl|res://*/edmPlayerTeam.msl;provider=System.Data.SqlServerCe.3.5;provider connection string="Data Source=|DataDirectory|\PlayerTeam.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
I am trying to allow the user to select the database that they would like to open. How do I modify the connection string programmatically without losing my associated dataset and tableadapter?
Thanks in advance :)
you can use that method to call your connection string from your App.Config file to be used in the data connection or adapter
public string GetConnectionStringByName()
{
string returnValue = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Connection Name Here"];
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
when you add a new database to your project it takes the same connection Name of the existing database plus a number by default.
so you can make the connection string as a variable and add the number to it when you add a new database.
Edit
By considering you will add databases to your project grammatically, then if you added a new data base.
it will take that connection string's Name:
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString1"
as it add a number at the end of the name of the existing database
so, you can invest the method i provided, to add the specified connection string Something like that:
public string GetConnectionStringByName(int DB_Number)
{
string returnValue = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Connection Name Here"];
if (settings != null)
returnValue = settings.ConnectionString+Convert.ToString(DB_Number);
return returnValue;
}
as the DB_Number variable could be saved in an XML file in order not to be loosed and its increased each time you add database.
So, if you add a new database to the existing 1 the connection Name should be:
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString1"
and if you added another database the DB_Number will be increased by 1 to change the connection name to be :
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString2"
and enable the user to choose with connection string he wants to use.
on the other hand . if your databases added manually before the application runs.
it will be easier to Handle as what you just have to do is to save your connection string in a data structure as an array and call the wanted connection to use
that is what i figured out from your question
I want to change the DB string connection I have stored in Web.config file depending on where is run the application.
I know how to read but, do anybody have an idea how to to change it?
http://geekswithblogs.net/AzamSharp/archive/2005/10/09/56457.aspx
Third link to come up on a BING search.
private void GetConfigSettings()
{
string path = Server.MapPath("Web.config");
string newConnectionString = #"(Your connection string here)";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
XmlNodeList nodeList = xDoc.GetElementsByTagName("appSettings");
XmlNodeList nodeAppSettings = nodeList[0].ChildNodes;
XmlAttributeCollection xmlAttCollection = nodeAppSettings[0].Attributes;
xmlAttCollection[0].InnerXml = txtKey.Text; // for key attribute
xmlAttCollection[1].InnerXml = newConnectionString; // for value attribute
xDoc.Save(path); // saves the web.config file
}
New answer based on your comment on my original answer
You can use the String.Replace function. The ConnectionString is just a string.
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
connectionString = connectionString.Replace("TextToReplace", "ReplacementText");
so assuming your connection string is
"Data Source=LiveDbServer;Initial Catalog=MyDataBase;Persist Security Info=True;User ID=someUserId;Password=yourPassword"
You could use the following logic
if(System.Environment.ServerName == "MyTestServer")
{
connectionString = connectionString.Replace("LiveDbServer", "TestDbServer");
}
The following is just based on a guess as to why you might want to change connectionstrings at run-time based on which server the app is running on
ALTHOUGH (added bonus idea) if your goal is to always have your test web server point to your test DB server and your live web server point to your live DB server, an easier method is to edit the HOSTS file. (I'm sure there are other options, but that was a simple enough hack for us, and it works with database connections, web service references, etc.)
Simply set up the hosts file on the test machine so that it maps "MyLiveDbServer" to the ipaddress of "MyTestDbServer", and viola - your apps will point to the test server without any extra code or configuration, automatically, and for all time.
I used to load the connection string into the Application object (for better or worse) in the Application_Start event of global.asax.
Then, I get the option of checking which server I'm running on and loading that connection string into the Application object, rhather than relying on just a single entry in web.config.
Example:
<connectionStrings>
<add name="testservername" connectionString="..." providerName="..."/>
<add name="prodservername" connectionString="..." providerName="..."/>
<add name="localhost" connectionString="..." providerName="..."/>
</connectionStrings>
...in global.asax:
<%# Import Namespace="System.Configuration.ConfigurationManager" %>
...
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application("cn") = ConnectionStrings(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_HOST"))
End Sub
So then, every time I would have used ConnectionStrings("cn"), I will instead use Application("cn").
Check to see what HTTP_HOST gives you on each server and name your connection strings accordingly.
Alternately, you could just use ConnectionStrings(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_HOST")) all over instead of storing the whole string in Application.
Another option would be to just store the host name in the Application variable to pass to ConnectionStrings any time you need it.