Trying to concatenate database name in connection string - c#

I am trying to concatenate database name in connection string like this:
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
base.Initialize(name, config);
string connectionString = "Server=My-PC\\SQLEXPRESS; Database="+name+";Integrated Security=True; App=EntityFramework;";
FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
connectionStringField.SetValue(this, connectionString);
}
But it throws exception: login failed for the database.
When I hard code the database name it works:
string connectionString = "Server=My-PC\\SQLEXPRESS;
Database=mydb;Integrated Security=True; App=EntityFramework;";
Anyone please guide me what am doing wrong.
Thanx
EDIT:
I have also tried this:
`string domaniName = Helpers.RouteManager.GetSubDomain();
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder["Data Source"] = "MY-PC\\SQLEXPRESS";
sqlBuilder["Initial Catalog"] = domaniName+"_db";
sqlBuilder["Integrated Security"] = true;
sqlBuilder["Application Name"] = "EntityFramework";`
but still getting the same result. When i hardcode dbname it works fine.
Please guide me.
Thanx.

Related

How to pass ConnectionString parameters with variables?

I have a ConnectionString and I want to pass it values (DataSource, Database, User ID, Password) with values from a .txt file and I need to read them, then pass them to the connectionString but I'm very confused how should I do this.
In my program I have a Helper Class to return the connectionString
public static class Helper
{
public static string ConnectionString(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
This is how I call the connectionString so I can access the database data
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.ConnectionString("Hotel")))
{
connection.Execute($"INSERT INTO dbo.Registos_Cancelados(Nome, Telemovel, Data) VALUES(#Nome, #Telemovel, #Data)", new { Nome = nome, Telemovel = telemovel, Data = data });
}
I have a text file with the values
"DataSourceName"
"DataBaseName"
"User IDName"
"PasswordName"
And I want them in the connection string.
<connectionStrings>
<add name="Hotel" connectionString="DataSource="DataSourceName";Database="DatabaseName";User Id="UserIdName";Password="PasswordName""
providerName="System.Data.SqlClient" />
</connectionStrings>
You're using SqlClient, so: your best bet here is SqlConnectionStringBuilder:
var cb = new SqlConnectionStringBuilder(theBaseString);
cb.DataSource = dataSourceName;
cb.InitialCatalog = dataBaseName;
cb.UserID = userId;
cb.Password = password;
var connectionString = cb.ConnectionString;
If you don't have a template string (theBaseString), just use new SqlConnectionStringBuilder() instead.
The advantage of using SqlConnectionStringBuilder here is that it knows all about the escaping rules for non-trivial values, reserved characters, etc.
You can format your connection string like below to pass the necessary values like dbname later.
<connectionStrings>
<add name="Hotel" connectionString="DataSource={0};Database={1};User Id={2};Password={3}"
providerName="System.Data.SqlClient" />
</connectionStrings>
After that in your Helper class, return the formatted connection string with the values that you read from txt file.
public static string ConnectionString(string name)
{
var dataSourceName = "...";
var dbName = "...";
var userId = "...";
var password = "...";
var connectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return string.Format(connectionString, dataSourceName, dbName, userId, password);
}

Connecting to multiple SQL Servers dynamicly with C# Form?

