Moving connection string from app.config to code in C# - c#

I'm trying to use Entity Framework and it put it's connection string into app.config. I would like to move it to code as it's easier for me at this stage of development.
metadata=res://*/database.csdl|res://*/database.ssdl|res://*/database.msl;provider=System.Data.SqlClient;provider connection string="data source=computer;initial catalog=database;persist security info=True;user id=user;password=Mabm#A;multipleactiveresultsets=True;App=EntityFramework"
How can I make Entity Framework use connection string from code rather then look at the app.config? Alternatively if it's not possible how can I pass parameters to app.config (like dbname, dbuser, dbpassword)?

You can use EntityConnectionStringBuilder for this purpose.
Check here
public string GetConnectionString()
{
string connectionString = new EntityConnectionStringBuilder
{
Metadata = "res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new SqlConnectionStringBuilder
{
InitialCatalog = ConfigurationManager.AppSettings["SystemDBName"],
DataSource = ConfigurationManager.AppSettings["SystemDBServerName"],
IntegratedSecurity = false,
UserID = ConfigurationManager.AppSettings["SystemDBUsername"],
Password = ConfigurationManager.AppSettings["SystemDBPassword"],
MultipleActiveResultSets = true,
}.ConnectionString
}.ConnectionString;
return connectionString;
}

When you create an instance of your ObjectContext derived class, you can simply pass the connection string as a constructor argument.

Rather than use a username and password, why not use Integrated Security? It is more secure and easier to manage.
i.e. 'Trusted_Connection = Yes' in your connection string and securely manage access through AD.
Connection Strings

First, create your context using the constructor with the connectionString parameter.
http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx
Note that it's not directly this constructor that you must call, but the specific inherited context constructor for your database that your Entity generator created for you.
Furthermore, if you want to pass the username and password at runtime, you can create a connection string using this class:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx
See here:
http://msdn.microsoft.com/en-us/library/bb738533.aspx

If the connection string log in details are always the same then I would suggest that you use ConfigurationManager to retrieve the connection string from your app.config and encrypt the ConnectionStrings section of the file.

Related

How can i get the password of oracle user instance from oracle connection string using C#?

I want to get the user id and the password of oracle db instance from the connection string that i have stored in my App.config file.
Here is the connection string stored in App.Config File
<add name="MyConnection" connectionString="Data Source=xe;User ID=UsmanDBA;Password=root;" providerName="System.Data.SqlClient" />
I have tried OracleConnectionString Builder but it does not return the password of connection string Here is the code:
public string ConPass()
{
OracleConnectionStringBuilder builder = new OracleConnectionStringBuilder();
builder.ConnectionString = con.ConnectionString;
return builder.Password;
}
this method does return the user id but not the password
Is there something i am missing? or is there any other way to do this?
Kindly help me to sort this out..
ConnectionString property never contains password. That is the security measure. In your code, password has been lost in this line:
builder.ConnectionString = con.ConnectionString;
You have to devise a different approach. For example, to read the connection string from config and then to feed it to the connection string builder. This might not be generally applicable if you only have the connection and no information from which config entry it was constructed...
On a related note, SQL Server connection (SqlConnection) exposes the Credential property which could be used to read password (I haven't actually tried this). I don't know of similar property in Oracle connection implementation.
You can make use of the SqlConnectionStringBuilder
string conString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
OracleConnectionStringBuilder builder = new OracleConnectionStringBuilder(conString);
string user = builder.UserID;
string pass = builder.Password;

Removed database out of connection string

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.

Entity Framework 6.0 + Encrypt Connection String

This question may be repeated but we were not able to find a good solution.
Our project uses EF 6.0 & C# and targeted for .NET 4.0 and above and finally SQL Server 2012.
The project works fine without. But have few queries on the EF connection string and the way it stores.
How to read the encrypted connection string stored in the app.config to be read in the EF's context.cs file.
We added the following code to read encrypted connection string, it works but to an extent only i.e. till we don't add the a new stored procedure.
public MCMS_II_LogEntities()
// : base("name=MCMS_II_LogEntities") //Original
:base( GetConnectionString())
{
}
public static string GetConnectionString()
{
string connString = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = "<Catalog Name>",
DataSource = ConfigurationManager.AppSettings["DataSourceAddress"].ToString(),
IntegratedSecurity = false,
MultipleActiveResultSets = true,
UserID = "<LOGIN ID>", // User ID such as "sa"
Password ="<PASSWORD>", // hide the password
}.ConnectionString
}.ConnectionString;
return String.Format(connString);
}
Once we add the new stored procedure or function to the EF model, the above coded added will be removed.
Query
What is the best practice to achieve this?
How to address this issue.
During the development process you shouldn't encode/encrypt the db connection string, it's a pain in the butt. The encryption should be done during the deployment/promotion phase not during development.
Test the connection string AFTER you have encrypted it. Encrypt it when you are ready to move the code to QA or PROD.

Update EF5 Model ConnectionString in Runtime

I have winforms app with SQL Db on my localServer. I added EF5 using Database_First.
The question is:
How to change the connection string of EF5 Model in "Runtime" using "OpenFileDialog"?
I want to provide the app with a "Feature" to let the client specify his Database Server where the app db is located.
There are two problems that need to be considered.
First DbContext has constructor that takes a user defined connection string, but this constructor is not exposed in the generated code for your context, so you have to add it in a partial file outside of the generated code.
And then the Entity Framework connection string itself differs from a typical SqlClient connection string, so you have to use EntityConnectionStringBuilder to build an appropriate connection string.
For example consider this sample code:
public partial class MyContext: DbContext
{
public MyContext(string efConnectionString):base(efConnectionString)
{
}
public static MyContext CreateContextFromAdoCS(string adoConnectionString)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = adoConnectionString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/MyModel.csdl|
res://*/MyModel.ssdl|
res://*/MyModel.msl";
var efCs = entityBuilder.ToString();
return new MyContext(efCs);
}
}
If you have an existing SqlClient connection string you can use the factory method to create an instance of your context.
Here Display a ConnectionString dialog you can see how to open a standard dialog to construct an SqlClient connection string.
Let it be in App.config
<add name="ConnectionStringNew" connectionString="Data Source=ServerName;user id=sa;Password=sasa;initial catalog=[DataBase]" />
Have a Combobox where you want to let the user to select the DataBase.
FIll the combobox with below coding.
SqlConnection con1 = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringNew"].ConnectionString);
SqlCommand comm = new SqlCommand("SELECT ROW_NUMBER() OVER(ORDER BY NAME) AS ID,NAME FROM SYS.SYSDATABASES WHERE DBID > 4 ORDER BY NAME", con);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dtblDataBase);
cmbDataBase.DataSource = dtblDataBase;
cmbDataBase.ValueMember = "ID";
cmbDataBase.DisplayMember = "NAME";
Replace the DataBase Name Like below.
DataBaseName = Convert.ToString(con1.ConnectionString);
CommonVariables.strDataBaseName = DataBaseName.Replace("[DataBase]", cmbDataBase.Text.Trim());
CommonVariables.strCompanyName = cmbDataBase.Text.Trim();
I have just given a coding sample.. Customize it as you want.

How To Work With SQL Database Added As Item In Visual Studio 2008?

If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)

Categories