Code Monkey home page Code Monkey logo

settingsplugin's Introduction

Settings Plugin for Xamarin And Windows

Preferences/Settings are part of .NET MAUI, please use this API going foward.

Create and access settings from shared code across all of your apps!

Documentation

Get started by reading through the Settings Plugin documentation.

Looking to store credentials and sensitive information? Use Xamarin.Essential's Secure Storage

NuGet

I have been working on Plugins for Xamarin for a long time now. Through the years I have always wanted to create a single, optimized, and official package from the Xamarin team at Microsoft that could easily be consumed by any application. The time is now with Xamarin.Essentials, which offers over 50 cross-platform native APIs in a single optimized package. I worked on this new library with an amazing team of developers and I highly highly highly recommend you check it out.

I will continue to work and maintain my Plugins, but I do recommend you checkout Xamarin.Essentials to see if it is a great fit your app as it has been for all of mine!

Xamarin.Essentials Migration

This plugin and Xamarin.Essentials store information in the same exact location :). This means you can seemlessly swap out this plugin for Xamarin.Essentials and not lose any data. Checkout my blog for more info: https://montemagno.com/upgrading-from-plugins-to-xamarin-essentials/

Build:

Platform Support

Platform Version
Xamarin.iOS iOS 7+
Xamarin.Android API 15+
Windows 10 UWP 10+
Xamarin.Mac All
Xamarin.tvOS All
Xamarin.watchOS All
.NET Framework 4.5+
.NET 6.0+
Tizen 4.0+
.NET for iOS iOS 10+
.NET for Android API 21+
Windows App SDK (WinUI3) 10+
.NET for Mac Catalyst All
.NET for Mac All

Settings Plugin or Xamarin.Forms App.Properties

I get this question a lot, so here it is from a recent issue opened up. This plugin saves specific properties directly to each platforms native settings APIs (NSUserDefaults, SharedPreferences, etc). This ensures the fastest, most secure, and reliable creation and editing settings per application. Additionally, it works with any Xamarin application, not just Xamarin.Forms.

App.Current.Properties actually serializes and deserializes items to disk as you can see in the implementation.

To me that isn't as reliable as saving direct to the native platforms settings.

Contribution

Thanks you for your interest in contributing to Settings plugin! In this section we'll outline what you need to know about contributing and how to get started.

Bug Fixes

Please browse open issues, if you're looking to fix something, it's possible that someone already reported it. Additionally you select any up-for-grabs items

Pull requests

Please fill out the pull request template when you send one. Run tests to make sure your changes don't break any unit tests. Follow these instructions to run tests -

iOS

  • Navigate to tests/Plugin.Settings.NUnitTest.iOS
  • Execute make run-simulator-tests

Android

Execute ./build.sh --target RunDroidTests from the project root

License

The MIT License (MIT) see License file

Want To Support This Project?

All I have ever asked is to be active by submitting bugs, features, and sending those pull requests down! Want to go further? Make sure to subscribe to my weekly development podcast Merge Conflict, where I talk all about awesome Xamarin goodies and you can optionally support the show by becoming a supporter on Patreon.

settingsplugin's People

Contributors

akadooie avatar andreimisiukevich avatar azureadvocatebit avatar clancey avatar danmiser avatar froggiefrog avatar hartez avatar jamesmontemagno avatar manojkulkarni30 avatar mimunoz avatar prashantvc avatar sdebruyn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

settingsplugin's Issues

Implement FileName for specifying file/suite/container name.

Feature Request:

This feature would enable any developer to specify an additional parameter on each method in the Settings plugin to specify a name for the platform specific file. If it is null or empty string, then use default. This would fix #3 and #17.

iOS

File name would be used to specify the SuiteName:

 NSUserDefaults GetUserDefaults(string fileName = null) =>
            string.IsNullOrWhiteSpace(fileName) ?
            NSUserDefaults.StandardUserDefaults :
            new NSUserDefaults(fileName, NSUserDefaultsType.SuiteName);

Android

This would be used to specify the shared preference name instead of using the default shared preferences. The FileCreationMode will be set to private because all other ones have been deprecated at this point according to documentation.

Implementation:

    ISharedPreferences GetSharedPrefence(string fileName) =>
            string.IsNullOrWhiteSpace(fileName) ?
            PreferenceManager.GetDefaultSharedPreferences(Application.Context) :
            Application.Context.GetSharedPreferences(fileName, FileCreationMode.Private);