I have some SQL Servers that is Identical exept for the data stored and i want to be able to change between them and if i add more i want to easy add them with a windows form.
I have done a database first and this is the connection string that was added to the App.config file. I changed the username and password for security reasons
<add name="MigrateDBFaktura3Entities"
connectionString="metadata=res://*/DB.ServerData.csdl|res://*/DB.ServerData.ssdl|res://*/DB.ServerData.msl;provider=System.Data.SqlClient;provider connection string="data source=FASTEC-ATTEST\SQLEXPRESS;initial catalog=MigrateDBFaktura5;persist security info=True;user id=**;password=**;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
Is there a easy way to change where i should get the data from?
I was thinking to use a combobox where i could chose what SQL Server it should get the data from.
If i manualy change the connection string it works. but how do i do it with code?
you can utilize class EntityConnectionStringBuilder to build your connection string. refer more here https://msdn.microsoft.com/en-us/library/orm-9780596520281-01-16.aspx and Programmatic Connection Strings in Entity Framework 6
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = ".";
string databaseName = "AdventureWorks";
// 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 = true;
// 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 = #"res://*/AdventureWorksModel.csdl|
res://*/AdventureWorksModel.ssdl|
res://*/AdventureWorksModel.msl";
Console.WriteLine(entityBuilder.ToString());
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Console.WriteLine("Just testing the connection.");
conn.Close();
}
What i did to make it work.
In the Context file i changed
public MigrateDBFaktura3Entities ()
: base("name=MigrateDBFaktura3Entities")
{
}
to
public MigrateDBFaktura3Entities (string connectionString)
: base(connectionString)
{
}
Then i made a HelperClass
class ConnectionHelper
{
public static string CreateConnectionString(LocationModel LM, string metaData)
{
const string appName = "EntityFramework";
const string providerName = "System.Data.SqlClient";
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = LM.datasource;
sqlBuilder.InitialCatalog = LM.catalog;
sqlBuilder.UserID = LM.Username;
sqlBuilder.Password = LM.Password;
sqlBuilder.MultipleActiveResultSets = true;
sqlBuilder.PersistSecurityInfo = true;
sqlBuilder.ApplicationName = appName;
EntityConnectionStringBuilder efBuilder = new EntityConnectionStringBuilder();
efBuilder.Metadata = metaData;
efBuilder.Provider = providerName;
efBuilder.ProviderConnectionString = sqlBuilder.ConnectionString;
var t = efBuilder.ConnectionString;
return efBuilder.ConnectionString;
}
public static FastecData CreateConnection(LocationModel locationmodel, string metaData = "res://*/DB.ServerData.csdl|res://*/DB.ServerData.ssdl|res://*/DB.ServerData.msl")
{
return new FastecData(ConnectionHelper.CreateConnectionString(locationmodel, metaData));
}
}
The LocationModel is Database that purly contains the data for the different servers i will connect to to get data from.
Then when i need to connect to it i only need to
MigrateDBFaktura3Entities db = ConnectionHelper.CreateConnection(CurrentLocation)
where CurrentLocation is a LocationModel

Entity Framework set connection string at runtime

I have been trying to get this work for last couple of days with no success.
This is what I have done so far.
string providerName = "System.Data.SqlClient";
string serverName = serverIPAddress;
string databaseName = myDBName;
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.PersistSecurityInfo = true;
sqlBuilder.MultipleActiveResultSets = true;
sqlBuilder.UserID = "sa";
sqlBuilder.Password = saPassword;
string providerString = sqlBuilder.ToString();
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = providerString;
entityBuilder.Metadata = "res://*/TUModel.myModel.csdl|res://*/TUModel.myModel.ssdl|res://*/TUModel.myModel.msl";
myEntities ctx = new myEntities(entityBuilder.ConnectionString);
The constructor in entity class look like
public myEntities(string connectionString) : base("name=myEntities")
{
}
When I run there is no error. However if I delete 'myEntities' connection string from app.config, then it throws exception. If I leave it as it is then it ignores the connection string in the code and use the one in app.config.
Any help would be greatly appreciated.
Your context constructor isn't passing your connection string in, instead it is passing through a fixed value of name=myEntities. Change it to this:
public myEntities(string connectionString) : base(connectionString)
{
}

The type initializer for 'NameSpace.Settings' threw an exception

I've a very simple class that I've added method GetConnectionString(). After adding it whenever any value is accesses from the Settings class it throws an exception The type initializer for 'NameSpace.Settings' threw an exception. As soon as I remove GetConnectionString() program works fine.
using System.Data.EntityClient;
using System.Data.SqlClient;
namespace CRM {
static class Settings {
public static bool userAuthenticated = false;
public static string userGroup = "";
public static Klienci currentlySelectedClient;
public static string sqlDataConnectionDetailsCRM = GetConnectionString();
public static string GetConnectionString() {
string connection = "";
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.InitialCatalog = dbInitialCatalog;
sqlBuilder.DataSource = dbServer;
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = dbUserName;
sqlBuilder.Password = dbPasswWord;
sqlBuilder.MultipleActiveResultSets = true;
EntityConnectionStringBuilder entity = new EntityConnectionStringBuilder();
entity.Metadata = #"res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl";
entity.Provider = "System.Data.SqlClient";
entity.ProviderConnectionString = sqlBuilder.ToString();
connection = entity.ToString();
return connection;
}
}
}
If I comment out sqlBuilder and entity. It works fine..
public static string GetConnectionString() {
string connection = "";
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
//sqlBuilder.InitialCatalog = dbInitialCatalog;
//sqlBuilder.DataSource = dbServer;
//sqlBuilder.IntegratedSecurity = false;
//sqlBuilder.UserID = dbUserName;
//sqlBuilder.Password = dbPasswWord;
//sqlBuilder.MultipleActiveResultSets = true;
EntityConnectionStringBuilder entity = new EntityConnectionStringBuilder();
//entity.Metadata = #"res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl";
//entity.Provider = "System.Data.SqlClient";
//entity.ProviderConnectionString = sqlBuilder.ToString();
connection = entity.ToString();
return connection;
}
What's going on? It seems fine to me..
Edit:
InnerException:
exception = "System.ArgumentNullException: Value cannot be
null.\r\nParameter name: Initial Catalog\r\n at
System.Data.SqlClient.SqlConnectionStringBuilder.set_InitialCatalog(String
value)\r\n at CRM.Settings.GetConnectionString() in
C:\Projects\Project.C.S...
While public static string dbInitialCatalog = "BazaCRM"; is set in Settings class.
The order of the fields being initialized is not guaranteed. What's going on here is that the sqlDataConnectionDetailsCRM is being initialized before the dbInitialCatalog field.
If you change those other static fields to be const it should fix it.
Or a better way might be to just removed your public static field, and retrieve the connection string from the method, or you might also like to investigate the Lazy<T> class, and use that to build the connection string the first time it's needed.
According to your error the value of dbInitialCatalog seems to be null, so the connection string builder is throwing an error. Because this is inside the static constructor of a class, the type itself can't be loaded and the whole thing fails.
Have you tried manually supplying the connection string yourself?

