How do I use the 'Project Properties>Settings'? - c#

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 .....
}
}

Related

How do I save multiple user settings in runtime in C#

I am trying to make my app stay the way I left it after closing the app. Therefore I want to save set of items from ListView to the settings and I can't figure out how to do that. I've found some solutions but I believe they are outdated as they don't seem to work.
Image shows set of items in ListView which I want to save so they appear there after restarting the app:
Items
This is where I want them to appear:
Settings
And this is part of code that I've tried out so far
private void btn_SaveConfig_Click(object sender, EventArgs e)
{
int i = 0;
Settings.Default["IP"] = tBox_discoverServerFrom.Text;
Settings.Default["DiscoveredServers"] = cBox_discoveredServers.Text;
foreach (var item in lV_groups.Items)
{
var property = new System.Configuration.SettingsProperty("Group"+i);
property.PropertyType = typeof(string);
property.Name = "Group " + i;
Settings.Default.Properties.Add(property);
Settings.Default.Save();
i++;
}
}
I do not think using the Settings API is a great idea if you want to save any significant amount of data.
I would recommend the following
Create a class describing all the data you want to save. To make serialization easier it should have a parameter less constructor and public setters for all properties. This is sometimes called a Data-Transfer-Object (DTO)
Use json to serialize the object to a file. You would normally place the file in a subfolder in the local app data folder: Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).
Do the reverse when you start the application. If there is a file, use Json to deserialize it and use it however you want.
You may optionally add logic to save the file periodically, this would allow recovery in case of application crashes. You might also want some system to keep more than one file, in case the application or computer crashes in the middle of a save operation, and the file becomes corrupt.

Write into a log file with C#

I am using the JitBit Macro Recorder to create "bots" that save me a lot of time at work. This program can use the mouse and the keyboard and perform tasks by checking different if-options like "if image found on screen".
My newest "bot" is about 900 lines of commands long and I would like to make a log-file to find an error somewhere in there. Sadly, this program doesn't offer such an option, but it let's me use c# as a task. I have NO experience with c# but I thought, that this is easy to do for someone who has some experience.
If I click execute c# code, I get the following input field:
Important: This code MUST contain a class named "Program" with a static method "Main"!
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
Now I need two code templates:
1. Write a message to a "bot_log.txt" located on my desktop.
[19.05.2016 - 12:21:09] "Checking if item with number 3 exists..."
The number "3" changes with every run and is an exact paste of the clipboard.
2. Add an empty line to the same file
(Everything should be added to a new line at the end of this file.)
If you have no idea how to program in C#, then you should learn it,
if you want to use code provided from answers.
And if you want to generate timestamps and stuff then it's not done within minutes and I don't think someone writes the whole code just for your fitting. Normally questions should have at least a bit of general interest.
Anyway:
This works, if you have a RichTextTbox in your program.
Just do a new event (like clicking a button) and do this inside it.
(This was posted somewhere here too or on another site, with sligh changes)
public static void SaveMyFile(RichTextBox rtb)
{
// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveLog = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the RTF extention for the file.
saveLog.DefaultExt = "*.rtf";
saveLog.Filter = "RTF Files|*.rtf"; //You can do other extensions here.
// Determine whether the user selected a file name from the saveFileDialog.
if (saveLog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveLog.FileName.Length > 0)
{
// Save the contents of the RichTextBox into the file.
try
{
rtb.SaveFile(saveLog.FileName);
}
catch
{
MessageBox.Show("Error creating the file.\n Is the name correct and is enough free space on your disk\n ?");
}
MessageBox.Show("Logfile was saved successful.");
}
}

C# app.config read and write

Can we save data or some text in app.config file
if yes then it is persistence or temporary ?
for example if i store last access date time in app.config file and then close/Exit the application after the some time/days/years when i start my application is it possible that the last access date time I can retrieve. If yes then how please explain with code ....
Thanks,
Raj
here is my code ..
Trying to retrieve date time from config file..
But show error object not set to be an object like...
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (email.To.Contains(Email) && DateTime.Compare(email.UtcDateTime.Date, Convert.ToDateTime(config.AppSettings.Settings["ModificationDate"].Value)) > 0)
Here i store /save the date time in app.config file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration
(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings.Add("ModificationDate", DateTime.Now + " ");
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine("Last Update :"+config.AppSettings.Settings["ModificationDate"].Value);
Console.ReadLine();
Please suggest me why it show me an error that object not set am done any mistake please ans...
You can create a settings xml file to do this.
In VS go to your project properties -> Settings, then write a value in.
In code, you can get/set that value using
Properties.Settings.Default.YourVariable = 0;
If you are setting the value make sure to save it
Properties.Settings.Default.Save();
See here for a good tutorial.
I would use a custom configuration section to create your configuration type - last access date time. you can create more complex hierarchy configuration and strongly-typed.
Again, it depend on your requirement and design if you need to do that. otherwise, standard file storage(txt/xml) would also allow you to do that. I personally normally using app.config for application specific level(appearance/fonts/servername etc.) configuration rather than transactional configuration.
for e.g
public class LastAccessConfigurationSection : System.Configuration.ConfigurationSection {
[ConfigurationProperty("LastAccess")]
public string LastAccess{
get { return (string)this["LaunchTime"]; }
set { this["LaunchTime"] = value; }
}
}
you can have a static class to manage the life-cycle that would allow you to persist the change.
public static LastAccessConfigurationSection Config { get; internal set; }
public static void Initialize() {
Config = ConfigurationManager.GetSection("LastAccess") as LastAccessConfigurationSection;
}
You could use App.config for storage like any other file and it will persist and be available the next time you run your program. That is the nature of file storage in general. I would suggest that you store that data in a separate file or database. I will not, however, write the code for you.

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#

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

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.

Categories