UWP and Win RT

These use ApplicationDataContainers. By default we use the root, but the LocalSettings can actually have buckets of additional containers. So we can attempt to create additional containers and return it if necessary:

ApplicationDataContainer GetAppSettings(string fileName = null)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                return ApplicationData.Current.LocalSettings;

            if (!ApplicationData.Current.LocalSettings.Containers.ContainsKey(fileName))
                ApplicationData.Current.LocalSettings.CreateContainer(fileName, ApplicationDataCreateDisposition.Always);

            return ApplicationData.Current.LocalSettings.Containers[fileName];
        }

.NET 4.5/WP Silverlight

These use isolated storage, so no implementation to be used.

Error occurred while trying to restore packages

I added this package to my portable project and it compiled fine but then I got a runtime error that said something about needing to reference the nuget package in the platform project (android in this case)

So I tried adding it to the android project, and now I get the following NuGet errors.
It appears that neither project can find the NuGet solution now?

Error NuGet Package restore failed for project PatrolLiveApp.Droid: NuGet.Protocol.Core.Types.FatalProtocolException: Unable to find version '2.5.1' of package 'Xam.Plugins.SettingsModel'.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package 'Xam.Plugins.SettingsModel.2.5.1' is not found on source 'C:\Program Files (x86)\Microsoft SDKs\NuGetPackages'.
https://api.nuget.org/v3/index.json: Package 'Xam.Plugins.SettingsModel.2.5.1' is not found on source 'https://api.nuget.org/v3/index.json'.
http://nugets.vapolia.fr/nuget/: Package 'Xam.Plugins.SettingsModel.2.5.1' is not found on source 'http://nugets.vapolia.fr/nuget/'.

Error NuGet Package restore failed for project PatrolLiveApp: NuGet.Protocol.Core.Types.FatalProtocolException: Unable to find version '2.5.1' of package 'Xam.Plugins.SettingsModel'.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package 'Xam.Plugins.SettingsModel.2.5.1' is not found on source 'C:\Program Files (x86)\Microsoft SDKs\NuGetPackages'.
https://api.nuget.org/v3/index.json: Package 'Xam.Plugins.SettingsModel.2.5.1' is not found on source 'https://api.nuget.org/v3/index.json'.
http://nugets.vapolia.fr/nuget/: Package 'Xam.Plugins.SettingsModel.2.5.1' is not found on source 'http://nugets.vapolia.fr/nuget/'.

Bug

Version Number of Plugin: 2.5.1
Device Tested On: Visual Studio 2015

Q: How long will settings persist?

Lovely plugin, James! Quick question: Will those settings survive a new install through the app store? I'd use it to store the current user token and volatile data that I would purge myself on logout, but don't want to be lost on app updates.

Settings and List of values

From @Goldstrike on June 4, 2016 12:37

Please take a moment to fill out the following (change to preview to check or place x in []) and remove all unused areas

This is a

  • Feature Request

Which plugin does this impact:

  • Settings

Hello,

I would like to know if there is a way to use the Settings to store Data Types like List<KeyValuePair<string, string>>.

I know that this type is not in supported basically, but I'm looking for a way to store some cookies, that will be returned by a WebService, through the Settings. The number and the names of the cookies could change, so I wouldn't store them as individual values.

Is there a way to manage this?

Copied from original issue: jamesmontemagno/Xamarin.Plugins#322

2.5.2.1 Android Double

Please fill out either the bug or feature request section and remove whatever section you are not using.

Bug

2.5.2.1 Android Double

double x = 1.5;
Settings.FontFactor = x;
var y = Settings.FontFactor; (returns 15, not 1,5)

Remove app but Settings are remaining

Settings are remaining after an app is deleted

Version Number of Plugin: 2.5.1.0
Device Tested On: iPad Pro

Expected Behavior

If I cancel an app, all settings are deleted

Actual Behavior

If I cancel an app and I reinstall it, I have all my old settings.
For example I save in settings, if an app is started for the first time. If yes I create some demo data.

Steps to reproduce the Behavior

Delete and app and reinstall it.

Android getSharedPreferences file name and mode

I saw that it's not possible to get the sharedPreference with a specified file name. The only way is to use the DefaultSharedPreferences.

It's a possibility for you to add this function? :
Context.getSharedPreferences (String name, int mode)

Thanks in advance

Settings.bundle on iOS sample

