Recently I've been studying about rewriting/replacing ConnectionString from the Web.config file. Suppose I have a 'dummy' account in my original web.config here:
<connectionStrings>
<add name="OracleDBConnString" connectionString="Provider=MSDAORA;Data Source=ISDDEV;User ID=dummy_account;Password=password;"
providerName="System.Data.OleDB" />
</connectionStrings>
Base on this post: How do I set a connection string config programatically in .net?, I can change the connection string from web.config dynamically but are there any negative effects if I change the connection string dynamically during runtime? Are there any 'conflict' if I have multiple users (with different accounts or conn string) accessing the system? Do you have any suggestions on what approach I can use?
The reason why I have to change the conn string is because I don't actually maintain passwords inside the database instead I use the login details of the user in the database directly. Thank you in advance.
Connection string in web.config is application-wide parameter. If you change it for one user using that reflection trick you've mentioned, it will get changed for the whole application, and other users will unintentional use it.
You can try using impersonation in pair with windows authentication, if your db provider supports it. That way user will be transparently authenticated to the database without the need for passing passwords around.
You can also create a new temporary connection string object, based on the one in web config, but with modified credentials, and then create a connection using it yourself.
Related
I have a C# windows form application and I connect it to the SQL server in my computer. Now I going to deliver the software to a user. So, what can I do to change the connection string to the user SQL server? Is there any way to do the connection string computer independent? Kindly help me
Regards.
I'm assuming you're hard-coding connection strings into your code. You need an application config file.
Or you could use connection string like this (if database (SQL server) is on same machine as app using it and database name is the same) :
Server=localhost\instanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
instanceName could be "nothing" (default instance) or named instance (SQLEXPRESS).
Or do it as #Xavier J suggested - store connection string in app config or INI file.
application config files are one idea, but because they are managed through the IDE means have to change manually for deployment.
Better to use the registry (cleaner too - no need to post-edit the file), and the installer can get conditional on where it's deployed, alternatively ask the user during installation, skip if the registry entry already exists.), confirm the connection string at install time. database path/host/name exists...
You can store it in the app.config of your project. Then if you wanted the user to give credentials you could make a form and save the string to the value of that configuration.
<appSettings>
<add key="connectionString" value="Connection string goes here"/>
</appSettings>
Then call it and set it using the ConfigurationManager
ConfigurationManager.AppSettings["connectionString"] = "Your Value";
Or you could just replace the connection string yourself in the file once its on the users computer
I have the following connection string:
Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID=sa;Password=password
(.net webservice)
This can obviously be viewed simply by opening up the app.config file and looking at the configuration settings.
What I need is a way to make a hacker unable to see the password. But at the same time, leave it customisable so that it can be changed when deployed on another database.
You have a number of options - the ones that I am aware of (in order of preference):
Use integrated (SSPI) security where you don't need to include a password in the config file
Encrypt the connection string (see Encrypting Configuration Information Using Protected Configuration)
Store the username and password separately and use string formatting to construct the full connection string,
So for example the connection string might look like this:
Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID={0};Password={1}
I'd go for option 1, if thats not possible then option 2. I've mentioned option 3 for completeness.
Have you read Protecting Connection Information (ADO.NET)?
First of all, don't use the "SA" account. It leaves your database wide open if someone gets the password. Use a custom account which only is allowed to do CRUD operations on a specific database.
The only way to get web.config is to hack your server. And if they have done that, you're screwed anyway.
Probably easiest to encrypt the connection strings within the web.config or app.config
See How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI
I Suggest en/decrypting the connection string. Therefore the connection string has to be set manually.
For encryption take a look at:
http://dotnet-snippets.de/dns/encrypt-and-decrypt-strings-SID205.aspx
For Custom Settings take a look at:
http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx
Replace the Encrypted with the correct one at runtime:
public static void SetAppSettingValue(string Key, string Value)
{
System.Configuration.Configuration config == ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings[Key].Value = Value;
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
You could encrypt the connection string - then when you access the connection string, decrypt it. This isn't fool proof though as you're then stuck with the problem of where to store the key to decrypt the connection string!
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
First, forgive my english.
My group and I are planning to do an application. This application can be installed to other machines, and should connect to a server and the database is password protected.
As a student, we always do this in a naive way:
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"database=database; " +
"connection timeout=30");
Always hardcoded.
What if we change the password of the database, or chage our server?
We have also to change the values in our code, recompile and reinstall the application in the pc. Is there something dynamic way of doing these?
We are thinking that in the first run of the application, the user will be prompted for the connection details and save that data into a file where the application will fetch it everytime it starts and use it for database connection, but there's a password involved.
Any suggestion, ideas, concepts, samples, etc...? How to do it in more professional way? Please help... Thanks.
You could store the database settings in app.config
http://www.ezzylearning.com/tutorial.aspx?tid=8067328
you could store your credentials in the config file - that way no need to recompile the project every time the password changes.
The config file can be encrypted too, so you could only change the password via the application you're making.
Windows lets you encrypt files, so that only processes running as the owner can read them. You could store the passwords in a file and encrypt it. See File.Encrypt on MSDN.
This would only be one factor in the security model. You probably also want to encrypt the file at the application level so malicious software that the users run doesn't sniff around for passwords.
There are several ways to do this. First off all you may save your connectionString in an app.Config/web.config file. Your connection objects may access this string by using
PROJECTNAME.Properties.Settings.Default.YOURCONNECTIONSTRINGNAME
Your app.config file may look something like this
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Winforms_Demo.Properties.Settings.dbNordwindConnectionString"
connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=dbNordwind;User ID=sa"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
As you can see this possibility still saves any user credentials hardcoded (although you may change them by manually editing the config.file (even after compiling). You may create such a config file by adding a new datasource to your project (e.g. sql server datasource). The wizard will then ask where to save your connectionString.
Another possibility will be connectionStringBuilder. This class offers some properties:
SqlConnectionStringBuilder conbuild = new SqlConnectionStringBuilder();
conbuild.InitialCatalog = "dbNordwind"; // database name
conbuild.IntegratedSecurity = false; // true if you use winAuthent
conbuild.UserID = "sa"; // e.g get this info by showing a authent form
conbuild.Password = "123";
conbuild.DataSource = "servername";
SqlConnection con = new SqlConnection(conbuild.ConnectionString);
Using this method you may even access a file and read any required data. In this case you have to look into security measures for your file!
Securing your file may be done by encrypting it (System.Security namespace) or saving data into any isolatedStorage (user specific - windows security will be used) or by using "aspnet_regiis -pef" to crypt any config-file.
As I transfer my Windows form application in C#.net from one computer to another, I have to change the connection string every time as the location of the Database file has changed.
How can I can I prevent this,so that I don't have to change the connection string again and again?
If the service you need to connect is always running on the local machine, you might use the localhost as the server name...
By the way localhost is mapped to the ip 127.0.0.1 in the hosts file.
Have your DB file in the same location of your application exe and then you can use
Application.StartupPath()
to get the path.
*I am assuming that this is a Windows Forms Application.
How has the location of the database changed? Is it not in a central location that all computers/users can access?
If not, you could store the connection information in settings and create a form that allows you to update those as needed. The form could be launched as part of the installer or on first run of the application.
A little more information about what you're doing would be helpful in presenting a real solution.
It's tricky to tell without an example of the type of connection string you're using (or which database you're accessing) but can't you use a relative path and assume that the database is somewhere relative to your app?
If you set your connection sting up like this...
<connectionStrings>
<add name="ConsoleApplication1.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
... then |DataDirectory| will by default resolve to the application's folder. You can, however, change DataDirectory by calling the AppDomain.SetData method. See the following for how to change it...
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/805bfd29-d864-4400-b353-bea13167f046
I've shown how you'd set the connection string in config, but the same holds true if you're setting it in code. If you are building a connection string in code, then may I suggest you look at using a connection string builder...
http://msdn.microsoft.com/en-us/library/ms254947.aspx
I am, of course, assuming a file path in your connection string, but if it's a database then won't localhost also work?