How to use a dynamic connection string in asp.net? - c#

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.

Related

Set database connection string at run time

I am working on a MVC 4 web site. It should allow the user to select which database to be connected with depending on user selection from the View. All the databases have the same table structure and schema etc.
I have a database ConnectionString defined in the Web.config file that allows for connection to the first database.
<connectionStrings>
<add name="DBConnectionString" connectionString="Data Source=DATABSE_SERVER;Initial Catalog=DATABASE_NAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD" providerName="System.Data.SqlClient" />
</connectionStrings>
I also used Linq DataContext to initialize connection to the database. Table mappings were all automatically generated by Linq to SQL in MVC 4.
public NEMP_DataDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
What is the best way to achieve this?
In LINQ to SQL, you just create the Context with the connection string:
DataContext myContext = new DataContext(customConnectionString);
You don't need to worry about closing them or anything. SQL Server is handling all that for you. So you simply adjust the connection string slightly (Database Name) and create a new context based on whatever variable in every page you need to use the Context.
You can use the ChangeDatabase method of SqlConnection
See MSDN.
First of all, you should have a storage to get all of the database connections.
Maybe the storage is a xml file or a simple database.
But you need to implement how to get the connection strings.
If you have used EntityFramework for your dataconext in your applicaiton.
You could have a constructor like the folowing code:
public ApplicationDbContext(string nameOfConnection)
: base(nameOfConnection)
{
this.Configuration.ProxyCreationEnabled = true;
this.Configuration.LazyLoadingEnabled = true;
}
Please invoke the 1 and get the nameOfConneciton, then invoke 2 to initialize the DbContext.
I'm not sure if I understand your question fully. But I assume you ask us that you want to let the user select the database they want to connect to. Then set the connection string.
Here's my solution, for example if you have 5 database to let user to select. You write those 5 connection string into web.config. Then make something like a drop down list or radio button that let's user to select database. And then make a if statement. For example if the first radio button is selected then
String connection string=connection.string["the name of connection string in web.confug"];
I hope this help you

Changing dataset connectionstring at runtime vs2010

I found a solution that must be for a older version then vs2010. I would like to know how to do this for vs2010? Does anyone know?
http://www.csharpbydesign.com/2008/01/overriding-dataset-settings-co.html
Let me explain little more detail.
I have a c# generated dataset. How can I change the connection string so I can use the dataset with another (identically structured yet differently populated) database? This has to occur at runtime as I do not know the server or database name at compile time. i AM USING vs2010 and SQL Server 2008 R2 Express
I think there is no simple way and you cannot change the Connection-String programmatically for the entire DataSet since it's set for every TableAdapter.
You need to use/create the partial class of the TableAdapter to change the connection-string since the Connection property is internal (if your DAL is in a different assembly). Don't change the designer.cs file since it will be recreated automatically after the next change on the designer. To create it just right-click the DataSet and chose "show code".
For example (assuming the TableAdapter is named ProductTableAdapter):
namespace WindowsFormsApplication1.DataSet1TableAdapters
{
public partial class ProductTableAdapter
{
public string ConnectionString {
get { return Connection.ConnectionString; }
set { Connection.ConnectionString = value; }
}
}
}
Now you can change it easily:
var productTableAdapter = new DataSet1TableAdapters.ProductTableAdapter();
productTableAdapter.ConnectionString = someOtherConnectionString;
Here's a screesnhot of my sample DataSet and the created file DataSet1.cs:
There's actually a much easier way to change the connection string.
Go to the Settings screen, where the connection string is displayed as a connection string.
First mark and copy the connection string that's displayed.
Then change the type from connection string to string. The text for the string will change to include xml.
Then paste the copied connection string over the xml text.
Then change the scope from Application to User.
When I want to change the connection string, I use the following code.
// assign the path to use to the variable fullpath (or whatever)
string newConnection = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", fullpath);
Properties.Settings.Default.HootConnectionString = newConnection;
Properties.Settings.Default.Save();
In my case, I have a global Dataset active, so I have to make that the data is reread by the tableadapter. And, of course, you'll have to add error control to make sure the database is still there.
You'll notice that this will not change what is displayed in Application Settings. Those are defaults.
This works for an Access database; so your mileage and requirements may vary.
EDIT: Caveat. As it works out, when installed, the connection string works well for opening and reading database content, but it complains about not having a connection string when trying to update a database.

Modify default connection string for SQL Server Compact Edition

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

How to change DbEntry settings at runtime

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.

How to connect published Visual C# solution to a different database

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...

Categories

Resources