C# Connection string save into AppData? - c#

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.

Related

How do I create a generic file path to a local database in a C# Application?

I have a simple data entry Windows Form with a datagridview display that links to a local database. When I run the program and try to add data on another computer, I get this message:
Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.
An attempt to attach an auto-named database for file C:\Users\roberto.yepez\Documents\Visual Studio\2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
The file path is to the path on the computer where I coded the program.
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True".ToString());
I am a self-taught coder, please help! :)
I believe you're running into a problem because your local sql server to which your code is trying to attach the StudentInfo1.mdf (whose path is in the connection string) already contains a database called StudentInfo1 - it decided to try and create a database of this name based on the name of the mdf file. I'm guessing that you can pick your own name by specifying Initial Catalog in your connection string but this would mean there are two databases with possibly the same set of tables and a potential for confusion
Per the comment I posted I would instead advocate that you use SQL Server Management Studio to permanently attach your db (you make have already done this) and then adjust your connection string so that it refers to the permanently attached db. This reduces the chances that your next question will be "my code says it's updating my db but I cannot see any changes!?"
Please move this connection string
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True"
to app.config file. When you deploy to production, change the paths in that app.config, according to the production machine settings.
You can even apply transformations on the app.config to deploy in various machines/scenarios.

Error opening connection to SQL CE file on test machine

I'm testing my application on a non-administrator windows 7 account. The application is installed into program files. This includes the .sdf file I need to read from. I've got the connection string marked as read only and set the temp path to my documents. This is the error that it spits out when I try to do connection.Open()
Internal error: Cannot open the shared
memory region
I've got the connection string defined in app.config, but I'm modifying it before I start using the connection. This part is in app.config Data Source=|DataDirectory|\DB.sdf;Password=password;
And then I modify it like so:
connection = new SqlCeConnection(connectionString +
";Mode=Read Only; Temp Path=" + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
This works on my developer machine (obviously) since its running from outside of a read-only directory. But even when I manually mark the .sdf file as read-only it still works, and successfully creates the temporary db file in the correct folder. However, on the test machine everything is located in a read-only program files folder, and it doesn't work.
The main goal of this problem is trying to make sure my program doesn't have to be ran as an administrator, and I would like to keep from moving the main copy of the db file from outside of the installation directory.
Let me know if I need to explain anything else. Thanks
I'm using a sql ce database too and had the same problems. my solution was to create the database in a subfolder in Environment.SpecialFolder.CommonApplicationData. If only one user will use it you can create it in Environment.SpecialFolder.ApplicationData. But here you don't need admin rights.
Another point is your connection string in your app.config. If you'll modify it in your program like me, it must be located in such a 'non-admin-right-needed' folder too. I have a static app.config in my app-folder in program files, but a second one with the connection string in Environment.SpecialFolder.LocalApplicationData (this is 'username\AppData\Local' in Win7). And I protect my connectionstring with DataProtectionConfigurationProvider encryption, so no one can read the data base password.
This is how you can map your second app.config to your app:
string ConfigPathString = #"{0}\MyApp\MyApp.config";
string ConfigPath = String.Format( ConfigPathString, System.Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData ) );
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = ConfigPath;
Configuration Config = ConfigurationManager.OpenMappedExeConfiguration( fileMap, ConfigurationUserLevel.None );
string myConnectionString = ConnectionStrings.ConnectionStrings["MyConnectionStringKey"].ConnectionString;
Like Calgary already mentioned in his comments you can't really open the file directly in the programs folder due to the restrictions of Windows 7 to non-admins. But due to the fact that you don't want to write anything into it, why don't you simply copy at startup the file into Environment.SpecialFolder.ApplicationData?
When your program starts up simply copy the file out of the programs folder into a proper location, use it as you like and delete it on application exit. So you don't leave any fragments (except the application would crash).
Just to be sure for the last scenario, you could add an additional delete operation to the setup deinstallation routine. So if the application will be removed and it crashed at the last start the setup will remove the trash, leaving the machine as before the installation of the software.

Establishing database connection

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.

connect Access via c#

