How do I write to a non-standard config file? - c#

I have a file called middle.config that is deployed in the same directory as an exe, but I need to update values in this file. That means that I have to go to C:\Program Files (x86)\ directory to access the file. Although it is named as a .config file it does not follow the usual schema of a .config file. It looks like this:
<configuationSettings>
<middleSettings
groupName="XYZ"
forkName="SomeDbName"
dbServerName="123.123.123.123"
cnnTimeoutSeconds="30"
cmdDefaultTimeoutSeconds="30"
cmdMediumTimeoutSeconds="60"
cmdLongTimeoutSeconds="480"
/>
<userKeys>
<Assemblies value="C:\assemblies\" />
</userKeys>
<friendlyDbName value="NiceData"/>
</configuationSettings>
I'm able to read and manipulate the content with Xml, but when I try to save the file back, a "No Permissions" error is thrown. I cannot relocate the file. I'm stuck with this legacy schema so I'm not able to treat it like a normal .config file using ConfigurationManager.OpenExeConfiguration. I cannot define sections or groups on this schema (I've not been able to anyway). All my users are Administrators on their local machines.
How do I overwrite or delete and replace this file while it is in a protected directory(my assumption about the permissions error)? Failing that, is there a way to access this schema somehow with ConfigurationManager.OpenExeConfiguration.
{edit starts here}
There are three applications in this scenario, A, B, and mine C. Application A does not know about any other applications. It can connect to many, many databases, and it drops a single file 'middle.config' that contains pointer info to the last database location that was used by the last Application A session. Application B, let's call it an import/export application, only operates on the last Application A database location. Application B reads the 'middle.config' file for database pointer info and then executes console commands against that database. It performs bulk dumps or bulk imports for selected portions of the database.
This was the situation when I come along to build application C that uses the import/export application B to fetch, blocks of data and return them to the database. So, in order for application C to use Application B
against any database, application C must modify the 'middle.config' file so that application B will find the correct database. Application C is new and the other two are legacy. I either find a way to make this work, or I force the user to start Application A and point to the database of interest, then close Application A. This is VERY unhandy.
{edit ends here}

It is not advisable to write data files to the program files directory, as this requires elevated permissions. Giving a program elevated permissions just to update a config file clashes with the Principal of Least Privilege, which states that
a particular abstraction layer of a computing environment, every
module (such as a process, a user or a program depending on the
subject) must be able to access only the information and resources
that are necessary for its legitimate purpose
It's not a "legitimate purpose" to give the process elevated permissions (that can allow it to do many harmful things) just to update a config file. MS recommended practice is to write that type of data elsewhere.
Instead, consider storing the config file in a subfolder of the ApplicationData folder.

Suggested that your app is creating its own location under the AppData location folder for the current user instead of writing to files under location where the the app is installed (especially if under Program Files which is very strict.) Not suggested to force the user to run as Administrator for your application either.

Your assumption about protected directories is correct. Program Files has an Access Control List which prevents modification by processes running as standard users and, on Vista upwards, even by administrator processes which are not running elevated. Accessing the file using the standard configuration classes would not get around this.
If you absolutely can't move the file (Eric J. is right when says that writing to Program Files after installation is a bad idea), then you could embed a manifest in your config file-editing program which will try to force elevation with a UAC prompt at launch. Of course, the best solution would involve a) using standard config schema and b) keeping user data in user-writeable locations, but sometimes that isn't possible for legacy reasons.
I'm not aware of any way to persuade ConfigurationManager to read a non-standard schema, unfortunately.

Move the logic to a separate process and launch it with admin privileges from your current application.

From a different angle, look at this: Writing custom sections into app.config
I found the linked article to be very useful. Not sure it is going to answer all your questions though.

Related

Protect the SQLite format 3 to my application only

