In my project I have a method which needs to return a ConnectionStringSettings object. As the database and server name will change dynamically, I need to dynamically
construct the connection string.
How do I convert a string to ConnectionStringSettings?
public ConnectionStringSettings getConnection(string server, string database)
{
//ConnectionStringSettings connsettings = new ConnectionStringSettings();
string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString();
connection = string.Format(connection, server, database);
// Need to convert connection to ConnectionStringSettings
// Return ConnectionStringSettings
}
--Web.config
<add name="myConnString" connectionString="server={0};Initial Catalog={1};uid=user1;pwd=blah; Connection Timeout = 1000"/>
The ConnectionStringSettings class constructor has an overload that takes two strings (first is the name of the connection string and the second is the connection string itself).
public ConnectionStringSettings getConnection(string server, string database)
{
string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString();
connection = string.Format(connection, server, database);
return new ConnectionStringSettings("myConnString", connection);
}
There's a third overload that takes in an extra string for the name of the provider.
Related
I have a project that uses entity framework data model(.edmx) in it's data layer.I want to add work station id in connection string to store it during create log in database.
This is what I do:
var d = new PresentModelConnectionString();
string connectionString = d.Database.Connection.ConnectionString;
string lastCharacter = connectionString.Substring(connectionString.Length - 1, 1);
if (lastCharacter == ";")
{
connectionString += $"workstation id={Helpers.UserId.ToString()}";
}
else
{
connectionString += $";workstation id={Helpers.UserId.ToString()}";
}
d.Database.Connection.ConnectionString = connectionString;
return d;
But when it tries to connect to database and get data returns The login for user sa failed.When I remove this line:
d.Database.Connection.ConnectionString = connectionString;
It works fine.
This is the connection string:
<add name="PresentModelConnectionString" connectionString="metadata=res://*/PresentModel.csdl|res://*/PresentModel.ssdl|res://*/PresentModel.msl;provider=System.Data.SqlClient;provider connection string="data source=192.168.1.101\sql2014;initial catalog=MIS;user id=sa;password=sa_123;connect timeout=600000000;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
How can I include work station id dynamically to connection string?
Thanks
After searching several hours I found this solution, it change the connection string of entity framework database first model.As Alex recommended in comments I should use SqlConnectionStringBuilder to make connection string.
Create a partial class for model context in a separate file for adding constructor that gives connection string as parameter:
public partial class PresentModelConnectionString
{
public PresentModelConnectionString(string connectionString):base(connectionString)
{
}
}
Make connection string:
//connection string in web.config
//Data Source=192.168.1.101\sql2014;Initial Catalog=MIS_Keshavarzi_980906;user id=sa;pwd=sa_123; Connect Timeout=60000;
string connectionString =
System.Configuration.ConfigurationManager.AppSettings["ABSConnectionString"];
SqlConnectionStringBuilder connectionStringBuilder = new
SqlConnectionStringBuilder(connectionString);
connectionStringBuilder.WorkstationID = Helpers.UserId.ToString(); //get work station id
connectionStringBuilder.ApplicationName = "EntityFramework"; //set application name
For modifying the model connection string use EntityConnectionStringBuilder:
EntityConnectionStringBuilder entityConnectionBuilder = new
EntityConnectionStringBuilder();
entityConnectionBuilder.Metadata =
"res://*/PresentModel.csdl|res://*/PresentModel.ssdl|res://*/PresentModel.msl";
entityConnectionBuilder.Provider = "System.Data.SqlClient";
entityConnectionBuilder.ProviderConnectionString =
connectionStringBuilder.ConnectionString;
PresentModel should change with your model name.
Finally create a new instance of model context with this connection string:
var entityContext = new
PresentModelConnectionString(entityConnectionBuilder.ConnectionString);
I recently converted a Delphi app to C#, and I'm having an issue with an SQL connection. For some reason, when calling the CheckConnection function (shown below), IF my connection string has empty parameters, the connection is still able to .Open() without errors. Why is this? I feel like my CheckConnection function has an issue, or maybe I'm not understanding how .Open() actually works.
How it's set up - There are some textboxes that contain the hostname, user, etc. which are used as the parameters for the the connection string. Everything works fine when those are filled out correctly, but when the parameters (aka the textboxes) are all left blank, the connection still opens.
String hostname, user, password, database, protocol, query;
string connString;
IDbConnection SqlConn;
DbProviderFactory factory;
public void SetConnectionParams()
{
hostname = ServerTextBox.Text.Trim();
port = StrToIntDef(PortTextBox.Text, 3306);
user = UserIDTextBox.Text;
password = PasswordTextBox.Text;
database = DBTextBox.Text;
protocol = ProtocolTextBox.Text; //MIGHT not need
GetConnectionString(); //Get the correct connection string
}
//Gets the connection string from app.config
//The parameters for the string are all set via textboxes in diff. part of code
public void GetConnectionString()
{
if (MySqlRB.IsChecked == true) //Sets up connection for MySQL
{
var cs = ConfigurationManager.ConnectionStrings["MySQL"];
connString = ConfigurationManager.ConnectionStrings["MySQL"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = String.Format(connString, hostname, port, database, user, password);
}
else //Sets up connection for MS SQL
{
if (WindowsAuth.IsChecked == true) //If windows authentication checkbox is checked
{
var cs = ConfigurationManager.ConnectionStrings["MSSQL_WA"];
connString = ConfigurationManager.ConnectionStrings["MSSQL_WA"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = string.Format(connString, hostname, database);
}
else //don't use windows authentication
{
var cs = ConfigurationManager.ConnectionStrings["MSSQL"];
connString = ConfigurationManager.ConnectionStrings["MSSQL"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = string.Format(connString, hostname, database, user, password);
}
}
}
//Supposed to check if the connection works or not
//This is working even if the connection string has empty parameters
public Boolean CheckConnection(bool check)
{
try
{
if (!CloseFirst && (SqlConn.State != System.Data.ConnectionState.Open))
{
return false;
}
else
{
using (SqlConn = factory.CreateConnection()) //make the connection
{
SqlConn.Close(); //make sure it's closed first just in case
SqlConn.ConnectionString = connString;
SqlConn.Open(); // Open the connection
if (SqlConn.State == System.Data.ConnectionState.Open)
{
SqlConn.Close();
return true;
}
else
{
return false;
}
}
}
}
catch
{
return false;
}
}
Example: Here's a connection string that's in my app.config for a sql server string:
<add name="MSSQL" providerName="System.Data.SqlClient"
connectionString="Data Source={0}; Initial Catalog={1}; User={2}; Password={3};" />
When debugging through the program, if I don't set any of the parameters, the string turns out like this:
connString = "Data Source=; Initial Catalog=; User=; Password=;"
That shouldn't be able to open right? It does though, and only when using SQL Server it seems, MySQL throws an error properly.
Edit:
Okay, turns out an error is not being thrown only when I use SQL Server windows authentication with this connection string:
<add name="MSSQL_WA" providerName="System.Data.SqlClient" connectionString="Data Source={0}; Initial Catalog={1}; Integrated Security=SSPI;"/>
Debugging through, the Data Source and Initial Catalog are empty, but the connection still opens. Not sure why this is?
I was given a method to get our database connection string to Sql Server:
SqlConnection GetConnectionString()
I call that and get what the connection string should be. If the database does not exist, I need the connection string without the database name in it. If I try to use the connection string with the database name in it, I get an error that it cannot connect to the database, which is it since it does not exist.
I am calling like this:
using (var connection = new SqlConnection(GetConnectionString().ConnectionString))
Is there a way to recreate the connection string easily without the database name?
SqlConnectionStringBuilder aBuilder =
new SqlConnectionStringBuilder(yourConnectionStringWithDatabase);
aBuilder.InitialCatalog = "";
string yourConnectionStringWithoutDatabase = aBuilder.ConnectionString;
It's easy
var connectionString = "data source=someInstance;initial catalog =someDatabase;etc.";
var pattern = "initial catalog[=\\s\\w]+;";
var dbRemoved = Regex.Replace(connectionString, pattern, "");
Note that I haven't handled case sensitivity, but this should be a good start for your requirements.
I know this question has been asked and answered a few times already, but every answer I have encountered has either been incomplete, overly vague or assumes more prerequisite knowledge than I have. I am seeking step-by-step instructions, in reasonably plain English, to swap out the database in my default connection string for a database name that will be looked up in a table. I keep coming across this snippet of code...
public DFDBEntities(string connectionString)
: base(connectionString)
{
}
...but no one really explains how, and where, to implement it. Assuming I have a class called "db" that represents my DataModel.EDMX model...
private DataModel db = new DataModel();
...how would I change the connection string associated with that class to point to a different physical database (with identical data structure)?
By using the default constructor you are basically saying "I want to use the default connection string" which is specified in the web.config.
The DbContext has a constructor overload which allows you override the default connection string, all you need to do is pass it in
db = new DataModel("MyConnectionStr");
Try :
private DataModel db = new DataModel(yourconnectionString);
You can use helper class for connenction settings like
public class EntityConnectionStringHelper
{
public static string Build()
{
string serverName = "******";
string databaseName = "****";
string password = "****";
string userid = "*****";
string meta = "********";
return EntityConnectionStringHelper.Build(serverName, databaseName, userid, password, meta);
}
public static string Build(string serverName, string databaseName, string userName, string password, string metaData)
{
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
return EntityConnectionStringHelper.Build(providerName, serverName, databaseName, userName, password, metaData);
}
public static string Build(string providerName, string serverName, string databaseName, string userName, string password, string metaData)
{
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = userName;
sqlBuilder.Password = password;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = string.Format(#"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", metaData);
return entityBuilder.ToString();
}
}
Than for your entity you can get intance with
DFDBEntities context = new DFDBEntities (EntityConnectionStringHelper.Build());
How to create authentication window for database when I use dataset - MyDatabaseDataSet?
When I didn't use dataset I simply open new SqlConnection for every operation and use some connection string which was created after I writed Login and Password. But Dataset use some default connection string. How to change it?
I want to connect to database and tables with connection string Data Source=XXXX-PC\MSSQLSERVER2;Initial Catalog=MyDatabase;User ID={0};Password={1} where {0} and {1} - parameters from authentication window.
I don't understand where to put my connection string and then use it as default connection string.
I've had problems in the past with DataSet objects using a default connection string.
To get around this, I pass the connection string into my SqlConnection constructor.
In my case I'm using a web.config to hold the connection string.
var dt1 = new CustomDataSet.CustomDataTable();
var connectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString
using (var connection = new SqlConnection(connectionString))
{
using (var da1 = new GetCustomDataTableAdapter() { Connection = connection })
{
da1.Fill(dt1, id);
}
}