Please fill out either the bug or feature request section and remove whatever section you are not using.

Bug

Version Number of Plugin:
Device Tested On: iOS
Simulator Tested On:

Expected Behavior

Read/write to Settings.bundle/Root.plist, edit from iOS Settings app

Actual Behavior

Settings are not displayed in iOS Settings app

Steps to reproduce the Behavior

Feature Request:

Is this designed to work with Settings.bundle/Root.plist in iOS? If so, can you provide and example?

System.NullReferenceException: Object reference not set to an instance of an object.

I have this model:

public class User {
    public string Name;
}

And the settings are:

private const string LoggedUserKey = "loggeduser_key";
private static readonly User LoggedUserDefault = null; // I also tried new User();

public static User LoggedUser {
    get { return AppSettings.GetValueOrDefault<User>(LoggedUserKey, LoggedUserDefault); }
    set { AppSettings.AddOrUpdateValue<User>(LoggedUserKey, value); }
}

In the constructor of my MainPageViewModel, I have this:

if (Settings.LoggedUser != null) {
    Debug.WriteLine("User is not null");
}

But I got this error:
System.NullReferenceException: Object reference not set to an instance of an object.

How to store setting is an Object?

I have an Object HUMAN: EyesColor, HairColor, Name, Tall
How to store setting is HUMAN Object or I must create one by one properties of HUMAN?

System.NotImplemented

I get this error when attempting to modify my Settings.cs
System.NotImplementedException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

I followed the instructions by adding the nuget package to my portable project. What then does error indicate?

Method 'Plugin.Settings.Abstractions.ISettings.GetValueOrDefault' not found.

I am using Xamarin.Forms 2.3.3.175. On iOS it works perfectly, yet on Android I get this message directly, without even seeing ui elements in my app.

public static string GeneralSettings
		{
			get
			{
				return AppSettings.GetValueOrDefault<string>(SettingsKey, SettingsDefault);
			}
			set
			{
				AppSettings.AddOrUpdateValue<string>(SettingsKey, value);
			}
		}

Bug

Version Number of Plugin:2.5.1.0
Device Tested On:
Simulator Tested On: Accelerated x86 (default Visual Studio for Mac)

Expected Behavior

I can get a value from settings.

Actual Behavior

Before even accessing the string, I get "Method 'Plugin.Settings.Abstractions.ISettings.GetValueOrDefault' not found."

Steps to reproduce the Behavior

Install the plugin in the PCL and Android. I run it, and get this error.

Settings: AddOrUpdateValue<string>("key", null) adds an entry with empty string as the value, on Android.

From @dvshub on April 16, 2016 5:54

Please take a moment to fill out the following (change to preview to check or place x in []):

This is a

  • Bug
  • Feature Request

Which plugin does this impact:

  • Battery
  • Connectivity
  • Contacts
  • DeviceInfo
  • ExternalMaps
  • Geolocator
  • Media
  • Permissions
  • Settings
  • Text To Speech
  • Vibrate
  • Other:

Version Number of Plugin: 2.1.0
Device Tested On: Nexus 6P, Android version 6.0.1
Simulator Tested On: iPhone 6s, iOS version 9.2

Actual Behavior

On iOS: AddOrUpdateValue("key", null) throws ArgumentNullException. This is the same behavior as iOS's native NSUserDefaults.

On Android: AddOrUpdateValue("key", null) adds/updates the "key" with empty string as the value. This is different from the iOS behavior of this library, and also different from Android's native SharedPreferences behavior which actually removes the key if it was already present, or doesn't do anything otherwise.

Expected Behavior

To keep the behavior of the library consistent for all platforms, it should throw ArgumentNullException in this case. This will ensure that the application code relying on this library behaves the same way across all platforms. That is the whole purpose of using a cross-platform library in the first place.

Steps to reproduce the Behavior

Call Settings.AddOrUpdateValue("key", null);

This is related to jamesmontemagno/Xamarin.Plugins#195 as the root cause of both is same.

Copied from original issue: jamesmontemagno/Xamarin.Plugins#285

Missing String Name(s)

Bug

Version Number of Plugin: 2.1
Device Tested On: Portable (Win)

Expected Behavior

Abstraction.dll and Settings.dll with strong names

Actual Behavior

No strong names. Our projects require strong names, so all references DLLs.

[Feature Request] Settings plugin - Secure storage for sensitive data (passwords, etc)

