Replacing connection string with a method in factory pattern - c#

I am planning to replace the factory created connection string which is from web.config with a function generated connection string. I am confused where to make this change?
Connection String in Web config as below:
<connectionStrings>
<add name="ConnectionStringToDB" connectionString="Data Source=GTD,2431;Network Library=DBMSSOCN;Initial Catalog=WorkflowExecutionDB;User ID=Dev_FID;Password=****" providerName="System.Data.SqlClient" />
</connectionStrings>
Currently following code will call this above connection string:
DatabaseProviderFactory factory; /* enterprise data library*/
Database ConnectionStringToDB; /* database schema*/
factory = new DatabaseProviderFactory();
// Create a Database object from the factory using the connection string name.
ConnectionStringToDB = factory.Create("ConnectionStringToDB");
DbCommand dbCmd = ConnectionStringToDB.GetStoredProcCommand("SP_Name");
Suppose i need to change the connection string which is coming from web-config to function method result as like below, where i need to put the GetConnectionString() in the code? :
public static string GetConnectionString()
{
return "Data Source=GTD,2431;Network Library=DBMSSOCN;Initial Catalog=WorkflowExecutionDB;User ID=Dev_FID;Password=****" providerName="System.Data.SqlClient"
}
Following might be wrong:
ConnectionStringToDB = factory.Create(GetConnectionString());
What the is the right way?

Related

how do I make my oledb program work on a different pc

Hey I'm new to programming and have never made an actual program that needs to work on another pc. The program is connected with a databank. When I'm on another pc i change program.exe.config file so that i can apply the right location of the databank but its still doesn't work. here is the code i have, maybe something is wrong here.
app.config:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
in standard code:
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb");
The first thing is that you are specifying a connection string in your application configuration file:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
You aren't using the connection string from your Program.exe.config, instead you are copying-and-pasting the connection string.
If you change your code slightly, perhaps you can see what i mean:
//Get the connection string to use
String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb";
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
What you should be doing is pulling the connection string from your application's configuration:
//Get our connection string setting, and the connectionString it contains
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
String connectionString = cs.ConnectionString;
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
There is one more change that you can make. Your connection string entry itself specifies which provider you want to use:
providerName="System.Data.OleDb"
But then you go ahead and use that provider yourself:
OleDbConnection con = new OleDbConnection(...);
If you changed your connection string to use a different provider:
providerName="System.Data.SqlClient"
your code would still be using the OleDbConnection, rather than the provider given in the application configuration.
Fortunately, the .NET framework has a handy little helper function, where it can create the correct provider for you:
public static DbConnection GetConnection()
{
//Get the connection string info from our application config
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
if (cs == null)
throw new Exception("Could not find connection string settings");
//Get the factory for the given provider (e.g. "System.Data.OleDbClient")
DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName);
if (factory == null)
throw new Exception("Could not obtain factory for provider \"" + cs.ProviderName + "\"");
//Have the factory give us the right connection object
DbConnection conn = factory.CreateConnection();
if (conn == null)
throw new Exception("Could not obtain connection from factory");
//Knowing the connection string, open the connection
conn.ConnectionString = cs.ConnectionString;
conn.Open();
return conn;
}

C#: SQL Server Connection String

I am trying to use a button that will add to my two columns in my database. I have placeholder values in there currently but will eventually be using 2 pop ups to read in those values.
My question is: how do I get the connection string? I don't know what to put there or where to get that data.
private void button_AddPartNumber_Click(object sender, EventArgs e)
{
string cmdString = "INSERT INTO Part_Numbers (Part_Number, Barcode_Number) VALUES (#val1, #val2)";
string connectionString = "I DONT KNOW WHAT TO PUT HERE";
using (SqlCommand connection = new SqlCommand(connectionString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = connectionString;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("#val1", "L-0G004-0830-xx"); //placeholder value
comm.Parameters.AddWithValue("#val2", "asdf1234"); // placehold value
}
}
} // end button_AddPartNumber_Click()
Well, what database are you using? For example, SQLServer? Oracle? MySQL?
In SQLServer, at least, the connection string is defined in the web.config, or app.config, and has syntax similar to the following:
<appSettings>
<add key="ConnectionStringName" value="AppName"/>
</appSettings>
<connectionStrings>
<add name="AppName" connectionString="Data Source=DataSourceName; Initial Catalog=DataBaseName; user id=UserID; password=Password" providerName="System.Data.SqlClient"/>
</connectionStrings>
Something like that. There's probably something I'm missing, but without testing it out in your code, I'm blanking on what that might be.
This how you extract the connection string from your code if the connection string is properly set in the web.config:
var connectionString = ConfigurationManager.ConnectionStrings["AppName"].ConnectionString;

