i created a data access layer dll using subsonic. however it uses the connectionstring from the app.config.
i am using it in ninjatrader and dont want to mess around with the ninjatrader app.config for the connecitonstring. how do i avoid this issue.
I believe the best you can hope for here is to use a separate file for the connection strings:
in app.config
<connectionStrings ConfigSource="myConnStr.config" />
in myConnStr.config:
<connectionStrings >
<add .... />
<add .... />
</connectionStrings >
I believe you can set it at runtime using the SetDefaultConnectionString method:
SubSonic.DataService.GetInstance("InstanceName").SetDefaultConnectionString("ConnectionString");
Sample how to programatically hardcode connectionstring:
string connectionString = string.Format(#"Data Source={0}", Path.Combine(this.ConfigFolder, ConfigDb));
string providerName = #"System.Data.SQLite";
var provider = ProviderFactory.GetProvider(connectionString, providerName);
_configRepo = new SimpleRepository(provider, SimpleRepositoryOptions.RunMigrations);
This sample use sqlite database which is located in this.ConfigFolder. ConfigDB contains name of a database file.
Related
I have a DB2 environment, to which I would like to connect with Entity Framework. To do that, I need a connection string which looks like this, in the app.config file:
<connectionStrings>
<add name="DB2Connect" connectionString="Database=my_db; UID=Username; PWD=Password;"/>
</connectionStrings>
It doesn't seem like a good idea to have a password hardcoded into the app.config file, so I would like to replace it at run time, but only temporarily! The temporary part, is what is causing me trouble. I have successfully managed to replace the connection string, with the following code, but it's no good when the password remains in the the app.config file, afterwards:
private static void SaveConnectionString(string name, string connectionString)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings[name].ConnectionString = connectionString;
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
Not sure if i am answering something different here, but if you are looking for a solution to having no/a different connection string when you build to release, you can look into:
https://marketplace.visualstudio.com/items?itemName=vscps.SlowCheetah-XMLTransforms
Hi I am developing an application for that I am taking connection string through dynamically from user at first time run.
My app.config is
<connectionStrings>
<add name="DConnection" connectionString=""
providerName="MySql.Data.MySqlClient"/>
<add name="SConnection" connectionString=""
providerName="System.Data.SqlClient" />
</connectionStrings>
I am assigning connection string to app.config's attributes by using below methods
private void CheckingSource(string constr)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["SConnection"].ConnectionString = constr; //CONCATINATE YOUR FIELDS TOGETHER HERE
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
}
private void CheckingDestination(string constr)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["DConnection"].ConnectionString = constr; //CONCATINATE YOUR FIELDS TOGETHER HERE
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
}
Now I have to write this connection string to app.config so when user run application next time these updated connection strings should be in use.
How can we manage it? I don't have any idea as I am still fresher to app.config and it's usage.
Now I have to write this connection string to app.config so when user run application next time these updated connection strings should be in use.
You shouldn't do this, the app.config file might be deployed to somewhere like C:\Program Files\Your Application which is not writeable by normal users.
Instead, supply the connection string to whatever needs it in some way other than using ConfigurationManager.ConnectionStrings.
using (var connection = new SqlConnection(GetConnectionStringFromUser())) { ...
With specific regards to "saving" a connection string, you should look at some sort of persistence mechanism like .NET's Application Settings.
The application settings architecture supports defining strongly typed settings with either application or user scope, and persisting the settings between application sessions.
Thanks #ta.speot.is resolved the issue using application setting.
Reference link.
Application Setting
might be helpful to all needy. Cheers.. :)
I'm newbie in C#. I want to ask, how can I separate the connection string config into a class?
Because every time I want to write code, I need to re-write the connection string and test the connection. So, I need to make a class so that every time I make a connection to the database, this class will test the connection first. Then after it works, the class will send the connection string to my coding.
Besides, if I want to change my source data, I just need to change in the class only. No need to search all my coding
So if I can make a class, how do I call and get the connection string from class?
Can it be like that?
This is my current coding for connection string in C#
FileInfo file = new FileInfo(Application.StartupPath + "\\conn.txt");
if (file.Exists)
{
StreamReader r = File.OpenText(Application.StartupPath + "\\conn.txt");
connString = r.ReadToEnd();
r.Close();
// Open SQL connection
SqlConnection openCon = new SqlConnection(connString);
try
{
Cursor = Cursors.WaitCursor;
openCon.Open();
}
catch
{
MessageBox.Show("Error to established connection\nPlease check Data Source");
openCon.Close();
Cursor = Cursors.Arrow;
}
else
{
MessageBox.Show("File config is missing");
}
}
Hope you can teach me as a newbie in C#. Thanks for the help. And sorry for bad english.
You should store connection strings in your configuration file. If you don't have a configuration file, add one by right-clicking the project and 'adding new item...' If you are writing a web app it will be a web.config file; if you are writing a client app it will be an app.config file.
You add a connection string to the configuration file in the connectionStrings node, normally at the top of the file.
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!-- add a string -->
<add name="MyConnectionString"
connectionString="Data Source=localhost; ... // etc
providerName="System.Data.SqlClient" />
</connectionStrings>
// and keep all the other configuration in the file
And then you simply refer to the configuration file using the ConfigurationManager class - you'll need to add a reference to System.Configuration if you don't already have one.
ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
You're trying to reinvent the wheel here. The .Net framework already include some simple techniques to handle this. If you're creating a Windows form project, you can store the connection string in App.Config using the connectionString attributes. If this is a web app, then you store it in web.config, here is how it would look like:
<connectionStrings>
<add name="Prod" connectionString="Server=myServer;Database=DB1;user=sa;password=myPassword;Trusted_Connection=false" providerName="SQL" />
</connectionStrings>
Then, in your code, you read the connection string from web.config as follow:
string connString = System.Configuration.ConfigurationManager.
ConnectionStrings["Prod"].ConnectionString;
You're asking a very basic question here and it indicates that you're trying to bully your way into learning c#. My advice to you is to grab a good C# book and go through it cover to cover to learn things the right way.
Instead of putting the connection string into a separate file, store it in your app.config or web.config file. .NET configuration files van contain a section that allows you to store connection strings:
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
You can retrieve this connection string using the following code:
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
I think Poster's question is pretty much valid. Although we can write connection string in Web.config or app.config once and use it in whole project, but there is a drawback of using this technique.
Connection string in web.config or app.config is never safe. These two files are ultimately like text files. There are ways to get the password from them. The security could be broken. So its better to use the connection string in a separate class file and get it in your whole project.
you could create a class which returns a sqlConnection...
public class DBConn
{
private string ConnectionString = "123456789Connection";
public SqlConnection getSqlConn()
{
return SqlConnection();
}
}
We've recently changed the name of the SQL DataBase our WebApp is using. Now, each of the DataTableAdapters will update to the new ConnectionString.
Our setup is as follows:
1) Interface (WebSite Project)
2) Business Logic (Class Library Project)
3) Data Access (Class Library Project) ---> Contains many DataSet classes
The app.config of the Data Access project contains the only connection string. When creating each of the DataTableAdapters, the wizard points to it correctly. Now, we've had to change the ConnectionString, and all of the existing DataTableAdapters (about ~60) will not work.
Simply changing the ConnectionString has not worked. What am I missing?
Thanks
Make sure the connection string name in your config is the same as the one in the Settings File. Because in the generated code, when it initialzed the connectionstring it setting the connection string as follow :
private void InitConnection() {
this._connection = new global::System.Data.SqlClient.SqlConnection();
this._connection.ConnectionString = global::ConsoleApplication4.Properties.Settings.Default.MyConnectionString;
}
Make sure that in your app config the name of your connectionString is the same. for example
<connectionStrings>
<add name="ConsoleApplication4.Properties.Settings.MyConnectionString"
connectionString="Data Source=MyServer;Initial Catalog=MyDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
The problem was in the Settings.Designer.cs file. Its an auto-generated file that did not update after the normal updating/clean/build process.
Thanks Everyone :-)
I am making a little library(DLL) to manage users and their roles/privileges. The plan is to be able to add this dll to an MVC project and be able to manipulate users/roles/etc. All the data resides in a SQL db.
I am using entity framework for data access.
So when I initialize a new RoleManager(this is the name of the main class in the lib I'm making) I supply it with a connectionString like so:
RoleManager roleManager = new RoleManager(string connectionString);
Then inside the constructor I do this:
db = new RoleManagerEntities(connectionString); //This is the EntityFramework
And I am trying to supply this connection string (among many others)
"metadata=res://*/RoleManager.csdl|res://*/RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'"
And I get the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
This question is a result of having trying to instantiate the EF from my new project without supplying a connection string and without having anything inside my app config for it to default to. Too bad I can't delete it now.
Just copy the connection string information from your DLL config file to your executable config file.
Basically you are trying to instantiate an ObjectContext via this ObjectContext Constructor (String) without passing the string parameter in its expected format and that's the problem.
Here is what you need to do:
1. First create an entry in your in your "test project" app.config because that is the place that the CLR is looking at to find the connection string at runtime.
<configuration>
<connectionStrings>
<add name="RoleManagerEntities" connectionString="metadata=res:///RoleManager.csdl|res:///RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'" />
</connectionStrings>
</configuration>
2. Now change the code to pass the connection string name instead of the actual connection string:
db = new RoleManagerEntities("name=RoleManagerEntities");
The constructor might be looking for a connection string in the connectionStrings setting of your web.config with the name that you pass it as the parameter.
So if you call:
db = new RoleManagerEntities("Foobar");
It is looking for:
I'm not positive that this is the solution but that's what the error message seems to indicate.
I am not an expert on EF, but I don't think that connection string is valid. Try:
metadata=res://*;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'