From @daniel-luberda on September 7, 2015 15:24

It would be very nice to have secure settings storing functionality for things like passwords, session tokens, etc implemented with platform specific API's ensuring security. It could be done just the same as Xamarin.Auth plugin account storing (backed by the Keychain on iOS and a KeyStore on Android). What do You think about it?

Copied from original issue: jamesmontemagno/Xamarin.Plugins#106

Calling AddOrUpdateValue with a string throws "Value of type String is not supported"

Calling AddOrUpdateValue with string type throws exception Value of type String is not supported.
Here's how this is possible:

object strValue = "a";

CrossSettings.Current.AddOrUpdateValue(key, strValue);

This is because the implementation is using Type.GetTypeCode to get the primitive type, but this returns System.TypeCode.Object, and not System.TypeCode.String as you could expect.

https://github.com/jamesmontemagno/SettingsPlugin/blob/master/src/Plugin.Settings.Android/Settings.cs#L207

Same issue is on iOS, it's very similar code.

As a solution, maybe use Convert.GetTypeCode which correctly returns TypeCode.String?

DateTime property Always fallback to UTC

Bug

Version Number of Plugin: 2.5.1
Device Tested On: Samsung Tab S2

If i create a property with type DateTime Always fallback to UTC even if it has a default value like this

 private const string ExpireTokenDateKey = "expiretokendate_key";
private static readonly DateTime ExpireTokenDateDefault = new DateTime(1980,10,19,12,12,12, DateTimeKind.Local);

Then if i do
Settings.ExpireTokenDate = DateTime.Now.AddSeconds(_authenticationResult.ExpiresIn);
Settings.ExpireTokenDate is in UTC

System.NotImplementedException

Please fill out either the bug or feature request section and remove whatever section you are not using.

Bug

Version Number of Plugin: 2.1.0
Device Tested On:
Simulator Tested On: Android emulator in Visual Studio

Code is breaking when trying to set a value. The error returned is...

System.NotImplementedException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

This breaks at the following point:

return CrossSettings.Current;

The NuGet package is installed in the project at the PCL solution level and also on both Droid and iOS.

-Dave

Make Settings.cs partial class?

Feature Request:

It's quite annoying to keep changing the default template Settings class to a partial class whenever I update the plugin, as I've another Settings class of the same root namespace, located in another folder.

Is it possible to change the default definition of the Settings class to be a partial class?

IOS 10 failure

Failed to run on IOS10, throw out a null exception. But the uwp and android still works fine. :)

Settings - Possibility of using alternative NSUserDefaults in iOS

From @Markusian on May 19, 2016 12:53

Please take a moment to fill out the following (change to preview to check or place x in []):

This is a

  • Bug
  • Feature Request

Which plugin does this impact:

  • Battery
  • Connectivity
  • Contacts
  • DeviceInfo
  • ExternalMaps
  • Geolocator
  • Media
  • Permissions
  • Settings
  • Text To Speech
  • Vibrate
  • Other

Version Number of Plugin: 2.1.0
Device Tested On: iPhone 6.0

Expected Behavior

The settings plugin uses the NSUserDefaults.StandardUserDefaults as default, not allowing to define any other NSUserDefaults database to store the objects. This is useful, for example, in the case in which an app group is used, and it is necessary to have shared settings between the container app and the extensions / other apps in the group.

Copied from original issue: jamesmontemagno/Xamarin.Plugins#309

Binding with PRISM Framework

With Prism Framework, I create a binding property like this:

private static User _loggedUser;
public User LoggedUser {
    get { return _loggedUser; }
    set { SetProperty(ref _loggedUser, value); }
}

How would I get the Settings.LoggedUser value and pass to that binding property?
What's the best way to work in this case?

Support for .NETStandard?

Feature Request:

Ist it possible to support .NetStandard? It is written everywhere to use .NetStandard instead of PCLs, but this plugin is not compatible (yet).

Package Manager console:
Package Xam.Plugins.Settings 2.5.1 is not compatible with netstandard1.4 (.NETStandard,Version=v1.4). Package Xam.Plugins.Settings 2.5.1 supports:

  • monoandroid10 (MonoAndroid,Version=v1.0)
  • net45 (.NETFramework,Version=v4.5)
  • portable-net45+win8+wp8+wpa81 (.NETPortable,Version=v0.0,Profile=Profile259)
  • uap10 (UAP,Version=v1.0)
  • win8 (Windows,Version=v8.0)
  • wp8 (WindowsPhone,Version=v8.0)
  • wpa81 (WindowsPhoneApp,Version=v8.1)
  • xamarinios10 (Xamarin.iOS,Version=v1.0)
    One or more packages are incompatible with .NETStandard,Version=v1.4.

