I developed a class library that uses Linq To Sql to communicate with a database.
When I added this I used Server Explorer to add a database and all the tables I want to talk to.
It then built a .dbml file for me.
In the "Designer" file I can see:
public TPDataContext() :
base(global::TPAPI.Properties.Settings.Default.TruePotentialConnectionString, mappingSource)
{
OnCreated();
}
If I update the "Linq to SQL" it regenerates a new designer.cs file
It stored the connection string in Settings.settings with the scope of "Application".
All functions just fine.
But, I have then added a winfoms project that needs to change this setting. So I added the following code:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString = txtConnectionString.Text;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
This updates the connection string in the dll but it only takes effect when the application is shutdown and restarted.
When I am upgrading clients it overwrites what the user had already entered when using it previously.
I cannot seem to work out the best way to:
Not overwrite previous user defined connection string when the app is upgraded.
Be able to save the new connection string and use it without having to stop/start the app.
Having had a read of other threads it appears that the dll shouldn't really have any "local" settings in it (?) and they should all be sent by the winforms app. But, I am unclear on how use Linq to Sql in the dll without it automatically looking/adding it's own connection string.
Can anyone help please?
Thanks
I have decided to rewrite all my DataContext calls to accept the connection string parameter.
I had to amend and test about 40 functions but now the connection string is stored in the winforms application as a user setting and overrides the default connection string generated by Linq to SQL.
So, now in my dll it now looks like
TPDataContext db = new TPDataContext(connStr);
HTH
Related
how can i manage connection string of an ADO.net Object model dynamically?
i have connected my application to database using Entity Framework and connection string is automatically added to app.config. how can i get list of available servers and change connections string based on that in the run-time?
Just because VS adds the connection string to app.config by default it doesn't mean that is a good idea and if you do keep the connection string there you cannot change it at run time.
One solution is to keep encrypted connection string in your settings and that will allow you to dynamically change it at run time by simply calling:
Settings.Default.Save();
and
Settings.Default.Reload();
I am about to deploy my application and have came into a bit of trouble.
I have the connection string for the database held in the application.settings and need a way to check if the database exists when the program first starts up, and if it doesn't, i need the program to create it before starting the program.
I am assuming it would be a mysql statement to check if db exists, if not create. However, I don't know where or how to do this, can I create a mysql dump of a blank database with tables etc already created and use that?
I have already stored the mysql dll files locally so there is no problem with that, its just creating the database that the string wants to connect to before the application runs so there are no connection errors straight away.
Thanks.
You can do this by running the following SQL statement:
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "my_db"
If it doesn't exist from the result set you get returned you can then create it.
This does pose questions regarding MySQL permissions and if your application should have user rights that enable such checking.
Edit in response of comments.
It isn’t clear if you create the connection string or not – I’ll assume the worst and that it is a part of the setup so your client can enter it (if you do know it the process below simplifies.
I would pass the connection string to the constructor of the MySqlConnectionStringBuilder class, this then makes it easy to connect to the database using the MySqlConnection class. I would use the properties from the new instance of the MySqlConnectionStringBuilder class (Server, Host, User etc) to setup the MySqlConnection class.
If the connection didn’t work I would return information to the user and they can update their connection string.
Once I’ve successfully connected to the database I would then use the database name from the Database property of my MySqlConnectionStringBuilder instance to build the query above.
If the command returns NULL the database doesn't exist and then needs creating, if the database does exist then the command will return the name of the database.
Now there are two paths:
It Doesn't exist – It needs creating, I would probably have an external SQL file with the create statements in (can be produced by MySQL dump by using the –nodata option). I would parse this file and execute the create statements
It does exist – I would now check the structure of the database to make sure it is compatible before continuing the installation.
At work I wrote an application that processes data from a SQL Server database and outputs it in file format.
Now I need to use it at home and since app has hard-coded connection string I've got a problem. I got a copy of database at my company, the original database is inaccesable from the outside of the company.
Connection string format looks like this
Data Source=serverName-01;Initial Catalog=dbName_01;Integrated Security=True;Pooling=False
I've tried to cheat app by editing windows hosts file:
serverName-01 127.0.0.1
But it did not work. Is there a way to make it work without going to work and editing source code ?
Lesson learned hard way - never hard-code connection srings :<
To do this you can use an alias defined in SQL Server Configuration manager. Create an alias for your local instance that has the exact same name as the one in the connection string.
Have a look at the following article for how to do this (it's pretty simple):
Create or Delete a Server Alias for Use by a Client (SQL Server Configuration Manager)
I am trying to switch different databases for a web application at Run time.
Senario
We have one asp.net web application and different databases for different customers.I am trying to switch particular connection string value from a common database where i am keeping a mapping table for connection string ,particular customer id and password .After the successful lo gin i am piking a connection string from the common database and edit the web.config file connection string section by replacing selected connection string at run time.
i am doing this by add following code to login event
conectionString = cString;
Configuration openWebConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection sections = openWebConfiguration.GetSection("connectionStrings") as ConnectionStringsSection;
if (sections != null)
{
sections.ConnectionStrings["ConnectionStringName"].ConnectionString = conectionString;
ConfigurationManager.RefreshSection("ConnectionStringName");
openWebConfiguration.Save();
}
i am reading above connection string on a page by using ConfigurationManager.problem is the web config file is changing but after calling to another page using Response.Redirect will throw an exception .Exception is "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack "I can realized this is something happen on cross threaded environment.My questions are
What is exact reason for above exception?
which page life circle of the Asp.net reads the setting from the web config file ?
What is the proper way i can implement above scenario?
I am wondering why this question seems still unanswered.OK i have found some answermy self.It may be wrong but some how they are giving some meaning to me.I assume following are acceptable for my knowledge level.
1)I don't know the exact reason ,but this is something happen because of code is modified while an application running
2)Based on my search WEB Config file is started to read by the application when the IIS server start.So what ever values to be modified inside WEB Config ,require to restart the IIS server to load them in to memory.We can modify the connection string dynamically but still the application will run on the previous connection string.So we need t restart the IIS to load newer one.
Note:Modify a existing connection string is different than add a new connection string to a WEB Config.
3)I have used a common data Base where i have authentication details for different different connection strings for Several database.WeB config has the connection string for above master database.If an user gives his authentication detail it will select his connection string and load it as new connection string .So the remaining process will be based on that connection string.
Any new arguments for above answers are highly appreciable.I need corrections from other developers because i am very eager to learn.
I have used app.config file for my winform application , the file is used to store the connection string which is used by all the Forms in my application to connect to a remote MySQL database.
But when I install the application on my customer's PCs, then I want that they could not see the app.config file. Is it possible? How? Please help with code.
Also, is there any other way, to create a connection string which is accessible by all the Forms. Like, can I make a class connection.cs and then inherit it in every Form.
But how to do this? I mean how to implement the code
My main objective is to create just one string for connection, so that , if i change it again and again, then i need not go and change it every Form, instead, i would just change it only in one File , and it would be used by all the Forms
Is using app.config file a good option or making a connection.cs file's a better one?
You don't need to use a connection string from every form, you need a data access layer and then you use it from everywhere, in theory only from another layer called business logic...
A form which needs to load data into a grid, a drop down or some other controls should consume data loaded by lower layers in your application stack.
Read something about 3 tier architecture.
The app.config is always visible on the user machine, so you should not treat any information stored in it as secret.
You really have two options:
Continue to store the connection string in the app.config but encrypt it. This will work fine if its an internal app and security is not to much of an issue. But since the encryption key has to be stored in the app a dedicated hacker could retrieve it.
use a three tier architecture as suggested already. With this the connection string is stored in the middle tier, while your application no longer connects directly to the database but rather through the middle tier. Authentication can then be done with a user name/password per user or by making use of windows authentication. The connection string is stored on a server and only people with acces to this server can look at it and see the DB connection string.
If you just want a simple solutions why not create a class named for example "Connection" in a file connection.cs and let it have a static attribute or property named for example "ConString" which holds the connection string:
public class Connection
{
public static ConString = "your connection string here";
}
Then you can access it everywhere:
OdbcConnection conn = new OdbcConnection(Connection.ConString);
BUT that would only be the quick and dirty way of doing it (although it works). It would be much nicer to create an own Database-Layer - but also much more work.
App.config can't be hidden on users machine, this is what you can do.
You can encrypt the connection string and store it in the app.config. have a look on this article, it shows you how to do that.
Try to define your connection string in program.cs before [statThread] by storing it in a public static string variable like constr etc. Then u can use that var anywhere referencing:
program.constr