How to set UserID and Password in EnterpriseLibrary 6.0 - enterprise-library

I have coded like the below:
#Code
DatabaseProviderFactory factory = new DatabaseProviderFactory();
database = factory.Create("DBinstanceName");
ConfigFile Entries
<oracleConnectionSettings>
<add name="CNQ" />
</oracleConnectionSettings>
<connectionStrings>
<add name="CNQ" connectionString=" Min Pool Size=0;Connection Lifetime=120;Max Pool Size=50; Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST= XXXX.com)(PORT=1521))) (CONNECT_DATA = (SID = cnq) (SERVER = DEDICATED) ) );"
providerName="Oracle.DataAccess.Client" />
</connectionStrings>
With the above code and config settings, the DatabaseObject is created perfectly. When I verify the connectionstring it has the values what I had mentioned in the connnection string. So far good.
Now, I have to add the UserId & Password to the connection string at the runtime. There is no methods I could find to add the user credentials to the existing connection string. Becuase, in the Database object the connection string is READ ONLY.
The only way I find is to set in the configuration file[App.config], which is not the way we want, because for every user, we have a separate userid and password in the Oracle database.
In fact, I had tried by settings the connections at the command object, and passed the command object to the execute reader, even then also the enterprise library 6.0, not taking the connection we set in the command object.
Please help us how to set the userid and password in the runtime.
Thanks in advance

In order to set connection string values at runtime you will have to programmatically create your database objects. For example:
Database database = new GenericDatabase(GetConnectionString(),
DbProviderFactories.GetFactory("Oracle.DataAccess.Client"));
Or if you are using OracleDatabase something like:
OracleDatabase database = new OracleDatabase(GetConnectionString());
You could use extension methods to hide a bit of the ugliness:
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.CreateWithConnectionString(GetConnectionString(),
DbProviderFactories.GetFactory("Oracle.DataAccess.Client"));
db = factory.CreateOracleDatabase(GetConnectionString());
public static class DatabaseProviderFactoryExtensions
{
public static Database CreateWithConnectionString(this DatabaseProviderFactory factory,
string connectionString,
DbProviderFactory dbProviderFactory)
{
return new GenericDatabase(connectionString, dbProviderFactory);
}
public static Database CreateOracleDatabase(this DatabaseProviderFactory factory,
string connectionString)
{
return new OracleDatabase(connectionString);
}
}
Another way to approach the issue if you know what connections you will have in advance (still at runtime but perhaps at application startup) is to use the DatabaseFactory.SetDatabases method to return the correct database based on a key. Unfortunately, the method only takes a single string so you can't specify nicely the username and password but you might be able to do something like this:
DatabaseFactory.SetDatabases(() => GetDatabase("Default"),
(dbName) => GetDatabase(dbName));
Database db = DatabaseFactory.CreateDatabase();
public Database GetDatabase(string dbName)
{
string connectionString = GetConnectionString(dbName);
return new OracleDatabase(connectionString);
}
Where the GetConnectionString method can create the proper connection string based on a name. However, I'm guessing this last way might not be the best given your description.

Thanks for your response.
Because I am using the Enterprise Library 6.0, only the First answer only works.
Database database = new GenericDatabase(GetConnectionString(),
DbProviderFactories.GetFactory("Oracle.DataAccess.Client"));
[or]
Oralce.DataAccess.Client.OralceClientFactory ocf = new Oracle.DataAccess.Client.OracleClientFactory();
Database database = new GenericDatabase(GetConnectionString(), ocf);
Thanks

Related

c# SqliteConnection set password to database

using Microsoft.Data.Sqlite;
private readonly string connectionString = #"Data Source=C:\DataBase\FichasPacientes.db";'''
The below connection string get me an error about version not recognized keyword.
//private readonly string connectionString = #"Data Source=C:\DataBase\DB.db;Version=3;";
My investigation led to me to this way to set the password, but the function don't exist.
using (SqliteConnection connect = new SqliteConnection(connectionString))
connect.SetPassword("password");
How can I set the password to the sqlite database?
In using (SqliteConnection connect = new SqliteConnection(connectionString))
You need to set the Password in your connectionString
Example
Data Source=c:\mydb.db;Version=3;Password=myPassword;

EntityConnection throws the exception when create the connection instance

