Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Phone- How to set LocalSettings first time?

In Desktop Application or Web Projects projects there were App.configs and Web.configs files to store settings. These settings were set in development time (or whenever later) but if this occures, it was ALWAYS once action.

In Windows Phone 8.1 XAML there isn't any App.config file, so developers are able to use Windows.Storage.ApplicationData.Current.LocalSettings. Nice.

How can I set these settings first time (this means on first application run ever, so I can later only read them and sometimes update existing values)? Of course I can set settings whenever I run application but this is time wasting. How do you set LocalSettings in you applications first time? I saw this solution Is there a "first run" flag in WP7 but I don't think so, that this is the only possibility.

like image 202
Fka Avatar asked Nov 07 '14 10:11

Fka


2 Answers

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

// Create a simple setting

localSettings.Values["exampleSetting"] = "Hello Windows";

// Read data from a simple setting

Object value = localSettings.Values["exampleSetting"];

if (value == null)
{
    // No data
}
else
{
    // Access data in value
}

// Delete a simple setting

localSettings.Values.Remove("exampleSetting");

Msdn Reference

Persistance of Data

like image 113
Eldho Avatar answered Oct 15 '22 05:10

Eldho


I have written code:

    public void Initialize()
    {
        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

        if (!localSettings.Values.ContainsKey(FirstRunSettingName))
        {
            localSettings.Values.Add(FirstRunSettingName, false);
        }

        localSettings.Values.Add(SettingNames.DataFilename, "todo.data.xml");
    }

    public bool IsFirstRun()
    {
        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

        if (localSettings.Values.ContainsKey(FirstRunSettingName))
        {
            return (bool)localSettings.Values[FirstRunSettingName];
        }
        else
        {
            return true;
        }
    }

In the App.xaml.cs file:

    public App()
    {
        this.InitializeComponent();
        this.Suspending += this.OnSuspending;

        var storageService = Container.Get<ISettingsService>();

        if (storageService.IsFirstRun())
        {
            storageService.Initialize();
        }
    }

I'm not sure this is proper way to set settings first time, but it is some soultion.

like image 21
Fka Avatar answered Oct 15 '22 06:10

Fka