Database File and Application that reads the db. The application has a registration component added. If the user doesn't want to register they can simply download the open source application, copy the database to the new folder, run a batch file and the database opens in the application, completely eliminating the registration and whatever extra features were added.
I want to keep the database file inhouse, even if it means adding the db file into the resources of the main application. The file does require data to be written to that file.
I've gone as far as converting the batch file to an exe file and loading the database file or even renaming the database file to something obscure like abc.exe (Even though its a db file it can be renamed to anything)
Database file is renamed to an exe file for the time being, I would prefer to either have it encrypted somehow or somehow placed into the resources of my main application and accessed that way, I am just trying to limit the way the software can be pirated.
Encryption:
You can encrypt SQLite databases using extensions such as SQLite Encryption Extension. The usefulness of such encryption depends on what you are trying to do. If your application can read the keys to decrypt it, so can a hacker that can run your application. You can use Windows Data Protection API to manage the keys so that if someone copied the database from one windows machine to another, the database would be unreadable; but again, if the hacker can access the source machine, they can obtain the keys just like your application (but it would protect against a "dumb" user from just copying the files over).
Putting it in your "main application resources": If you mean embedding the database within the EXE, you are out of luck if you have a requirement to write the data. Generally speaking, an EXE cannot modify itself (though depending on OS/version/user permission/absense of antimalware agents, etc, you might theoretically accomplish a self-modifying EXE; but, if you want your app to work most of the time in the wild, this strategy won't succeed). Even if you did succeed in an EXE that read itself, loaded the embedded blob as a database, modified that database in memory, then rewrote the entire EXE with database exported as a new blob (of different size than the original, wreaking havoc on the assembly), it wouldn't help. The attacker can do what your app does and access the data. Do yourself a favor and follow the operating system's guidelines for writing user data. For Windows, this is generally reading and writing files to your Local App Data folder.
Renaming a SQLite database to have an EXE extension. What are you trying to accomplish? Obscurity? Renaming it to EXE might fool some users (certainly not the motivated user I've described above), but it also might accidentally fool anti-malware / anti-virus software running on your legitimate user's operating systems into thinking your application is writing malformed executables (which would be suspicious) and shut your application down, or at least prevent it from working correctly. This will cause your users to not use your application or a mountain of support for you. What does it gain? It stops a "dumb" user from trying to open it in a SQLite query tool?
All that said, if you want to limit your user's abilities to read the data stored on their own storage devices, you really can't stop a determined user. You can stop the less savvy users. The majority of users cannot run a reflector on a C# assembly and figure out what it is doing, but many can. If you want to stop the less savvy users, encryption of the data will stop most of them, and it will be the least likely approach you've discussed to prevent your application from working "in the wild".

How to load a config file based on user selection from "unknown" location

I have searched and searched and can't find a solution to my specific problem. I am updating a console app that will now be used for more than one client. We have decided, over storing the info in a db at least for now, to store the clients info in config files. Each client will have their own configuration file. I need to know how to load a/any config file from an "unknown" location. All of the examples that I found want me to put in the path of the file. While using my computer, I will know the path, but once it gets pushed to other servers, the paths to the file will change.
Working under these conditions, how can I load a config file for any client without knowing the path to the file?
EDIT: The console app is only ran on one server, but it is used to go to different clients websites and crawl their site. This is why each client has their own config file. It contains the information needed to get and use their site. We have a task set up for the app to run each client on a timer.
Since everything was being read from the bin folder, I looked at the properties and changed from Do Not Copy to Copy Always for Copy to Output Directory. Now it WILL locate the config files in the bin folder. And the answer to this question put me in the direction to read my config files.
What about writing every piece of code with in mind that it is to be used in another file, say with an include statement. So, every file is used in another one until we reach a wrapper file, which only purpose is to define the location of the config file. The application would always be called through such a wrapper file. This wrapper file will do whatever necessary to determine the location of the config file and make it available to the included files. If it knows the user, it can look up in a table. The key point here is that, the wrapper files would not move when you move the code from one environment to another. I think that this is a useful feature, because we do not want edit the code each time that we move it from one environment to another. Another advantage of this approach is that it applies to all environments, even very limited environments. For example, let say you provide only a folder to a programmer as a sandbox to experiment with the code. This programmer does not have access to the /bin or the /etc directory. In contrast, the proposed approach will work fine in this case, because the programmer can set the config files wherever he wants in its local wrapper files. This issue is discussed here How to organize code so that we can move and update it without having to edit the location of the configuration file?

Writable .config file for all users in application directory?

I need to have a common application settings file and i need it to be editable by the application at runtime.
I don't want to use the build in settings operation by putting "User" in settings scope because it gets saved in users local directory.
On the other hand i cant use the .config with "Application" as i cannot save into this file from within the application.
One might say "Create your own save settings XML file its easy"..Yes probably it is but i wonder what is the solution for a common writable config file with MS build in classes?
To have data, whatever the format, updateable by all users then all users need to be able to save to whatever container holds that data.
This applies whatever the format, from text file to RDBMS.
The problem with a file that you manage (eg. .config (XML) file) is twofold:
Concurrency.
Access Control.
The ConfigurationManager and associated classes will write to a .exe.config file with applicable declaration of the configuration elements and properties, but the underlying file has to be writeable. You'll need to:
Set an ACL in an installer so all (applicable) users have write access. This means outside the application they can write as well, this is unavoidable as there is no ability to set access control based on application.
Install outside Program Files. UAC virtualises writes to Program Files (so applications assuming all users can write anywhere don't break), but this also means it cannot be used for shared modifiable data.
Concurrency is another problem. What is two users both modify the shared data together? One user will overwrite the others changes unless you implement some locking and reloading on changed.
Consider using a multi-user database for the data instead. They are designed for this kind of thing, Config files are not.
Update (based on comment):
To have a (non-admin) user update a .exe.config in Program Files will still hit UAC virtualisation (ie. any writes will be directed to a per-user location, and not-visible to anyone else).
Easier to use the ConfigurationManager.OpenExeConfiguration(string) method to load a .config from some shared location (eg. in C:\ProgramData1) which has an appropriate ACL. The returned Configuration object has all the capabilities of the implicit load from .exe.config for <appSettings> as well as custom sections, plus access to Save and SaveAs.
1 Of course using correct methods to get actual local path, not hardcoding.

Where to store custom configuration files

I currently store a serialized XML file in the application directory that contains all changes specific to the program operation (not typical system or user configuration). Weeks ago, we started running into problems where it would not save correctly (read my previous question about this).
Long story short, we finally discovered that Windows 7 (and sometimes Vista) has an issue with writing into the application directory (specifically anything under Program Files). Now, if this were a normal configuration file I would simply store it under the user's APPDATA folder, but it is not normal. We run this on our own instrumentation, and misconfigurations are 99% of the reason customers have issues running our software. So we need this file to be accessible such that they can easily find it and email it to us. Appdata is hard enough for experienced users to find, much less very non-technological people.
We've also tried running it as Administrator, and making folder permissions wide open (we have control over every computer it runs on; it will never run on some random person's machine). But, these sometimes work, and sometimes do not.
The worst part is that when I write the file back out, it doesn't even throw an error; it simply writes it to some temporary directory that expires at some unknown point in time. Weeks later, our user will have an issue, and the configuration file is all messed up.
So, my question is where should I be storing this file, if not in Program Files? Should I just put it in APPDATA anyway, and make a small utility that emails it to us automatically in case of a problem? Or can I leave it in Program Files, but change some specific permission or registry key to allow it to operate normally?
It depends on whether or not the user needs to edit the file directly. If not, you should put them in %APPDATA%, which you can access via:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Otherwise, you might put it in My Documents:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Either way, putting it in Program Files is not a good idea. As you discovered, there are permission issues, even if running as Administrator.
For those users, you could build a button in that would open this directory. You could put it in an inconspicuous place that you could later direct them to.
For users that have an email client on their box, you could have a button that would create a new email with subject and automatically attach the file to the email.

Best place to store configuration files and log files on Windows for my program?

I need to store log files and configuration files for my application. Where is the best place to store them?
Right now, I'm just using the current directory, which ends up putting them in the Program Files directory where my program lives.
The log files will probably be accessed by the user somewhat regularly, so %APPDATA% seems a little hard to get to.
Is a directory under %USERPROFILE%\My Documents the best? It needs to work for all versions of Windows, from 2000 forward.
If you're not using ConfigurationManager to manage your application and user settings, you should be. The configuration toolkit in the .NET Framework is remarkably well thought out, and the Visual Studio tools that interoperate with it are too.
The default behavior of ConfigurationManager puts both invariant (application) and modifiable (user) settings in the right places: the application settings go in the application folder, and the user settings go in System.Environment.SpecialFolder.LocalApplicationData. It works properly under all versions of Windows that support .NET.
As for log files, System.Environment.SpecialFolder.LocalApplicationData is generally the place that you want to put them, because it's guaranteed to be user-writeable.
There are certainly cases where you wouldn't - for instance, if you want to write files to a network share so that you easily can access them remotely. There's a pretty wide range of ways to implement that, but most of them start with creating an application setting that contains the path to the shared folder. All of them involve administration.
I have a couple of complaints about ConfigurationManager and the VS tools: there needs to be better high-level documentation than there is, and better documentation of the VS-generated Settings class. The mechanism by which the app.config file turns into the application configuration file in the target build directory is opaque (and the source of one of the most frequently asked questions of all: "what happened to my connection string?"). And if there's a way of creating settings that don't have default values, I haven't found it.
Note: You can get the path to the LocalApplicationData folder in .NET by using the following function:
string strPath=System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
For application settings - use System.Environment.SpecialFolder.ApplicationData - this is where a roaming profile data is stored, so it allows your user to log and work from different machines in the domain.
For log files - System.Environment.SpecialFolder.LocalApplicationData
The accepted answer notes that for log files the following is a good spot.
System.Environment.SpecialFolder.LocalApplicationData This equates to a path of C:\Users\[User]\AppData\Roaming which you can see is user specific. Like the accepted answer mentions this is a guaranteed user-writeable location and can be useful for certain situations
However in a web application environment you may be running your application under a network account and you or a coworker may need to try and track down where exactly those logs are going per application. I personally like to use the non user specific location enumeration of
System.Environment.SpecialFolder.CommonApplicationData which equates to C:\ProgramData. Yes, you will need to specify access rights for any folders you create, but it's usually a one time deal and then all of your application logs can live in one happy location.
Additionally, while looking around the Internet, there is a project out there to programatically set write access to folders you create within CommonApplicationData, Allow write/modify access to CommonApplicationData.
To be honest %appdata% is still the best place to place your config files and log files, as it serves the purpose of a placeholder to store your application data. It should not be that hard to access, just write %appdata% in explorer and you will be directed straight to your %appdata% directory.
Do not store config files in the application folder, Microsoft has stated this is NOT the ideal location. Windows has been moving towards blocking writing to C:\Program Files\ and you'll find in Vista any application that tries to write here, will fire up a UAC warning.
Windows 7 will allow users to customize what UAC popups they use (expect some power users to block most of them) and your app will fail/freeze if the user never approves this write attempt.
If you use the proper userprofile and appdata variables, then Win 2000, XP, Vista, and Win7 will map the data to the proper write friendly folder, with no UAC popups.
You can use SHGetSpecialFolderPath:
int MAX_PATH = 255;
CString m_strMyPath;
SHGetSpecialFolderPath(NULL, m_strMyPath.GetBuffer(MAX_PATH), CSIDL_COMMON_APPDATA, TRUE);
This will specify the 'special folder path' which you can safely write logs to for windows:
For XP: C:\Documents and Settings\All Users\Application Data
For Vista: C:\ProgramData
Check the MSDN page here: http://msdn.microsoft.com/en-us/library/bb762204(VS.85).aspx
The best answer depends on the nature of the logs and configurations. If they are program-wide, and don't need to survive uninstallation of the application, then I think they're fine where they are. If the logs and configurations are user specific, or need to survive uninstallation, then they belong somewhere under %USERPROFILE% - %APPDATA% being the 'proper' base directory for this type of thing.
I use the Isolation Storage for configuration. You can also use the Temp folder to store temporary information like log.

Categories

Resources