See: https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/ (section: As a library author, what should I do now?)

Storing reference objects

@jamesmontemagno or anyone else who might have tried the following:

Is it possible to store my custom objects through the settings plugin?

EDIT: Sorry, just noticed the supported data types

[Feature request] Remove all method

From @oansquer on February 1, 2016 8:46

Hello,

Can you add a method to remove all settings ?
In my app, I have a reset command and I want to be sure to remove all settings values.
On Android, I do it with;

ISharedPreferencesEditor edit = Preferences.Edit();
edit.Clear();
edit.Commit();

On UWP:

ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
foreach (string key in settings.Values.Select((p) => p.Key).ToList())
{
settings.Values.Remove(key);
}

Thanks,

Olivier

Copied from original issue: jamesmontemagno/Xamarin.Plugins#204

Color problem

In other my project this is working fine. FYI in this project I added a Acr.Geofences library.

Bug

Version Number of Plugin: 2.5.2.1
Device Tested On: Android 6
Simulator Tested On: Android 6

Expected Behavior

Return a Color or ColorDefault

private const string BoxColorWorkKey = "BoxColorWork_key";
private static readonly Color BoxColorWorkDefault = Color.FromHex("#65A4BE");
public static Color BoxColorWorkSettings
{
    get
    {
        return AppSettings.GetValueOrDefault<Color>(BoxColorWorkKey, BoxColorWorkDefault);
    }
    set
    {
    AppSettings.AddOrUpdateValue<Color>(BoxColorWorkKey, value);
    }
}

Actual Behavior

Exception

at Plugin.Settings.SettingsImplementation.GetValueOrDefaultCore[T] (Android.Content.ISharedPreferences sharedPreferences, System.String key, T defaultValue) [0x00331] in <1055e94092394c9a94e7dbe657c5f555>:0
at Plugin.Settings.SettingsImplementation.GetValueOrDefault[T] (System.String key, T defaultValue) [0x0001c] in <1055e94092394c9a94e7dbe657c5f555>:0
at HandyApp.Helpers.Settings.get_BoxColorWorkSettings () [0x00010] in /Users/enricorossini/Projects/HandyApp/HandyApp/HandyApp/HandyApp/Helpers/Settings.cs:91
at HandyApp.ViewModels.AppointmentListViewModel+c__async0.MoveNext () [0x00154] in /Users/enricorossini/Projects/HandyApp/HandyApp/HandyApp/HandyApp/ViewModels/AppointmentListViewModel.cs:44
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.m__0 (System.Object state) [0x00000] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1018
at Android.App.SyncContext+c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/3511/501e63ce/source/xamarin-android/src/Mono.Android/Android.App/SyncContext.cs:18
at Java.Lang.Thread+RunnableImplementor.Run () [0x0000b] in /Users/builder/data/lanes/3511/501e63ce/source/xamarin-android/src/Mono.Android/Java.Lang/Thread.cs:36
at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in /Users/builder/data/lanes/3511/501e63ce/source/monodroid/src/Mono.Android/platforms/android-24/src/generated/Java.Lang.IRunnable.cs:81
at (wrapper dynamic-method) System.Object:ec7cfaa4-bbaf-45f5-baea-e4a9c61b10f1 (intptr,intptr)

Would be nice to have a clear all settings method in CrossSettings

From @bmmathe on April 8, 2016 18:4

Please take a moment to fill out the following (change to preview to check or place x in []):

This is a

  • Bug
  • [x ] Feature Request

Which plugin does this impact:

  • Battery
  • Connectivity
  • Contacts
  • DeviceInfo
  • ExternalMaps
  • Geolocator
  • Media
  • Permissions
  • [x ] Settings
  • Text To Speech
  • Vibrate
  • Other:

Version Number of Plugin: 2.1.0

For debugging purposes it would be nice to have a way to clear all settings in the CrossSettings.Current object. It would also be helpful in a "Delete Profile" scenario.

Copied from original issue: jamesmontemagno/Xamarin.Plugins#274

Settings: AddOrUpdateValue always returns true (Android)

Bug

