├── .github
├── FUNDING.yml
└── workflows
│ └── release.yml
├── .gitignore
├── Avalonia.Preferences.Android
├── Avalonia.Preferences.Android.csproj
└── Storage
│ └── AndroidPreferencesStorage.cs
├── Avalonia.Preferences.sln
├── Avalonia.Preferences
├── AsyncHelper.cs
├── Avalonia.Preferences.csproj
├── IPreferences.cs
├── Preferences.cs
└── Storage
│ ├── AbstractPreferencesStorage.cs
│ └── GenericPreferencesStorage.cs
├── LICENSE
├── README.md
├── global.json
├── release.sh
└── unrelease.sh
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: sandreas
2 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 | on:
3 | push:
4 | tags:
5 | - "v[0-9]+.[0-9]+.[0-9]+"
6 | env:
7 | GITHUB_USER: 'sandreas'
8 | PROJECT_NAME: 'Avalonia.Preferences'
9 | PACKAGE_ID: 'Sandreas.Avalonia.Preferences'
10 | PROJECT_PATH: 'Avalonia.Preferences/Avalonia.Preferences.csproj'
11 | DOTNET_VERSION: '6.0.401'
12 | jobs:
13 | build:
14 | runs-on: ubuntu-latest
15 | timeout-minutes: 15
16 | steps:
17 | - name: Checkout
18 | uses: actions/checkout@v2
19 |
20 | - name: Setup dotnet
21 | uses: actions/setup-dotnet@v1
22 | with:
23 | dotnet-version: ${{ env.DOTNET_VERSION }}
24 |
25 | #- name: Install workloads
26 | # run: |
27 | # dotnet workload install android --ignore-failed-sources
28 |
29 | - name: Get version
30 | id: version
31 | uses: battila7/get-version-action@v2
32 |
33 | - name: Build
34 | run: dotnet build Avalonia.Preferences --configuration Release /p:Version=${{ steps.version.outputs.version-without-v }}
35 |
36 | # - name: Test
37 | # run: dotnet test --configuration Release /p:Version=${{ steps.version.outputs.version-without-v }} --no-build
38 |
39 | - name: Pack
40 | run: dotnet pack Avalonia.Preferences --configuration Release --include-symbols /p:Version=${{ steps.version.outputs.version-without-v }} --no-build --output .
41 |
42 | - name: Push
43 | run: |
44 | dotnet nuget push ${{ env.PACKAGE_ID }}.${{ steps.version.outputs.version-without-v }}.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{secrets.NUGET_API_KEY}}
45 | env:
46 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
47 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | */obj/
3 | */bin/
4 |
5 |
--------------------------------------------------------------------------------
/Avalonia.Preferences.Android/Avalonia.Preferences.Android.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0-android
5 | enable
6 | enable
7 | 21
8 | 21
9 | true
10 | true
11 | portable
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Avalonia.Preferences.Android/Storage/AndroidPreferencesStorage.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Preferences.Storage;
2 |
3 | namespace Avalonia.Preferences.Android.Storage;
4 | /*
5 | // https://github.com/jamesmontemagno/SettingsPlugin/blob/master/src/Plugin.Settings/Settings.android.cs
6 | public class AndroidPreferencesStorage : AbstractPreferencesStorage
7 | {
8 | private readonly ISharedPreferences _sharedPreferences;
9 |
10 | public AndroidPreferencesStorage(Context appContext)
11 | {
12 | _sharedPreferences = appContext.GetSharedPreferences(
13 | appContext.PackageName , FileCreationMode.Private)!;
14 | }
15 |
16 | public override bool SetSerialized(string key, string value)
17 | {
18 | using var editor = _sharedPreferences.Edit();
19 | if (editor == null)
20 | {
21 | return false;
22 | }
23 | editor.PutString(key, Convert.ToString(value, CultureInfo.InvariantCulture));
24 | return true;
25 | }
26 |
27 | public override string GetSerialized(string key) => _sharedPreferences.GetString(key, "") ?? "";
28 |
29 |
30 | public override bool Remove(string key)
31 | {
32 | using var editor = _sharedPreferences.Edit();
33 | if (editor == null)
34 | {
35 | return false;
36 | }
37 | editor.Remove(key);
38 | return true;
39 | }
40 |
41 | public override int Clear()
42 | {
43 | var count = _sharedPreferences.All?.Count ?? 0;
44 | using var editor = _sharedPreferences.Edit();
45 | if (editor == null)
46 | {
47 | return -1;
48 | }
49 |
50 | editor.Clear();
51 | editor.Commit();
52 | return count;
53 | }
54 |
55 | public override bool ContainsKey(string key) => _sharedPreferences.Contains(key);
56 | }
57 | */
--------------------------------------------------------------------------------
/Avalonia.Preferences.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Avalonia.Preferences", "Avalonia.Preferences\Avalonia.Preferences.csproj", "{E1B47020-2ED6-4854-8A47-48A8A20BA57E}"
4 | EndProject
5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Avalonia.Preferences.Android", "Avalonia.Preferences.Android\Avalonia.Preferences.Android.csproj", "{AD77CE3B-2766-47D8-BFCC-C711CB82197C}"
6 | EndProject
7 | Global
8 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
9 | Debug|Any CPU = Debug|Any CPU
10 | Release|Any CPU = Release|Any CPU
11 | EndGlobalSection
12 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
13 | {E1B47020-2ED6-4854-8A47-48A8A20BA57E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
14 | {E1B47020-2ED6-4854-8A47-48A8A20BA57E}.Debug|Any CPU.Build.0 = Debug|Any CPU
15 | {E1B47020-2ED6-4854-8A47-48A8A20BA57E}.Release|Any CPU.ActiveCfg = Release|Any CPU
16 | {E1B47020-2ED6-4854-8A47-48A8A20BA57E}.Release|Any CPU.Build.0 = Release|Any CPU
17 | {AD77CE3B-2766-47D8-BFCC-C711CB82197C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
18 | {AD77CE3B-2766-47D8-BFCC-C711CB82197C}.Debug|Any CPU.Build.0 = Debug|Any CPU
19 | {AD77CE3B-2766-47D8-BFCC-C711CB82197C}.Release|Any CPU.ActiveCfg = Release|Any CPU
20 | {AD77CE3B-2766-47D8-BFCC-C711CB82197C}.Release|Any CPU.Build.0 = Release|Any CPU
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/Avalonia.Preferences/AsyncHelper.cs:
--------------------------------------------------------------------------------
1 | namespace Avalonia.Preferences;
2 |
3 | internal static class AsyncHelper
4 | {
5 | private static readonly TaskFactory Factory = new(CancellationToken.None,
6 | TaskCreationOptions.None,
7 | TaskContinuationOptions.None,
8 | TaskScheduler.Default);
9 |
10 | public static TResult RunSync( Func> func)
11 | {
12 | return Factory
13 | .StartNew(func)
14 | .Unwrap()
15 | .GetAwaiter()
16 | .GetResult();
17 | }
18 |
19 | public static void RunSync( Func func)
20 | {
21 | Factory
22 | .StartNew(func)
23 | .Unwrap()
24 | .GetAwaiter()
25 | .GetResult();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Avalonia.Preferences/Avalonia.Preferences.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 | Sandreas.Avalonia.Preferences
8 | sandreas
9 | snupkg
10 | https://github.com/sandreas/Avalonia.Preferences.git
11 | https://github.com/sandreas/Avalonia.Preferences.git
12 | avalonia;preferences;settings;user settings
13 |
14 | Cross platform user preferences for avalonia
15 |
16 | Avalonia.Preferences
17 | README.md
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Avalonia.Preferences/IPreferences.cs:
--------------------------------------------------------------------------------
1 | namespace Avalonia.Preferences;
2 |
3 | public interface IPreferences
4 | {
5 | public bool Set(string key, T? value);
6 |
7 | public T? Get(string key, T? defaultValue);
8 |
9 | public bool Remove(string key);
10 | public int Clear();
11 | public bool ContainsKey(string key);
12 |
13 | public Task SetAsync(string key, T? value, CancellationToken? ct = null);
14 |
15 | public Task GetAsync(string key, T? defaultValue, CancellationToken? ct = null);
16 |
17 | public Task RemoveAsync(string key, CancellationToken? ct = null);
18 | public Task ClearAsync(CancellationToken? ct = null);
19 | }
--------------------------------------------------------------------------------
/Avalonia.Preferences/Preferences.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Preferences.Storage;
2 |
3 | namespace Avalonia.Preferences;
4 |
5 | public class Preferences : IPreferences
6 | {
7 | public static IPreferences? PlatformStorage { get; set; }
8 | private readonly IPreferences _storage;
9 |
10 | public Preferences(IPreferences? storage = null)
11 | {
12 | _storage = PlatformStorage ?? storage ?? new GenericPreferencesStorage();
13 | }
14 |
15 |
16 | public bool Set(string key, T? value) => _storage.Set(key, value);
17 |
18 |
19 | public T? Get(string key, T? defaultValue) => _storage.Get(key, defaultValue);
20 |
21 | public bool Remove(string key) => _storage.Remove(key);
22 |
23 | public int Clear() => _storage.Clear();
24 |
25 | public bool ContainsKey(string key) => _storage.ContainsKey(key);
26 |
27 | public async Task SetAsync(string key, T? value, CancellationToken? ct = null) =>
28 | await _storage.SetAsync(key, value, ct);
29 |
30 | public async Task GetAsync(string key, T? defaultValue, CancellationToken? ct = null) =>
31 | await _storage.GetAsync(key, defaultValue, ct);
32 |
33 | public async Task RemoveAsync(string key, CancellationToken? ct = null) =>
34 | await _storage.RemoveAsync(key, ct);
35 |
36 | public async Task ClearAsync(CancellationToken? ct = null) => await _storage.ClearAsync(ct);
37 | }
--------------------------------------------------------------------------------
/Avalonia.Preferences/Storage/AbstractPreferencesStorage.cs:
--------------------------------------------------------------------------------
1 | namespace Avalonia.Preferences.Storage;
2 |
3 | public abstract class AbstractPreferencesStorage: IPreferences
4 | {
5 | protected static bool HasTokenBeenCancelled(CancellationToken? ct)
6 | {
7 | if (ct == null)
8 | {
9 | return false;
10 | }
11 |
12 | return ct.Value.CanBeCanceled && ct.Value.IsCancellationRequested;
13 | }
14 |
15 | public bool Set(string key, T? value) => AsyncHelper.RunSync(() => SetAsync(key, value));
16 | public async Task SetAsync(string key, T? value, CancellationToken? ct = null) => await TryPersistAsync(key, value, ct??CancellationToken.None);
17 | public T? Get(string key, T? defaultValue) => AsyncHelper.RunSync(() => GetAsync(key, defaultValue));
18 | public async Task GetAsync(string key, T? defaultValue, CancellationToken? ct = null) =>
19 | !ContainsKey(key) ? defaultValue : await LoadAsync(key, ct ?? CancellationToken.None);
20 | public abstract Task RemoveAsync(string key, CancellationToken? ct = null);
21 | public abstract Task ClearAsync(CancellationToken? ct = null);
22 |
23 | public bool Remove(string key) => AsyncHelper.RunSync(() => RemoveAsync(key));
24 | public int Clear() => AsyncHelper.RunSync(() => ClearAsync());
25 | public abstract bool ContainsKey(string key);
26 |
27 | public abstract Task TryPersistAsync(string key, T value, CancellationToken ct);
28 | public abstract Task LoadAsync(string key, CancellationToken ct);
29 |
30 | }
--------------------------------------------------------------------------------
/Avalonia.Preferences/Storage/GenericPreferencesStorage.cs:
--------------------------------------------------------------------------------
1 | using System.IO.IsolatedStorage;
2 | using System.Text.Json;
3 |
4 | namespace Avalonia.Preferences.Storage;
5 |
6 | // https://github.com/jamesmontemagno/SettingsPlugin/blob/master/src/Plugin.Settings/Settings.dotnet.cs
7 | public class GenericPreferencesStorage : AbstractPreferencesStorage
8 | {
9 | private static IsolatedStorageFile Store => IsolatedStorageFile.GetUserStoreForDomain();
10 | private static readonly SemaphoreSlim Sema = new(1, 1);
11 |
12 | public override bool ContainsKey(string key) => Store.FileExists(key);
13 |
14 | public override async Task RemoveAsync(string key, CancellationToken? ct = null)
15 | {
16 | await Sema.WaitAsync(ct ?? CancellationToken.None);
17 | try
18 | {
19 | if (!ContainsKey(key) || HasTokenBeenCancelled(ct)) return false;
20 | Store.DeleteFile(key);
21 | return true;
22 | }
23 | finally
24 | {
25 | Sema.Release();
26 | }
27 | }
28 |
29 | public override async Task ClearAsync(CancellationToken? ct = null)
30 | {
31 | await Sema.WaitAsync(ct ?? CancellationToken.None);
32 | try
33 | {
34 | var fileNames = Store.GetFileNames();
35 | foreach (var file in fileNames)
36 | {
37 | if (HasTokenBeenCancelled(ct))
38 | {
39 | return -1;
40 | }
41 | Store.DeleteFile(file);
42 | }
43 |
44 | return fileNames.Length;
45 | }
46 | catch (Exception)
47 | {
48 | return -1;
49 | }
50 | finally
51 | {
52 | Sema.Release();
53 | }
54 | }
55 |
56 | public override async Task TryPersistAsync(string key, T value, CancellationToken ct)
57 | {
58 | await Sema.WaitAsync(ct);
59 | try
60 | {
61 | await using var stream = Store.OpenFile(key, FileMode.Create, FileAccess.Write);
62 | await JsonSerializer.SerializeAsync(stream, value, (JsonSerializerOptions?)null, ct);
63 | return true;
64 | }
65 | catch (Exception)
66 | {
67 | return false;
68 | }
69 | finally
70 | {
71 | Sema.Release();
72 | }
73 | }
74 |
75 | public override async Task LoadAsync(string key, CancellationToken ct) where T: default
76 | {
77 | await Sema.WaitAsync(ct);
78 |
79 | // it may happen, that a value type changes and can't be deserialized
80 | // so prevent exceptions in this case
81 | try
82 | {
83 | await using var stream = Store.OpenFile(key, FileMode.Open);
84 | return await JsonSerializer.DeserializeAsync(stream, (JsonSerializerOptions?)null, ct);
85 | }
86 | catch (Exception)
87 | {
88 | return default;
89 | }
90 | finally
91 | {
92 | Sema.Release();
93 | }
94 | }
95 |
96 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Avalonia.Preferences
2 | Cross platform preferences library for AvaloniaUI
3 |
4 |
5 | ## Usage
6 |
7 | - Install nuget `Sandreas.Avalonia.Preferences`
8 |
9 |
10 | ### Dependency Injection
11 |
12 | ```c#
13 | var services = new ServiceCollection();
14 | // ...
15 | services.AddSingleton();
16 | // ...
17 | ```
18 |
19 | ### API sample (simple)
20 |
21 |
22 | ```c#
23 |
24 | var counter = 0;
25 |
26 | // check for key
27 | if (preferences.ContainsKey("counter"))
28 | {
29 | // get value with defaultValue fallback
30 | counter = _preferences.Get("counter", 0);
31 | }
32 |
33 |
34 | counter++;
35 |
36 | // set value and check for success
37 | if(!_preferences.Set("counter", counter)) {
38 | Console.WriteLine("Error: Could not set counter");
39 | }
40 |
41 | // remove value
42 | if(!_preferences.Remove("counter")) {
43 | Console.WriteLine("Error: Could not remove counter");
44 | }
45 |
46 | // remove all values (clear)
47 | var clearedItemsCount = _preferences.Clear();
48 | if(clearedItemsCount == -1) {
49 | Console.WriteLine("Error: Could not clear preferences");
50 | } else {
51 | Console.WriteLine("Success: Removed " + clearedItemsCount + " items from preferences");
52 | }
53 | ```
54 |
55 |
56 |
57 | ### API sample (async, xplat)
58 |
59 | #### Platform specific storage
60 | If you need platform specific storage (e.g. for iOS or Android), you have to implement your own `IPreferences` implementation and statically set it before instantiating `Preferences`.
61 | To simplify the implementation, you can extend `AbstractPreferencesStorage` already providing some helpful overridable methods. As an example take a look at `GenericPreferencesStorage`
62 | ```c#
63 | // e.g. YourProject.Android/SplashActivity.cs
64 | protected override void OnResume()
65 | {
66 | base.OnResume();
67 | // your platform specific IPreferences implementation must be added statically before instantiation
68 | Preferences.PlatformStorage = new AndroidPlatformStorage(Application.Context);
69 | StartActivity(new Intent(Application.Context, typeof(MainActivity)));
70 | }
71 | ```
72 |
73 | #### Async usage
74 | ```c#
75 | // _preferences is set as class property via Dependency Injection
76 | private async Task GetCounterAsync() {
77 | // cancellation is not actually used, but you could
78 | var cts = new CancellationTokenSource();
79 | var ct = cts.Token;
80 | var counter = 0;
81 |
82 | // check for key
83 | if (_preferences.ContainsKey("counter"))
84 | {
85 | // get value with defaultValue fallback
86 | counter = await _preferences.GetAsync("counter", 0, ct);
87 | }
88 |
89 |
90 | counter++;
91 |
92 | // set value and check for success
93 | if(!await _preferences.SetAsync("counter", counter, ct)) {
94 | Console.WriteLine("Error: Could not set counter");
95 | }
96 |
97 | // remove value
98 | if(!await _preferences.RemoveAsync("counter", ct)) {
99 | Console.WriteLine("Error: Could not remove counter");
100 | }
101 |
102 | // remove all values (clear)
103 | var clearedItemsCount = await _preferences.ClearAsync(ct);
104 | if(clearedItemsCount == -1) {
105 | Console.WriteLine("Error: Could not clear preferences");
106 | } else {
107 | Console.WriteLine("Success: Removed " + clearedItemsCount + " items from preferences");
108 | }
109 | return counter;
110 | }
111 | ```
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "6.0.401",
4 | "rollForward": "latestMinor",
5 | "allowPrerelease": false
6 | }
7 | }
--------------------------------------------------------------------------------
/release.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | VERSION="$1"
3 | if [ "$VERSION" = "" ]; then
4 | echo "please provide a version as first parameter (e.g. 1.0.0)"
5 | exit 1
6 | fi
7 | git tag -a "v$VERSION" -m "release $VERSION" && git push origin --tags
--------------------------------------------------------------------------------
/unrelease.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | VERSION="$1"
3 | if [ "$VERSION" = "" ]; then
4 | echo "please provide a version as first parameter (e.g. 1.0.0)"
5 | exit 1
6 | fi
7 | git tag -d "v$VERSION" && git push --delete origin "v$VERSION"
--------------------------------------------------------------------------------