Generating a Connection String in C# - c#

I'm trying to write an application that will let users connect to an arbitrary database, assuming they have the proper ODBC drivers. However, I'm getting stuck on the connection strings. For any particular database type it's easy to look online and find which keyword/value pairs are required, but is that information accessible from the driver itself?
What I want to do is have the user select the driver they want from a list (generated by SQLDrivers), then generate a form that will prompt them for the keywords necessary to generate the string, so that my application does not need to know about specific ODBC drivers. Is there any way to do this? Or will I have to hard code support for each one separately? Maybe connection strings aren't the way to go, and there's another method I'm overlooking?

You can take a look at ConnectionStringBuilders and see if they'll be any help.
You can use the following code to enumerate the configurable properties, which would allow you to create your config form.
var builder = new SqlConnectionStringBuilder();
var properties = (from key in builder.Keys.OfType<string>()
select key);
properties contains:
Data Source
Failover Partner
AttachDbFilename
Initial Catalog
Integrated Security
Persist Security Info
User ID
Password
Enlist
Pooling
Min Pool Size
Max Pool Size
Asynchronous Processing
Connection Reset
MultipleActiveResultSets
Replication
Connect Timeout
Encrypt
TrustServerCertificate
Load Balance Timeout
Network Library
Packet Size
Type System Version
Application Name
Current Language
Workstation ID
User Instance
Context Connection
Transaction Binding

In 2010 Microsoft released there VS2010 Connection dialog for us little people to use. It is awesome, should do what you want and is freely distributable. The download for the dialog and its source code can be found here.
To get you started: once you have compiled the code you will need to include references to Microsoft.Data.ConnectionUI, Microsoft.Data.ConnectionUI.Dialog and Microsoft.Data.ConnectionUI.SqlCeDataProvider. The dialog is then called like
// Initialisation.
DataConnectionDialog dcd = new DataConnectionDialog();
DataConnectionConfiguration dcs = new DataConnectionConfiguration(null);
dcs.LoadConfiguration(dcd);
// Edit existing connection string.
if (!String.IsNullOrEmpty(strExistingConn))
dcd.ConnectionString = strExistingConn;
// Launch Microsoft's SqlConnection dialog.
string strSqlFinConn = String.Empty;
if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
{
// Load tables as test.
using (SqlConnection connection = new SqlConnection(dcd.ConnectionString))
connection.Open();
}
dcs.SaveConfiguration(dcd);
return dcd.ConnectionString;
If this is not what you want then #HackedByChinese answer looks like the best approach.
I hope this helps.

I found a very simple way to solve this, actually, at http://msdn.microsoft.com/en-us/library/windows/desktop/ms715433(v=vs.85).aspx.
If you call the ODBC API function SQLDriverConnect with an incomplete connection string (like, for example, one that only contains the Driver keyword) and set the last argument to SQL_DRIVER_COMPLETE, it will pop up with a dialog generated by the driver that prompts for any required information that wasn't included, then return the finished connection string once it's closed.

Apart from the good answers already posted you might want to take a look at the ODBC API SQLBrowseConnect.

Related

Should I keep the SqlConnection open?

In my Unity3D game the Player plays himself through short levels, which at the beginning take about 4 seconds. The goal is to get the best possible clear time in each level. I am currently saving these clear times locally, but I would like to upload them to an SQL Server, to be able to create a leaderboard for each level.
Since performing the SqlConnection.Open() command takes about 1-2 seconds, sometimes also 3, I was wondering whether I should keep a static connection always open, ready to execute any queries that I want to run.
Are there any unwanted and dangerous side-effects when doing it?
Edit: This is the code that I use for opening the SqlConnection.
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder()
{
DataSource = dataServer,
UserID = userId,
Password = password
};
SqlConnection connection = new SqlConnection(builder.ToString());
connection.Open();
First I'll answer this question:
Are there any unwanted and dangerous side-effects when doing it?
Assuming you keep this code in your Game (client) and the SQL Server is not client-side but in a server of yours located somewhere, a simple Client Reverse Engineer will be able to grab your credentials from your connection string and use them to gain Unauthorized access to your database. (NEVER trust the client)
With that being said, I would suggest you use a simple server-side technology (php,Socket App, Java servlet, etc..) along with the SQL that the client will send the information there and then to the database.
Example:
1) Client-> Posts Data -> PHP
2) PHP -> Connects -> SQL Database
3) PHP -> Inserts data -> SQL Database
Like this you can also retrieve the results of your ladder from the database by asking php (or whatever technology you are using) to send your data to the client.
Best wishes in your progress, and feel free to contact me for any additional information!

Passing connection string from linqpad to custom library causes login failure

I am writing a linqpad script for migrating data into a db from an excel file. Once the data has been imported it needs to be synchronized between multiple dbs. This has been done in a dll as the functionality is used elsewhere.
My issue is that when passing a connection string to my dll from linqpad I get the message Login failed for user 'xxxxxxx'. As far as I can tell it is because the password for the SQL authentication is not passed in the connection string. IS there any way to make linqpad include the password in the connection string:
SyncController syncController = new SyncController(this.Connection.ConnectionString);
syncController.SyncAll();
If it is at all possible I want to avoid forcing the person who will be running this to update a password variable when running this. Thanks.
You're right: the password will disappear from the connection string after the connection is opened. This is a feature of the .NET Framework, and is not specific to LINQPad.
There are two workarounds. First, you can capture the connection string as the first line in your LINQPad script, before querying any data:
string cxString = this.Connection.ConnectionString;
The other workaround is to add the following text to your connection string:
Persist Security Info=true
To do this in LINQPad, right-click the connection and choose Properties. Click Advanced, and enter the additional connection string text into the box provided.

Updating Connection String in DLL from Winforms - Linq to SQL

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

Issues on dynamically change and switching the connectionString in web Config

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.

using app.config file for connection string, and abstract it from users

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

Categories