Save/Read object values using Properties.Settings - c#

I want to save the state of my object when the software exit and restore it when the software loads. Im doing this (code below) now, but I think there must be another bether/smarter way to do that. :)
Ive read a little about Databing, but for this I would need to modify MyClass, deriving it from CollectionBase, etc.. Do you think it is a good ideia?
One more thing, is there a way to store a Point*F* (PointFFFF no Point) directly in Properties.Settings (I could not find it in browse)?
LoadConfig()
{
MyClass.ItemA = Properties.Settings.Default.ItemA;
}
SaveConfig()
{
Properties.Settings.Default.ItemA = MyClass.ItemA;
Settings.Default.Save();
}

I see nothing wrong with it. Yes, you could certainly use bindings also. You can create settings for other non-primitive types by going to type "Browse..." and then select the type you want to save. You would be able to browse for System.Drawing.Point and use that. It'll serialize the value in the app.config file.

Related

Unity/C# Savegame Migration

I've written a SaveLoad class, which contains a Savegame class that has a bunch of ints, doubles, bools but also more complex things like an array of self-written class objects.
That savegame object is being created, serialized and AES encrypted on save and vice versa on load - so far, so good.
The problem I'm facing now is that if there are new variables (in a newer version of the game) that have to be stored and loaded, the game crashes on load, because the new variables can't be loaded correctly (because they are not contained in the old save file). E.g. ints and doubles contain the default 0 while an array is not initialized, thus null.
My current "solution": For each variable that is being loaded, check if it doesn't contain a specific value (which I set in the Savegame class).
For example: In Savegame I set
public int myInt = int.MinValue;
and when loading, I check:
if(savegame.myInt != int.MinValue){
//load successful
}else{
//load failed
};
This works so far for int and double, but once I hit the first bool, I realized, that for every variable I have to find a value that makes "no sense"(not reachable usually), thus was a failed load. => Shitty method for bools.
I could now go ahead and convert all bools to int, but this is getting ugly...
There must be a cleaner and/or smarter solution to this. Maybe some sort of savegame migrator? If there is a well done, free plugin for this, that would also be fine for me, but I'd prefer a code-solution, which may also be more helpful for other people with a similar problem.
Thanks in advance! :)
Your issue is poor implementation.
If you are going to be having changes like this, you should be following Extend, Deprecate, Delete (EDD).
In this case, you should be implementing new properties/fields as nullables until you can go through and data repair your old save files. This way, you can check first if the loaded field is null or has a value. If it has a value, you're good to go, if it's null, you don't have a value, you need to handle that some way.
e.g.
/*We deprecate the old one by marking it obsolete*/
[Obsolete("Use NewSaveGameFile instead")]
public class OldSaveGameFile
{
public int SomeInt { get; set; }
}
/*We extend by creating a new class with old one's fields*/
/*and the new one's fields as nullables*/
public class NewSaveGameFile
{
public int SomeInt { get; set; }
public bool? SomeNullableBool { get; set; }
}
public class FileLoader
{
public SavedGame LoadMyFile()
{
NewSaveGameFile newFile = GetFileFromDatabase(); // Code to load the file
if (newFile.SomeNullableBool.HasValue)
{
// You're good to go
}
else
{
// It's missing this property, so set it to a default value and save it
}
}
}
Then once everything has been data repaired, you can fully migrate to the NewSaveGameFile and remove the nullables (this would be the delete step)
So one solution would be to store the version of the save file system in the save file itself. So a property called version.
Then when initially opening the file, you can call the correct method to load the save game. It could be a different method, an interface which gets versioned, different classes, etc but then you would require one of these for each save file version you have.
After loading it in file's version, you could then code migration objects/methods that would populate the default values as it becomes a newer version in memory. Similar to your checks above, but you'd need to know which properties/values need to be set between each version and apply the default. This would give you the ability to migrate forward to each version of the save file, so a really old save could be updated to the newest version available.
I'm facing the same problem and trying to build a sustainable solution. Ideally someone should be able to open the game in 10 years and still access their save, even if the game has changed substantially.
I'm having a hard time finding a library that does this for me, so I may build my own (please let me know if you know of one!)
The way that changing schemas is generally handled in the world of web-engineering is through migrations-- if an old version of a file is found, we run it through sequential schema migrations until it's up-to-date.
I can think of two ways to do this:
Either you could save all saved files to the cloud, say, in MongoDB, then change their save data for them whenever they make updates or
You need to run old save data through standardized migrations on the client when they attempt to load an old version of the save file
If I wanted to make the client update stale saved states then, every time I need to change the structure of the save file (on a game that's been released):
Create a new SavablePlayerData0_0_0 where 0_0_0 is using semantic versioning
Make sure every SavablePlayerData includes public string version="0_0_0"
We'll maintain static Dictionary<string, SavedPlayerData> versionToType = {"0_0_0": typeof(SavablePlayerData0_0_0)} and a static string currentSavedDataVersion
We'll also maintain a list of migration methods which we NEVER get rid of, something like:
Something like
public SavablePlayerData0_0_1 Migration_0_0_0_to_next(SavablePlayerData0_0_0 oldFile)
{
return new SavablePlayerData0_0_1(attrA: oldFile.attrA, attrB: someDefault);
}
Then you'd figure out which version they were on from the file version, the run their save state through sequential migrations until it matches the latest, valid state.
Something like (total pseudocode)
public NewSavedDataVersion MigrateToCurrent(PrevSavedDataVersion savedData)
{
nextSavedData = MigrationManager.migrationDict[GetVersion(savedData)]
if (GetVersion(nextSavedData) != MigrationManager.currentVersion) {
return MigrateToCurrent(nextSavedData, /* You'd keep a counter to look up the next one */)
}
}
Finally, you'd want to make sure you use a type alias and [Obsolete] to quickly shift over your codebase to the new save version
It might all-in-all be easier to just work with save-file-in-the-cloud so you can control migration. If you do this, then when a user tries to open the game with an older version, you must block them and force them to update the game to match the saved version stored in the cloud.

What is the difference between Settings.Default.[PropertyName] , Settings.Default.Properties and Settings.Default.PropertyValues?

I wanted to know the difference between these 3 Settings.Default.<PropertyName> , Settings.Default.Properties and Settings.Default.PropertyValues .
I have a wpf window that would dynamically generate controls based on these Settings and then one can update the Settings values
I first used Settings.Default.Properties Collection , but I believe it does not update the values in either config or the physical settings file in the user folder.
So I used reflection to update , But I still couldn't figure how to obtain
values by Reflection . (May still need to research on this)
Settings.Default.GetType().GetProperty(propertyName,
typeof(string)).SetValue(source, fileDialog.FileName, null);
Settings.Default.Save();
Settings.Default.Reload();
Then I saw Settings.Default.PropertyValues has the latest updated values and tested that in debug mode,
string properyValue =
Convert.ToString(Settings.Default.PropertyValues[propertyName].PropertyValue);
strangely they don't seem to be working when I created the installer and exe . Still to figure what exactly wrong.
Can someone point me out if I am complicating things and missing something?
Update 1
After nflash's comment , I checked when the file was created. The file was not created when the application starts for all 3 , I even called Settings.Default.Save right at the start but it doesn't create the file Settings.Default.<PropertyName> , Settings.Default.Properties are instantiated but Settings.Default.PropertyValues not.
Only once I make a change in the Settings and Save , the file is created.
Update2
Right now the solution that I came with is
source.GetType().GetProperty(setting.Name, typeof(string))
.SetValue(source, "NewValue", null);
As mentioned by nflash , it would be type safe (Although Reflection has it's demirits) . But the Settings.Default.<PropertyName> is synchronized and instantiated correctly hence.
Just want to add that you can only change settings with "User" scope. When you save the new value of the setting the value is not saved in the config in the application path but instead it is saved in the user.config inside the %localappdata% folder (%localappdata%\CompanyName\ApplicationName_someGUID\AppVersion)
Update:
About your last update, the user.config file is only created when you save a setting with a value different from the default value of the setting.
I'm not sure if you still have questions about this, so I'm trying to add more info:
Settings.Default.<PropertyName> as wonko79 pointed out is just a property accessor to the corresponding value. If you look at the code behind the settings (or just Go To Definition of the property) you will see something like this:
public string PropertyName {
get {
return ((string)(this["PropertyName"]));
}
set {
this["PropertyName"] = value;
}
}
The array operator is accessing the underlying structure that holds the values that in fact is the PropertyValues.
The difference between the Properties and PropertyValues is a little bit trickier. These are really two different structures (one is a SettingsPropertyCollection and the other is a SettingsPropertyValueCollection). The Properties property is defined in the ApplicationSettingsBase class and the PropertyValues is defined in the SettingsBase class.
The SettingsProperty class (elements of the SettingsPropertyCollection) contains information about the setting itself (metadata?) and its default value.
The SettingsPropertyValue class (elements of the SettingsPropertyValueCollection) contains the actual value of the setting and some additional control information, like if the value is dirty, if it is using default value, etc.
In the end of the day this is all how .NET internally manages the Settings and all that we need to know is how to get and set these settings.
I always like to work with the properties that the setting designer generates as it is strongly typed and already makes the cast to the corresponding type. Also using the Properties or PropertyValues requires a string as a parameter and in case of a typo I will only get an error in runtime as opposed to the compile error that I get if misspell the name of the property.
To save the settings after changing them you have to call
Settings.Default.Save();
Settings.Default.<PropertyName> is a property accessor to the corresponding settings value.
Settings.Default.Properties is a collection of all settings in your settings file.
Settings.Default.PropertyValues is a collection of all values of the settings in your settings file.
Maybe Using Settings in C# is a good starting point to read.
The article mentioned by user1064248 is good info, but does not address the PropertyValues issue. I cannot add anything to the good advice from Rameez and nflash except for this pragmatic advice: If you wish to force PropertyValues to populate, you need only to force a value to change. In my settings I have a DateTime property called "Timestamp" and if you put this in the form Load event, you will find that nn1 is zero, and nn2 contains the count all of the properties:
int nn1 = Properties.Settings.Default.PropertyValues.Count;
Properties.Settings.Default.Timestamp = DateTime.UtcNow; // Forces PropertyValues to load
int nn2 = Properties.Settings.Default.PropertyValues.Count;

Visual Studio Settings.settings file

Is there a way of creating a new setting in the Settings.settings file during run time?
For example, I want to write to the settings file from one class function, and read that value from a different class function. And no, I don't want to pass the values.
I know how to get values from the Settings.settings file
(value = Properties.Settings.Default.XXX)
I know how to update an existing value
(Properties.Settings.Default.XXX = newValue; Properties.Settings.Default.Save())
I want to know how I can add "Name", "Type", "Scope" and "Value" into the Settings.settings file during run time.
Any suggestions would be appreciated!
Thanks,
Ivar
The Issues
I believe Visual Studio generates code when you design the application settings and values, therefore at runtime this would not be easy and at worst impossible without a designer. However you can sometimes call upon design features at runtime.
You'll notice the code-behind has the properties in C# that you create in your designer. For example, I added a setting for:
Age [int] 30.
The code-behind has generated:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("30")]
public int Age {
get {
return ((int)(this["Age"]));
}
set {
this["Age"] = value;
}
}
(The code generation is why you have strongly-typed settings)
I'm unsure if you could effect this same thing at runtime. You would have to generate code and feed it back to the JIT compiler dynamically or something like that. Or maybe there's another way I don't know about in my limited understanding of settings.
Suggestion/Workaround
I'd suggest figuring out an alternate/easier way instead of jumping through hoops. For example, make one setting a collection type that is serializable so it can store multiple values.
Then you can, for example, store multiple ages under just one setting:
Ages [System.Collections.ArrayList] {add multiple values programatically}
You might end up with C# code to manage it like:
System.Collections.ArrayList list = new System.Collections.ArrayList();
list.Add("1");
list.Add("30");
Properties.Settings.Default.Ages = list;
Properties.Settings.Default.Save();

Winforms - Dynamic Load / Save Settings

I have a "settings file" in my Winforms application called Settings.settings with a partial class for custom methods, etc. Is there a way to load / save dynamic settings based on arbitrary keys?
For example, I have some ListViews in my application in which I want to save / load the column widths; Instead of creating a width setting for each column for each list view I would like a simple method to load / save the widths automatically.
Below is an example of the save method I have tried:
internal sealed partial class Settings
{
public void SetListViewColumnWidths(ListView listView)
{
String baseKey = listView.Name;
foreach (ColumnHeader h in listView.Columns)
{
String key = String.Format("{0}-{1}", baseKey, h.Index);
this[key] = h.Width;
}
}
}
When running that code I get the error "The settings property 'TestsListView-0' was not found." Is there something I am missing?
Store your column width settings in an Xml Serializable object. Ie, something that implements IXmlSerializable then create a single setting entry of that type in Settings.settings.
A good option would probably be an Xml Serializable Dictionary. A quick google search found quite a few different blog posts that describe how to implement that.
As mentioned in other answers you'll need to ensure that this object is a User setting. You may also need to initialize the setting instance. Ie, create a XmlSerializableDictionary() instance and assign it to the setting if the setting is null. The settings subsystem doesn't create default instances of complex setting objects.
Also, if you want these settings to persist between assembly versions (ie, be upgradable) you will need to upgrade the settings on application startup. This is described in detail on Miha Markič's blog and Raghavendra Prabhu's blog.
I think the error
The settings property
'key' was not found.
occurs because the 'key' value does not exist in your settings file (fairly self-explanatory).
As far as I am aware, you can't add settings values programmatically, you might need to investigate adding all of the settings you need to the file after all, although once they are there, I think you'll be able to use the sort of code you've given to save changes.
To Save changes, you'll need to make sure they are 'User' settings, not 'Application'.
The Settings file is quite simple XML, so you might be able to attack the problem by writing the XML directly to the file, but I've never done it, so can't be sure it would work, or necessarily recommend that approach.
http://msdn.microsoft.com/en-us/library/cftf714c.aspx is the MSDN link to start with.
You can do Settings.Save() or similar on user settings, but note that such settings would NOT get persisted to the xxx.exe.config file in your app directory as you'd expect. They actually go somewhere deep inside the user folder (search your drive for xxx.exe.config to find it). Next time that you manually change xxx.exe.config in your app directory, the change will mysteriously not apply (the system is still using the saved one from the user directory).

Best way to pass a large number of arguments into a configuration dialog

I've got a situation where I have a main form that pops up an advanced configuration form that just has half a dozen matched check boxes and combo boxes to select some advanced options (the check boxes to enable/disable, the combo to select a media if enabled).
If I just pass the individual settings for the check and combo boxes in to the constructor for the dialog that's obviously a dozen arguments, which seems a bit excessive.
My other obvious option would be since in the main form these settings are stored in a large IDictionary with all the other main form settings I could just pass this dictionary in and fetch it back afterward with the updated values, but my understanding is that this wouldn't really be very good coding practice.
Am I missing a good way to do this that is both efficient and good coding practice?
(this particular code is in C#, although I have a feeling a general solution would apply to other languages as well)
I personally would create a carrier object to store the values. You then get the nice intellisense for it, and changes to it would be quite straightforward. It would also be faster than dictionary lookups for parameter values. And of course, you get type safety. :)
You could go with Rob's solution; that's the prettiest for development. Your "carrier object" could contain the entire IDictionary and have typed properties to help intellisense. The properties could update the IDictionary. When you're done, you can pass the carrier object back and fetch the IDictionary directly from it.
For example, if your dictionary had key/value pair "FirstEnabled"/boolean, you could do this:
class ContainerObject
{
public IDictionary<object, object> _dict;
public ContainerObject(IDictionary<object, object> dict)
{
_dict = dict;
}
public bool FirstEnabled
{
get { return (bool) _dict["FirstEnabled"]; }
set { _dict["FirstEnabled"] = value; }
}
}
You can change the member "_dict" to private or protected and have a accessor function if you want.
Something like this should be good:
MyConfigurationDialog dialog = new MyConfigurationDialog();
//Copy the dictionary so that the dialog can't mess with our settings
dialog.Settings = new Dictionary(existingSettings);
if(DialogResult.OK == dialog.Show()) {
//grab the settings that the dialog may have changed
existingSettings["setting1"] = dialog.Settings["setting1"];
existingSettings["setting2"] = dialog.Settings["setting2"];
}
I agree with Rob Cooper. Create a class to represent your configuration, and pass that into the constructor of your form. This will also allow you to define methods on your new "config" class like "saveSettings", "LoadSettings", etc. That in turn should keep the code more maintainable in general.
As an quick-and-dirty alternative, if you are saving these to a file somewhere, just pass the name of the file, and have your form read that at run-time.
The first option really is the way to go though, IMO.

Categories

Resources