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.
Related
I am trying to make a sql server connection. I have used ASP.net web form template which is having its own login and register Ui. I just have to use my sql Server name and the database name in the connection configuration. I had googled and read regarding the sql connection. I FOUND something like this in WEbconfig i have to alter..
<connectionStrings >
<add
name="myConnectionString"
connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
It does not work if i use it . Should i use SqlConnection con = new SqlConnection(strcon); in my login page.if in case, then where ? While in this template i have something like..
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
.....
I ma bit confused please educate me or guide me in the right way.
I have a server name xyz-1-2, database name: data123, username: abcd123 and password: asdf123.
I am trying to connect to one database and visualize the data.
I assume you are using at least Visual Studio 2013 to create the web form project by using the default template available there.
Now, let's take a look on the database setup first, as it seems like this is the one you're asking about.
After the project generation, the default connection string in the web.config file, usually look like this :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebMVCWithAuth-20180220020657.mdf;Initial Catalog=aspnet-WebMVCWithAuth-20180220020657;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
When will the connection string be used actually in the project? Please examine the screenshot below :
It's not necessary to change the connection's name here, but please do adjust the connectionString value, in the later stage.
So, where's the actual database file resides, you may ask? Actually, it is hidden in the App_Data folder, and you will not see it until click the "Show All Files" icon just below the "Solution Explorer" header, as shown in the following screenshot :
And how do you browse the content of this database? Look into the left-most of the VS editor and find a toolbox "Server Explorer", and there you are. See this screenshot?
Now by the time you end reading this, you should have an idea how to have your own user manager database, based on this template.
Oh, and one more tip : you can actually copy this local database to a real server and attach it to the database server so you may continuously maintain the database in a more secure environment.
Hope it helps.
So I have a DB (webster.accdb) which will be getting installed on a server (eg. \SERVER\WEBSTER)
However different locations may have differing SERVER names (ADMIN1 etc etc)
When the program originally installs, it checks the con string in app.config which I have put as "DEFAULT" - literally the string.
The program checks the connection string in app config, and if it is DEFAULT, then it runs a little prompt i have made which asks for details from the user regarding the server name and a few other specifics.
They click "connect" and it writes the newly constructed connection string to app.config and the program loads after a series of tests.
Now this works under VS tests and installs on D: drives in temp folders. My issue is that if 'properly' installed to the programfiles section, then we now have the issue of access being denied to alter the file.
So could someone point me in the right direction with regards to the correct process as i know I'm doing it wrong:
Create an XML in Appdata for the user, which has the con strings, and this is generated on first use, and is used for the constrings from then on?
Save the con strings as Settings, and use This code to update settings, then make sure all my con strings in my program no longer point to configuration, but to settings??
Something better because I am clueless and this is totally not how i should be doing this at all!
Code used to update the config:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["LOTSConnectionString"].ConnectionString = "Data Source=" + txtpcname.Text + ";Initial Catalog=" + cmbdispense.SelectedItem + ";Integrated Security=False;User ID=webbit;Password=ill923r6MG";
config.Save(ConfigurationSaveMode.Modified, true);
Access Denied means the user which is executing the app either does not have permission or because of inbuilt security by Operating System, app is executing under restricted permissions. Try executing app with Administrator by right clicking on it and choosing run as.
You can prevent this by Setting up connection string at the time of installation instead. Prompt a user to enter details during installation.
So pretty much I self confess to not understanding the benefits of the USER section of the config.
I have changed my connection strings to just "STRING" and put in the USER section of Settings.
Now i can refer to my strings as
properties.settings.default["ConString"].tostring
This is then saved to User/APPDATA/Local
For noobs like me reading this, that means the original app.config file in programfiles stays THE SAME, but an excerpt is taken out of it relating to the user section and put into appdata.
What was confusing me the whole time was selecting "connection string" in settings, which didnt allow selection as a USER setting.
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
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.
I have a desktop WPF application which uses Entity Framework 4.1 Code First approach to manage data.
EF adds a connection string to the App.config file and I wan't to be able to change this connection string at runtime.
Scenario is like this:
When I deploy the application it has a default connection string in the App.config file. The user runs the application and since the connection string will probably be invalid for the user (because of server name, user id and password) I will display a server configuration window.
Here user will enter the valid information about his connection and press OK. I will then be able to change the App.config file and save the user's new valid information to the file.
Problems:
If I change it using ConfigurationManager, the changes will be temporary meaning that the file is not saved, changes are made in memory.
If I read the App.config file into a stream, make required changes in the memory, delete physical file and save the in memory stream as App.config again, Windows will not let me make changes to files under ProgramFiles folder.
What is would be the best approach here?
EDIT: Problem Again!
After I modify the App.config file with this method:
private void ApplyChangesToConnectionString()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
config.Save(); // This line throws an exception
ConfigurationManager.RefreshSection("connectionStrings");
}
config.Save(); method call throws an error saying
"Access to "C:\Program Files (x86)\MyCompany\MyApp\MyApp.exe.config"
is denied."
I know that files under "Program files" are immutable, so how can I handle this?
I couldn't modify ConfigurationManager.ConnectionStrings["key"] object, because it is readonly.
So I decided to add a new connection string to my App.config file so it looks like this:
<connectionStrings>
<add name="SomeUniqueName" connectionString="Data Source=(local)\SQLExpress;Initial Catalog=MyDb;User Id=sa;Password=password; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
and then changed my DbContext constructor to take newly added connection string like this:
public MyContext()
: base("name=SomeUniqueName")
{
}
Here, the value of name attribute at connection string and constructor must match.
Then to change this newly added connection string at runtime I used a method like this:
private void ApplyChangesToConnectionString()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
App.config is not the proper place to do this since it's a global configuration used by the application.
I recommend you to save the settings per user. See this related question : c# - approach for saving user settings in a WPF application?
App.config is the correct approach in my opinion, however I wouldn't rely on writing the file physically yourself. Instead, allow the framework to do the heavy lifting for you.
Check out the sample here.
EDIT: Glad Sandeep's comment above has helped you. Feel free to check out that link too if you want a bit more information!