i need to open a connection to a remote access db.
in the local environment to the remote acess db is working great .
when i run this application from production server (other server) it's fail with message
"
It is already opened exclusively by another user, or you need permission to view its data.
"
my code :
conString =
#"Provider=Microsoft.JET.OLEDB.4.0;"
+ #"data source=" \\150.248.248.38\d$\TestApp\vending.mdb;Jet OLEDB:Database Password=1234;";
OleDbConnection connAccess = new OleDbConnection(conString);
try
{
connAccess.Open();
objDiningRoom.Connection = connAccess;
....
}
catch (Exception ex)
{
}
finally
{
connAccess.Close();
connAccess.Dispose();
}
*Its not open in other place
thanks
This looks like it is a permissions problem.
Make sure you give the IUSR account (or whatever account ASP.NET runs as) read/write permissions to your database.
you can try :here
copied from there :
This commonly occurs when your database file is opened exclusively
by another application (usually MS
Access). Close all applications that
use this database and try again.
This error may occur if the account being used by Internet Information
Server (IIS), (usually IUSR), does
not have the correct Windows NT
permissions for a file-based database
or for the folder containing the
file.
Check the permissions on the file and the folder. Make sure that you
have the ability to create and/or
destroy any temporary files.
Temporary files are usually created
in the same folder as the database,
but the file may also be created in
other folders such as /Winnt. If
you use a network path to the
database (UNC or mapped drive),
check the permissions on the share,
the file, and the folder.
Check to make sure that the file and the data source name (DSN) are
not marked as Exclusive.
Simplify. Use a System DSN that uses a local drive letter. Move the
database to the local drive if
necessary to test.
The "other user" might be Visual InterDev. Close any Visual InterDev
projects that contain a data
connection to the database.
This error may also occur when accessing a local Microsoft Access
database linked to a table where the
table is in an Access database on a
network server. In this situation,
please refer to the following article
in the Microsoft Knowledge Base for a
workaround: Q189408 PRB: ASP Fails to
Access Network Files Under IIS 4.0

OLEDBConnection.Open() generates 'Unspecified error'

I have an application that uploads an Excel .xls file to the file system, opens the file with an oledbconnection object using the .open() method on the object instance and then stores the data in a database. The upload and writing of the file to the file system works fine but I get an error when trying to open the file on our production server only. The application works fine on two other servers (development and testing servers).
The following code generates an 'Unspecified Error' in the Exception.Message.
Quote:
System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
try
{
x.Open();
}
catch (Exception exp)
{
string errorEmailBody = " OpenExcelSpreadSheet() in Utilities.cs. " + exp.Message;
Utilities.SendErrorEmail(errorEmailBody);
}
:End Quote
The server's c:\\temp and c:\Documents and Settings\\aspnet\local settings\temp folder both give \aspnet full control.
I believe that there is some kind of permissions issue but can't seem to find any difference between the permissions on the noted folders and the folder/directory where the Excel file is uploaded. The same location is used to save the file and open it and the methods do work on my workstation and two web servers. Windows 2000 SP4 servers.
While the permissions issue may be more common you can also encounter this error from Windows file system/Access Jet DB Engine connection limits, 64/255 I think. If you bust the 255 Access read/write concurrent connections or the 64(?) connection limit per process you can get this exact same error. At least I've come across that in an application where connections were being continually created and never properly closed. A simple Conn.close(); dropped in and life was good. I imagine Excel could have similar issues.
Try wrapping the location in single quotes
System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + location + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
If you're using impersonation you'll need to give permission to the impersonation user instead of/in addition to the aspnet user.
Anything in the inner exception? Is this a 64-bit application? The OLEDB providers don't work in 64-bit. You have to have your application target x86. Found this when getting an error trying to open access DB on my 64-bit computer.
I've gotten that error over the permissions thing, but it looks like you have that covered. I also have seen it with one of the flags in the connection string -- you might play with that a bit.
Yup. I did that too. Took out IMEX=1, took out Extended Properties, etc. I managed to break it on the dev and test servers. :) I put those back in one at a time until it was fixed on dev and test again but still no workie on prod.
not sure if this is the problem you are facing,
but, before disposing of the connection, you should do Connection.Close(),because the Connection.Dispose() command is inherited from Component and does not properly dispose of certain connection resources.
not properly disposing of the connection could lead to access issues.

Categories