change connection string in class application at runtime?

I have class application that uses ado.net to connect to Sqlite database. The application uses the db to store some data and the db may be changed at run time. The user may make backups of the db and change the location, but in this case i need to know how to change the connection string.
I have tried this code but it didn't work:
string conn =
#"metadata=res://*/KzDm.csdl|res://*/KzDm.ssdl|res://*/KzDm.msl;" +
#"provider=System.Data.SQLite;" +
#"provider connection string=" +
#""" +#"Data Source=" +
#"F:\My Own programs\KrarZara2\KZ\KZ\Kzdb.s3db" +
#""";
Entities ent = new
Entities(conn);
this error "Keyword not supported: 'data source'."
happen at this line
public Entities(string connectionString) : base(connectionString, "Entities")
i write that and it worked with me
EntityConnectionStringBuilder conn = new EntityConnectionStringBuilder();
conn.Metadata = #"res://*/KzDm.csdl|res://*/KzDm.ssdl|res://*/KzDm.msl";
conn.Provider = "System.Data.SQLite";
conn.ProviderConnectionString = #"data source=F:\My Own programs\KrarZara2\KZ\KZ\KrarDS.krar;Version=3;";
EntityConnection entity = new EntityConnection(conn.ConnectionString);
using (DmEnt ent = new DmEnt(entity))
{
var parcel = ent.Parcels.SingleOrDefault(d => d.id == 1);
var pparcc = ent.Parcels.Select(d => d.id == 2);
Parcel r = new Parcel();
r.ParcelNumber = "11ju";
r.Area = 8787;
ent.AddToParcels(r);
ent.SaveChanges();
}
Dm ent is the entity model in edmx ado.net
wrong line order, should be:
#""" +
#"Data Source=" +
I'd actually surprised that connection string works at all. In addition, it would be simpler to use string.Format to build this connection string:
var filename = #"F:\My Own programs\KrarZara2\KZ\KZ\Kzdb.s3db";
var connString = string.Format("Data Source={0};UseUTF16Encoding=True;", filename );
using( var conn = new SQLiteConnection( connString ) )
{
...
}
First, you would replace UseUTF16Encoding with the proper value for your setup. Second, note that the file path in the connection string is not surrounded by quotation marks.
If you are looking for a means to swap Sqlite data files at runtime you might look at this blog entry:
SQLite and Entity Framework 4
A summary of the solution is to parse the Entity framework connection string, change the data file and then reset it:
public static string RedirectedEntityFrameworkConnectionString(string originalConnectionString, string databaseFile, string password)
{
// Parse the Entity Framework connection string.
var connectionStringBuilder = new EntityConnectionStringBuilder(originalConnectionString);
if (connectionStringBuilder.Provider != "System.Data.SQLite")
{
throw new ArgumentException("Entity Framework connection string does not use System.Data.SQLite provider.");
}
// Parse the underlying provider (SQLite) connection string.
var providerConnectionStringBuilder = new SQLiteConnectionStringBuilder(connectionStringBuilder.ProviderConnectionString);
// Redirect to the specified database file, and apply encryption.
providerConnectionStringBuilder.DataSource = databaseFile;
providerConnectionStringBuilder.Password = password;
// Rebuild the Entity Framework connection string.
connectionStringBuilder.ProviderConnectionString = providerConnectionStringBuilder.ConnectionString;
return connectionStringBuilder.ConnectionString;
}
To use, you would do something like:
const string OriginalConnectionString = "..."; // (Copy out of app.config)
var connectionString = RedirectedEntityFrameworkConnectionString(OriginalConnectionString, myFileName, null);
using (var context = new MyEntities(connectionString))
{
...
}

Categories