How to create connection string that independent on instance and server name? - c#

i want my application can run on every device that maybe have different server name and instance. my connection string is below:
DBDataContext db = new DBDataContext(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_data\DB.mdf;Integrated Security=True;User Instance=False");

If I understand you correctly and the Data Source is always on the local server, why don't you get the ip address of the server with System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
string myLocalserverIP = System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
then use that in your Data Source string.

Related

Change connectionString dynamically

I have a WinForm C# application that uses SQL server which needs to be accessed through VPN, the original connectionstring that we have on the server is:
connectionString="Data Source=localhost;Initial Catalog=MyDB;user id=myuser;password=mypass"
This connection string is at the app.config file
Everyone in the LAN can access the app and execute just fine, now when we connect through VPN, the connection to the SQL database doesn't work (obiously because the connectionstring needs to be different)
The IP we get when we connect using VPN may not always the same so my question is, can I dynamically change the connectionstring so that the user can input the Source when using VPN?
Thanks
Use String.Format() to gernerate the connection string.
string datasource = DatasourceTb.Text; // get value from user input.
string catalog = "MyDB";
string username = "myuser";
string password = "mypass";
string connectionString =
String.Format("Data Source={0}; Initial Catalog={1}; User Id={2}, Password={3};",
datasource,
catalog,
username,
password
);

Parameters needed to connect to a MySql Database using C#

When I want to connect to Database using C# visual studio 2013, I provide the following parameters to the "connectionString" using "MySqlConnection":
string server="localhost";
string database="database123";
string uid = "*****";
string password = "******";
string port = "3306";
but I noticed that if I don't provide "database" or "port" it works fine too.
My question is what should one provide to establish a proper connection?
or What is considered sufficient info to establish a connection?
I would use this.
SqlConnection connection = new SqlConnection("server=somthing; database=something; User ID=******; Password=******");

Mysql connect to server without any database

In my program C# program I need to create several mysql databases if they don't exist on the mysql server.
So I created a connection string to the server:
add name="ServerConnection" connectionString="Server=localhost;Port=7070;uid=root;password=pass;" providerName="MySql.Data.MySqlClient"/>
Once the databases are created how can I use the existing connection to connect to one of the databases ?
Should there be a connection string for each database on the mysql server ?
Thanks
No you don't need to create separate connectionstrings in your config file for each database you have the need to create.
You could use the, not so well known, class called MySqlConnectionStringBuilder living in the usual namespace MySql.Data.MySqlClient.
This class allows to specify any single key/value pair required by your connectionstring.
It also accepts, as a constructor parameter, a previous connection string that is internally splitted in the various key/value pairs and then it exposes these key/value pairs as properties of an instance of the MySqlConnectionStringBuilder.
This permits to change one property (the Database for example) and then rebuild a connection string with the updated values.
So for example you could write
MySqlConnectionStringBuidler mcb = new MySqlConnectionStringBuilder("yourinitialconnectionstring");
mcb.Database = "yournewdatabasename";
string newConnString = mcb.GetConnectionString(true);
using(MySqlConnection cnn = new MySqlConnection(newConnString))
{
......
}
The final call to GetConnectionString requires a boolean value set to true if you want the connectionstring returned to contain the password.
(Example based on MySql Provider 6.3.6)

Asp.net MVC2 - Multiple databases

I have a database called
"Config" where I have a table called "Customer"
In the Customer table I hold the login credentials, along with a connection String to the client's database.
Inside of my controller I'm checking to see what customer database i'm querying
String connectionString = "";
if (id == 1)
connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Client1.mdf;Integrated Security=True;User Instance=True";
else if (id == 2)
connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Client2.mdf;Integrated Security=True;User Instance=True";
using (TestDbaseDataContext db = new TestDbaseDataContext(connectionString))
{
var searchRecords = db.SearchRecords;
return View(searchRecords.ToList());
}
There will be an undetermined number of client's using separate databases, these connection strings will change based on archived status, and other factors. I don't think hard coding these strings in app.config will do what I need.
I have a "Master" database, that holds all of the client's configuration settings, along with the client's database connection string. The mater database is only used to mitigate which client database to search. I store the connection strings in the master database so I can pass that connection string for the logged in customer to query the correct database. It is a requirement to have each client in it's own database
How would you store this connection string so I can pass to my datacontext when needed?
Should it be stored in a session variable, or should I query the Config database Customer table in each controller method?
I've set up a similar "siloed" multi-client application before. This is a good case for a session variable. Each user relates to a client, which has its own database. On login, each user should get a "context" object in Session state containing all necessary identifying data, including database connection string.

How do I get the Application Name from either SQL Server connection string or the IIS application name using C#?

How do I get the Application Name from an SQL Server connection string in the web.config file.
I want to use to log escalated error messages from a web application into the Windows Event Log.
Maybe there is a better way of doing this, ie using the IIS/Web application name?
Thanks
Mark
What does the connection string look like?
DbConnectionStringBuilder is good for parsing and inspecting connection-string values by key:
DbConnectionStringBuilder db = new DbConnectionStringBuilder();
db.ConnectionString = connectionString;
Console.WriteLine(db["Application Name"]);
otherwise you can get various details from the http server variables.
SqlConnectionStringBuilder is also useful if you are using SQL Server:
SqlConnectionStringBuilder sc = new SqlConnectionStringBuilder(connectionString);
string applicationName = sc.ApplicationName;

Categories