How to avoid application settings corruption when a background agent is used

LIke most of my applications, I used to save all my application settings in the IsolatedStorageSettings.ApplicationSettings. It seems like a logical good choice. In my last application, I added a Background Agent to my project. When I was looking for best practices on how to exchange settings between the background agent and my application, I came across with this text from the MSDN library:

For Periodic and Resource-intensive Agents: Use LINQ 2 SQL or a file in isolated storage that is guarded with a Mutex. For one-direction communication where the foreground app writes and the agent only reads, we recommend using an isolated storage file with a Mutex. We recommend that you do not use IsolatedStorageSettings to communicate between processes because it is possible for the data to become corrupt.

After, I found someone who implemented a solution that uses a Mutex. While the solution is good, the only problem is that his personal settings are mixed with the IsolatedStorage operations.

To help the reuse of the solution in different projects, I created a IsolatedStorageHelper class. Also, instead of relying on the XmlSerializer in order to save an object, I based my solution using the powerful library of Json.NET.

Usage

The IsolatedStorageHelper has three methods:

  • WriteObjectToFileUsingJson
  • ReadObjectFromFileUsingJson
  • IsFileExists

Here is the example that uses all the methods:

Settings mySettings = new Settings();

IsolatedStorageHelper.WriteObjectToFileUsingJson("Settings.txt", mySettings, "MyMutexName");

if (IsolatedStorageHelper.IsFileExist(SettingsFileName))
{
    Settings = IsolatedStorageHelper.ReadObjectFromFileUsingJson<Settings>("Settings.txt", "MyMutexName");
}

To use the IsolatedStorageHelper in your project:

1- Add the IsolatedStorageHelper.cs file into your project.

2- Add the Nuget package Json.net.

If your project does not have a background agent, you can still use my utility class, you can omit the mutexName parameter of the WriteObjectoToFileUsingJson and ReadObjectFromFileUsingJson.


Download