Version Number of Plugin: 2.1.0
Device Tested On:
Simulator Tested On: Nexus 4 (KitKat)

Expected Behavior

Should only return true if the setting value was added or was actually different than the previous value

Actual Behavior

Always returns true

Steps to reproduce the Behavior

update a settings value that already exists and observe the return value of AddOrUpdate.

Android lose settings

Version Number of Plugin: 2.5.1.0 and pre
Device Tested On: Nexus s , nexus 5 , nexus 7 and other non google device.

In Android frequently but randomly settings losses.
To try to reproduce the bug you can rebuild but it happens also with a normal build signed and not .

Settings: Storing and retrieving double.MaxValue throws OverflowException (doubles can also lose precision)

From @dvshub on April 16, 2016 6:17

Please take a moment to fill out the following (change to preview to check or place x in []):

This is a

  • Bug
  • Feature Request

Which plugin does this impact:

  • Battery
  • Connectivity
  • Contacts
  • DeviceInfo
  • ExternalMaps
  • Geolocator
  • Media
  • Permissions
  • Settings
  • Text To Speech
  • Vibrate
  • Other:

Version Number of Plugin: 2.1.0
Device Tested On: Nexus 6P, Android version 6.0.1
Simulator Tested On: iPhone 6s, iOS version 9.2

Expected Behavior

If I store the value double.MaxValue and later retrieve it, I should get the same value back.

Actual Behavior

  1. double.MaxValue is stored without issues, but while retrieving the value, it throws OverflowException.
  2. If I store 0.12345678901234567, when I retrieve it, I get 0.123456789012346, so I lose precision and what I get is not what I set.

Steps to reproduce the Behavior

Settings.AddOrUpdateValue("key", double.MaxValue);
double d = Settings.GetValueOrDefault("key", 0.0D); // throws OverflowException

This is an issue not just with double.MaxValue but with any number that needs more than 15 digits for representation. This is actually because of the way doubles are converted to strings in .Net (since that is what the Settings library does when storing double values). When converting the number to string, the value will be rounded off to 15 digits if it needs more than 15 digits for representation.
E.g., if the original number is 0.12345678901234567, converting it to string results in "0.123456789012346", and converting it back to double results in 0.123456789012346, which is not what you started with.

Consider the following C# .Net code.
double originalDouble = double.MaxValue;
string doubleAsString = Convert.ToString(originalDouble, System.Globalization.CultureInfo.InvariantCulture);
double roundtripDouble = Convert.ToDouble(doubleAsString, System.Globalization.CultureInfo.InvariantCulture);
// this last conversion throws Overflow exception

This issue can be overcome by using format specifiers “R” and “G17”.
More info at
https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
“In some cases, Double values formatted with the "R" standard numeric format string do not successfully round-trip if compiled using the /platform:x64 or /platform:anycpu switches and run on 64-bit systems. To work around this problem, you can format Double values by using the "G17" standard numeric format string. "
https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#RFormatString

Also discussed at http://stackoverflow.com/questions/766918/convert-1-79769313486232e308-to-double-without-overflowexception

Copied from original issue: jamesmontemagno/Xamarin.Plugins#286

Comparison to Xamarin.Forms.Application.Properties

How does this package compare to the functionality in Xamarin.Forms.Application.Properties?

Some write-up in the readme would be helpful, since the readme implies this package is useful with Xamarin Forms, and yet there seems to be considerable overlap between this package and what's build into Xamarin Forms.

Add roaming settings for UWP (and WinRT)

Feature Request:

I really would like roaming settings that come with UWP/WinRT apps. In addition to using ApplicationData.Current.LocalSettings, also allow ApplicationData.Current.RoamingSettings.

In fact, I've already implemented it in a forked project: https://github.com/limefrogyank/SettingsPlugin

I didn't want to break any of your current code, so I simply wrote a second file in the WP81 project called RoamingSettings.cs where I changed only LocalSettings to RoamingSettings. (Then linked it to UWP)

I modified CrossSettings's CreateSettings method to accept an enum for Local or Roaming with a default of Local.

I then modified CrossSettings to add a second property called CurrentRoaming that gets a second Lazy reference to an ISettings type called roamingSettings. This version is instantiated with CreateSettings(SettingsType.Roaming)

It seems to work fine on my end. The preprocessor symbols in the IF THEN statements need to be updated to include the other WinRT projects... I'm only using UWP so I didn't care.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.