In my EF project if I execute the following
using (EntityConnection con = new EntityConnection("name=HCMConnection"))
it throws the exception
The specified named connection is either not found in the configuration,
not intended to be used with the EntityClient provider, or not valid.
The connection string is in the Web.Config and it looks like following
<add name="HCMConnection" connectionString="Data Source=DEV-PROG-01;
Initial Catalog=HCM;
user id=HCMUser;
password=*******;
MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
I suspect it does no like the SqlClient provider, does not it?
Thanks.
I believe you should have (replace settings class with the correct one for your app type). There is no EntityConnection constructor that can take the connection string name as a param to work.
using (EntityConnection con = new EntityConnection(SettingsClass.HCMConnection))
However its probably a better idea to let the dbcontext manage the connection instead of doing it manually, this constructor can take just the connection name.
using (MyDbContext con = new MyDbContext ("HCMConnection"))
And even better in your context class
public MyDbContext()
: base("HCMConnection")
Paul
Not clear what is the SettingsClass in my case, but I decided to use the same context to use its connection:
public ActionResult Education(ModelHCMContainer model)
{...
and execute the following
using (DbCommand cmd = model.Database.Connection.CreateCommand())
{
model.Database.Connection.Open();
try
{
cmd.CommandText = String.Concat("select ed.*,", ...
"order by ed.DateStart DESC");
using (var _reader = cmd.ExecuteReader())
{
using (ModelHCMContainer context = new ModelHCMContainer())
{
var records = ((IObjectContextAdapter)context).ObjectContext.Translate<HCMApplication.Models.POCO.Profile.HCMEducationPOCO>(_reader);
items = records.ToList();
}
}
}
finally
{
model.Database.Connection.Close();
}
}
It seems like working fine.
Thanks.

Entity Framework - Database First without config

I'm developing a class library that deals with an exiting db using EF. I want to avoid the consumer of the class library (and .exe or a web site) to have in the *.config file the Entity connection string. I want the connection string set a run-time.
How do I set the connection string with Database First approach? There is no constructor overload that takes a connection string and when I created one (in a separate partial class) I got an "UnintentionalCodeFirstException".
I have reviewed already the following links:
Is there a way to change connection string in database first?. Its about modifying the connection string in the config file, which I want to avoid, also because it would recycle the process (in the case of a web app)
How can l use Entity Framework without App.config. Not good because it uses ObjectContext and I need the context generated when I imported the database.
There is a constructor on DbContext that takes a DbConnection, and you need to use an EntityConnection object for it:
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = "server name";
sqlBuilder.InitialCatalog = "database name";
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
var entityBuilder = new EntityConnectionStringBuilder();
// Initialize the EntityConnectionStringBuilder.
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
using(var context = new YourDbContext(entityBuilder.ToString())){
//do stuff here
}
The important thing to note is the metadata part - "Model1" obviously needs to be replaced for your model name.
Ref: http://msdn.microsoft.com/en-us/library/bb738533.aspx
EDIT 20/02/2013 22:25
So as an addition you'll need to extend the created DbContext class with a partial class that adds a constructor to support the above code, like this:
public partial class YourDbContext
{
public YourDbContext(string connection) : base(connection) {}
}
This class needs to be in the same namespace as the DbContext that is generated by the entity framework wizard.

Passing ConnectionString for Entity constructor must include provider="System.Data.SqlClient" & providerName="System.Data.EntityClient"

I need to pass a the connection string to an Entity object constructor (cannot be stored in config).
I have successfully used the EntityConnectionStringBuilder to connect to the database but believe because it does not allow me to add providerName="System.Data.EntityClient" (only the provider property > provider="System.Data.SqlClient") will not let me update the database.
How can this be passed to the constructor along with the connection string from the string builder.
My connection string is basically identical to this
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient"
You don't have to set the outer providerName - you just need to replicate the connectionString entry from your web.config.
var sqlBuilder = new SqlConnectionStringBuilder();
...
var entBuilder = new EntityConnectionStringBuilder();
entBuilder.ProviderConnectionString = sqlBuilder.ConnectionString;
entBuilder.Provider = "System.Data.SqlClient";
entBuilder.Metadata = "res://...";
using ( var db = new AdventureWorksContext( entBuilder.ConnectionString ) )
{
...
Also, your metadata configuration looks odd. I have always used this format:
metadata=res://*/AdventureWorks.csdl|res://*/AdventureWorks.ssdl|res://*/AdventureWorks.msl;
If you're using Code First, you just need the SQL Connection String.
See this question: Entity Framework Code First and Connection String Issue

Best way to retrieve the connection string for IBATIS.NET from the web.config

I have an web application where I have a requirement to encrypt and store the connection string in the web.config.
What is the best way to retrieve this and use this connection string with IBATIS.NET instead of storing the connection string in the SqlMap.config?
The last three messages of this discussion thread discuss what you want.
Essentially, you're overwriting the connection string iBATIS loads from the config file before your call to Configure().
For example, in your SqlMap.config:
<database>
<provider name="sqlServer2005" />
<dataSource name="TheDB" connectionString="${connectionString}"/>
</database>
And in your code where you configure the builder, something like:
DomSqlMapBuilder builder;
string connection;
NameValueCollection properties;
connection = AccessTheEncryptedStringHere();
// Put the string in collection to pass to the iBATIS configurator
properties = new NameValueCollection();
properties.Add("connectionString", connection);
// Build the iBATIS configurator
builder = new DomSqlMapBuilder();
builder.Properties = properties;
builder.Configure("SqlMap.config");
Are you looking out for this? retrieving the encrypted connectionstring from web.config--
You can try the foll. code--
name of the connection string is omni_dbConnectionString
string connectionString = ConfigurationManager.ConnectionStrings["myProtectedConfigProvider"].ProviderName;
or
string connectionString = ConfigurationManager.ConnectionStrings["omni_dbConnectionString"].ConnectionString;