How to change application settings (Settings) while app is open? - c#

I've written a class that should allow me to easily read and write values in app settings:
public static class SettingsManager
{
public static string ComplexValidationsString
{
get { return (string)Properties.Settings.Default["ComplexValidations"]; }
set
{
Properties.Settings.Default["ComplexValidations"] = value;
Properties.Settings.Default.Save();
}
}
the problem is the value isn't really saved, I mean it is not changed when I exit the application and run it again. What can I do to ensure that the saved value persists between closing and opening again?

settings scope must be user not application

You should check
Properties.Settings.Default.Properties["ComplexValidations"].IsReadOnly
It is probably true, this is what Roland means with "Application Scope". Save will fail silently. Take a look at Project|Properties|Settings, 3rd column.

Are you sure it's not saving the changes? The [ProgramName].exe.config file in the bin folder won't be updated. The acutal file used is usually put in C:\Documents and Settings\[user]\Local Settings\Application Data\[company name]\[application].exe[hash string]\[version]\user.config. I know when I tried this kind of thing it took me a while to realise this was the file that was getting updated.

I just tested a User Setting and it is persisted if you run this Console app twice:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Settings1.Default.Setting);
Console.ReadLine();
Settings1.Default.Setting = "A value different from app.config's";
Settings1.Default.Save();
}
}
Just try it out. It won't take a minute.

Related

How do I use the 'Project Properties>Settings'?

I want to set a cache limit for my C# program so I decided to use the Project Properties>Settings function of Visual Studio [2015] to do so.
I had some help and was told to enter this.
My settings I want are as follows:
Folder Path- C:\SysApp
Size Limit- 150MB
Amount to Delete- 149MB
For the sizeLimit and toDelete sections I need to know what unit (ie. bytes, megabytes, kilobytes...) they're in so I can convert them to what I listed above.
I was also told that
If you change the settings value in the program you need to save the new values before exiting the application. This is done with Properties.Settings.Default.Save();. This command creates a .config file with your values.
I need to know where in my coding to insert the Properties.Settings.Default.Save(); command.
Screenshots would be very helpful. Thanks.
The is no possibility to store metadata like units into default settings. You have to define the unit (kB, MB,...) the user should enter or store it as a string (e.g. 150MB) and parse it yourself.
The Save method must be called after setting the values (example):
Properties.Settings.Default.sizeLimit = 150000
Properties.Settings.Default.Save();
If you only want to read the settings (see comments below) change the scope of the settings from "User" to "Application" and read the settings in your program like this:
class Program {
void main(string args[]) {
String folderPath = Properties.Setings.Default.folder;
int folderSizeLimit = Properties.Setings.Default.sizeLimit;
int amountToDelete = Properties.Setings.Default.toDelete;
DeleteOldFilesIfOverFolderLimit(folderPath, folderSizeLimit, amountToDelete);
}
private private void DeleteOldFilesIfOverFolderLimit(string folderPath,
long folderSizeLimit,
long amountToDelete)
...... from other post .....
}
}

Storing the Users Choice in C# Winform permanently

How can I store the user's choice permanently in c# winform.
I wrote this code to fetch the setting:
string my_data_to_do = (string)Settings.Default["MyDataToDo"];
And to save the user's setting I wrote:
if (checkBox3.Checked)
{
Settings.Default["MyDataToDo"] = "Tasks In Hand";
}
else
{
Settings.Default["MyDataToDo"] = "Nothing To Do";
}
This is showing the saved data but only until I exit my application. When I exit and start my program again, all these settings gets automatically removed, and the default data comes, which I saved in Settings.settings file.
Can anyone please help me in this?
It's hard to tell if you're doing it from just the code exert you've posted, but after setting the setting like that you will need to call Settings.Default.Save() to have it persist beyond the application closing.

can record unc connection?