ObjectContext ConnectionString Sqlite

I need to connect to a database in Sqlite so i downloaded and installed System.Data.SQLite and with the designer dragged all my tables.
The designer created a .cs file with
public class Entities : ObjectContext
and 3 constructors:
1st
public Entities() : base("name=Entities", "Entities")
this one load the connection string from App.config and works fine.
App.config
<connectionStrings>
<add name="Entities" connectionString="metadata=res://*/Db.TracModel.csdl|res://*/Db.TracModel.ssdl|res://*/Db.TracModel.msl;provider=System.Data.SQLite;provider connection string="data source=C:\Users\Filipe\Desktop\trac.db"" providerName="System.Data.EntityClient" />
</connectionStrings>
2nd
public Entities(string connectionString) : base(connectionString, "Entities")
3rd
public Entities(EntityConnection connection) : base(connection, "Entities")
Here is the problem, i already tried n configuration, already used EntityConnectionStringBuilder to make the connection string with no luck.
Can you please point me in the right direction!?
EDIT(1)
I can do my queries if i use de parameterless constructor but i need to change the connection string, i can't use the one in my app.config.
How can i construct a valid connection string?!
Found it =)
if you use the EntityConnectionStringBuilder to specify the Metadataand the Provider and use the SqlConnectionStringBuilderto build the provider connection string and set the DataSource to your DB. You can connect =)
var con = new EntityConnectionStringBuilder()
{
Metadata = #"res://*/Db.TracModel.csdl|res://*/Db.TracModel.ssdl|res://*/Db.TracModel.msl",
Provider = #"System.Data.SQLite",
ProviderConnectionString = new SqlConnectionStringBuilder()
{
DataSource = db,
}.ConnectionString,
};
connection = con.ConnectionString;

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)

How can I make LINQ to SQL use a connection string which is being modified at runtime?

I'm experimenting some difficulties trying to use Connection String Builders (ADO.NET) within LINQ to SQL. Let me show you guys what I'm trying to do:
the app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="LoremIpsum"
connectionString="Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and a snippet of the form:
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["LoremIpsum"];
if (null != settings)
{
string connection = settings.ConnectionString;
SqlConnectionStringBuilder builder =
new SqlConnectionStringBuilder(connection);
// passwordTextBox being the control where joe the user actually
// enters his credentials
builder.Password = passwordTextBox.Text;
}
LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext();
// finally some rather anecdotic LINQ sentence here:
var foo = db.Table.Single(bar => bar.Table == whatever);
On the other hand checking the Immediate Window:
?builder.ConnectionString
"Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;Password=swordfish"
I'm always getting an exception: Login failed for user 'joe'. Any ideas? Thanks much in advance.
It seems like you are trying to modify the connection string that is stored in the app.config file. When you use a no argument constructor for your data context, it reads what was configured at design time.
Try injecting your modified connection string into the constructor of the DataContext:
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"];
SqlConnectionStringBuilder builder;
LINQTOSQLDataClassDataContext db;
if (null != settings)
{
string connection = settings.ConnectionString;
builder = new SqlConnectionStringBuilder(connection);
// passwordTextBox being the control where joe the user actually enters his credentials
builder.Password =passwordTextBox.Text;
db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
} }
You're forgetting to send in the connectionstring to the DataContext constructor.
Example:
LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
You can force a DataContext to use a specific connection string with
DataContext db = new DataContext(myConnectionString);
The parameterless DataContext constructor will use a connection string from the App.config file first, then the connection string set at compile time.

Categories