The Pc I use have an UNC file. I'm in a Network with other people.
Every other can open the file by tipping in the adress line \\file.
Know I want to write a c# programm in Vs2010 which watch over the file I use Win7 32bit. If any one Open the file the programm shall write in a Logfile that someone has open my file.
I tried to use the FileSystemWatcher but this only look for changes/saves/cration but not for Opening.
I read somthing about "auditing" and that I'm be able to do that(watch over my unc file) with this(auditing).But i tried to find out how to use auditing in c# but i found not much.
.
So my Questions:
Is it possible to do what i want with "auditing" ?
Did someone worked with auditing in c# befor or has anyone a link or somtihng to show me how it works in c#?
mfg Sam
Sry for bad english
You might want to use the Audit Object Access.
The steps you have to follow:
Enable the Audit object access in the Local Computer Policy.
Enable auditing for the object you want to follow.
From your application, use the EventLog.EntryWritten Event to detect the file opening event
Here's a simplistic sample usage, but you'll have to dig in the documentation in order to capture and log as you need to:
class Program
{
public static void Main()
{
EventLog myNewLog = new EventLog("Security", ".", "Microsoft Windows security");
myNewLog.EntryWritten += new EntryWrittenEventHandler(MyOnEntryWritten);
myNewLog.EnableRaisingEvents = true;
Console.ReadLine();
}
public static async void MyOnEntryWritten(object source, EntryWrittenEventArgs e)
{
await Task.Factory.StartNew(() =>
{
if (e.Entry.InstanceId == 4656 || e.Entry.InstanceId == 4663)
{
Console.WriteLine(e.Entry.Message);
}
});
}
}

How to add entity-framework to console application (images are included)

I try to add entity-framework to console application:
I press "add new item" and
then
then
then I added code:
class Program
{
static void Main(string[] args)
{
try
{
Database1Entities db = new Database1Entities();
db.AddToTableTest(new TableTest { name = "name" });
db.SaveChanges();
int count = db.TableTest.Count();
int ui = 9 + 0;
}
catch (Exception e)
{
}
}
}
It gives no error, but I don't see any changes in database.
I described the issue better here
I did the same steps you did to setup a EF model. your database.mdf file has the Copy to Output Directory set to Copy always, that means that every time you hit F5 (build or debug your app) the file is getting replaced by the empty one on your project.
Changing the Copy to Output Directory on the Properties window of the mdf file should solve your problem.
If you use Copy if newer you are going to be persisting any modifications on the contents of the database until you edit the database (mdf) itself.
With Do not copy any change to the mdf file is not going to get reflected on your application and will probably generate problems with EF.
I recommend for this scenario that you use Copy if newer and fill your basic data in the mdf file so you will have it always available.

Count the number of times the Program has been launched

How can I get the number of times a program has previously run in c# without keeping a file and tallying. Is there a Application class or something in c# to check the count.
Please give a detailed explantion as i know nothing about it.This is A windows console application not windows forms.
You can do that my creating an Entry in the Registry. And another way is by using an Application Settings.
But I prefer Application Settings because it has less task to do.
See HERE: Creating an Application Settings.
Tutorial From Youtube
Recent versions of Windows automatically maintain this information in the registry under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist.
The data is obfuscated with ROT13, but that's easy to "decrypt". A free utility (with source code) is available and can serve as your starting point.
You could send a message to a database or webservice every time the program starts up (assuming there's a network connection).
You could keep a count on some form of hardware thet's not a standard storage device (therefore not technically being a file).
You could make a registry entry that you keep the count in (if you ignore the fact that the registry entry is, at some level, persisted into a file somewhere).
You could just have a file somewhere that keeps track of the count. Not sure why you're so opposed to this one in the first place....
If you are running a Winforms application, the you can easily use the Application Settings. Right click on your Solution Name --> Properties --> Settings Tab. More info and tutorial here.
Then, every time your program starts, increment this setting and save it.
Ref: Count the number of times the Program has been launched
In my knowledge Windows does not keep this information for you. You would have to tally the value somewhere (file, database, registry setting).
Better way is Application Settings as:
Create setting in app.config and then use it as:
Properties.Settings.Default.FirstUserSetting = "abc";
then, you usually do this in the Closing event handler of the main form. The following statement to Save settings method.
Properties.Settings.Default.Save();
Implementation using Registry:
static string AppRegyPath = "Software\\Cheeso\\ApplicationName";
static string rvn_Runs = "Runs";
private Microsoft.Win32.RegistryKey _appCuKey;
public Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegyPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegyPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
public int UpdateRunCount()
{
int x = (Int32)AppCuKey.GetValue(rvn_Runs, 0);
x++;
AppCuKey.SetValue(rvn_Runs, x);
return x;
}
If it's a WinForms app, you can hook the Form's OnClosing event to run UpdateCount.
Then Check tutorial to Read, write and delete from registry with C#

Categories