├── .editorconfig
├── .gitattributes
├── .github
├── FUNDING.yml
└── workflows
│ ├── ci-sample.yml
│ ├── ci.yml
│ └── release-nuget.yml
├── .gitignore
├── LICENSE
├── README.md
├── nuget.png
├── samples
├── Plugin.Maui.FormsMigration.Sample.sln
└── Plugin.Maui.FormsMigration.Sample
│ ├── App.xaml
│ ├── App.xaml.cs
│ ├── AppShell.xaml
│ ├── AppShell.xaml.cs
│ ├── MainPage.xaml
│ ├── MainPage.xaml.cs
│ ├── MauiProgram.cs
│ ├── Platforms
│ ├── Android
│ │ ├── AndroidManifest.xml
│ │ ├── MainActivity.cs
│ │ ├── MainApplication.cs
│ │ └── Resources
│ │ │ └── values
│ │ │ └── colors.xml
│ ├── MacCatalyst
│ │ ├── AppDelegate.cs
│ │ ├── Info.plist
│ │ └── Program.cs
│ ├── Tizen
│ │ ├── Main.cs
│ │ └── tizen-manifest.xml
│ ├── Windows
│ │ ├── App.xaml
│ │ ├── App.xaml.cs
│ │ ├── Package.appxmanifest
│ │ └── app.manifest
│ └── iOS
│ │ ├── AppDelegate.cs
│ │ ├── Entitlements.plist
│ │ ├── Info.plist
│ │ └── Program.cs
│ ├── Plugin.Maui.FormsMigration.Sample.csproj
│ ├── Properties
│ └── launchSettings.json
│ └── Resources
│ ├── AppIcon
│ ├── appicon.svg
│ └── appiconfg.svg
│ ├── Fonts
│ ├── OpenSans-Regular.ttf
│ └── OpenSans-Semibold.ttf
│ ├── Raw
│ ├── AboutAssets.txt
│ ├── dotnetbot.json
│ └── ukelele.mp3
│ ├── Splash
│ └── splash.svg
│ └── Styles
│ ├── Colors.xaml
│ └── Styles.xaml
└── src
├── Plugin.Maui.FormsMigration.sln
└── Plugin.Maui.FormsMigration
├── AppProperties
├── Extensions.windows.cs
├── LegacyApplication.shared.cs
├── PropertiesDeserializer.android.cs
├── PropertiesDeserializer.ios.cs
├── PropertiesDeserializer.net.cs
└── PropertiesDeserializer.windows.cs
├── Constants.shared.cs
├── Plugin.Maui.FormsMigration.csproj
├── SecureStorage
├── AndroidKeyStore.android.cs
├── KeyChain.ios.cs
├── LegacySecureStorage.android.cs
├── LegacySecureStorage.ios.cs
└── LegacySecureStorage.windows.cs
└── VersionTracking
├── LegacyPreferences.android.cs
├── LegacyPreferences.ios.cs
├── LegacyPreferences.net.cs
├── LegacyPreferences.shared.cs
├── LegacyPreferences.windows.cs
└── LegacyVersionTracking.shared.cs
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Suppress: EC112
2 | # top-most EditorConfig file
3 | root = true
4 |
5 | # Default settings:
6 | # A newline ending every file
7 | # Use tabs as indentation
8 | [*]
9 | insert_final_newline = false
10 | indent_style = tab
11 | indent_size = 4
12 |
13 | # Code files
14 | [*.{cs,csx,vb,vbx}]
15 | indent_style = tab
16 | indent_size = 4
17 |
18 | # Code files
19 | [*.sln]
20 | indent_size = 4
21 |
22 | # Xml project files
23 | [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
24 | indent_size = 2
25 |
26 | # Xml config files
27 | [*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
28 | indent_size = 2
29 |
30 | # JSON files
31 | [*.json]
32 | indent_size = 2
33 |
34 | # XML files
35 | [*.xml]
36 | indent_size = 2
37 |
38 | [*.cs]
39 |
40 | # Organize usings
41 | dotnet_sort_system_directives_first = true
42 |
43 | # IDE0160: Use file scoped namespace
44 | csharp_style_namespace_declarations = file_scoped:error
45 |
46 | # CS4014: Because this call is not awaited, execution of the current method continues before the call is completed
47 | dotnet_diagnostic.CS4014.severity = error
48 |
49 | # Remove explicit default access modifiers
50 | dotnet_style_require_accessibility_modifiers = omit_if_default:error
51 |
52 | # CA1063: Implement IDisposable Correctly
53 | dotnet_diagnostic.CA1063.severity = error
54 |
55 | # Add braces (IDE0011)
56 | csharp_prefer_braces = true
57 | dotnet_diagnostic.IDE0011.severity = error
58 |
59 | # Pattern matching
60 | dotnet_style_object_initializer = true:suggestion
61 | dotnet_style_collection_initializer = true:suggestion
62 | dotnet_style_coalesce_expression = true:suggestion
63 | dotnet_style_null_propagation = true:suggestion
64 | dotnet_style_explicit_tuple_names = true:suggestion
65 | dotnet_style_prefer_is_null_check_over_reference_equality_method=true:suggestion
66 |
67 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
68 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
69 | csharp_style_inlined_variable_declaration = true:suggestion
70 | csharp_style_throw_expression = true:suggestion
71 | csharp_style_conditional_delegate_call = true:suggestions
72 |
73 | # Naming rules
74 |
75 | dotnet_diagnostic.IDE1006.severity = error
76 |
77 | ## Public Fields are kept Pascal Case
78 | dotnet_naming_symbols.public_symbols.applicable_kinds = field
79 | dotnet_naming_symbols.public_symbols.applicable_accessibilities = public
80 |
81 | dotnet_naming_style.first_word_upper_case_style.capitalization = first_word_upper
82 |
83 | dotnet_naming_rule.public_members_must_be_capitalized.symbols = public_symbols
84 | dotnet_naming_rule.public_members_must_be_capitalized.style = first_word_upper_case_style
85 | dotnet_naming_rule.public_members_must_be_capitalized.severity = suggestion
86 |
87 | ## Instance fields are camelCase
88 | dotnet_naming_rule.instance_fields_should_be_camel_case.severity = error
89 | dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields
90 | dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style
91 |
92 | dotnet_naming_symbols.instance_fields.applicable_kinds = field
93 |
94 | dotnet_naming_style.instance_field_style.capitalization = camel_case
95 | dotnet_naming_style.instance_field_style.required_prefix =
96 |
97 | ## Static fields are camelCase
98 | dotnet_naming_rule.static_fields_should_be_camel_case.severity = error
99 | dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields
100 | dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style
101 |
102 | dotnet_naming_symbols.static_fields.applicable_kinds = field
103 | dotnet_naming_symbols.static_fields.required_modifiers = static
104 | dotnet_naming_symbols.static_fields.applicable_accessibilities = internal, private, protected, protected_internal, private_protected
105 |
106 | dotnet_naming_style.static_field_style.capitalization = camel_case
107 | dotnet_naming_style.static_field_style.required_prefix =
108 |
109 | # Modifier preferences
110 | csharp_prefer_static_local_function = true:suggestion
111 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:error
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: jfversluis
4 |
--------------------------------------------------------------------------------
/.github/workflows/ci-sample.yml:
--------------------------------------------------------------------------------
1 | name: Build Sample App for CI
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 | paths-ignore:
7 | - "**.md"
8 | pull_request:
9 | branches: [ "main" ]
10 |
11 | jobs:
12 | build-sample-ci:
13 |
14 | runs-on: windows-latest
15 |
16 | steps:
17 | - uses: actions/checkout@v3
18 | - name: Build
19 | run: dotnet build samples\Plugin.Maui.FormsMigration.Sample.sln -c Release
20 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Build for CI
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 | paths-ignore:
7 | - "**.md"
8 | pull_request:
9 | branches: [ "main" ]
10 |
11 | jobs:
12 | build-plugin-ci:
13 |
14 | runs-on: windows-latest
15 |
16 | steps:
17 | - uses: actions/checkout@v3
18 | - name: Build
19 | run: dotnet build src\Plugin.Maui.FormsMigration.sln -c Release
20 |
--------------------------------------------------------------------------------
/.github/workflows/release-nuget.yml:
--------------------------------------------------------------------------------
1 | name: Create a (Pre)release on NuGet
2 |
3 | on:
4 | push:
5 | tags:
6 | - "v[0-9]+.[0-9]+.[0-9]+"
7 | - "v[0-9]+.[0-9]+.[0-9]+-preview[0-9]+"
8 | jobs:
9 | release-nuget:
10 |
11 | runs-on: windows-latest
12 |
13 | steps:
14 | - uses: actions/checkout@v3
15 | - name: Verify commit exists in origin/main
16 | run: |
17 | git fetch --no-tags --prune --depth=1 origin +refs/heads/*:refs/remotes/origin/*
18 | git branch --remote --contains | grep origin/main
19 | - name: Get version information from tag
20 | id: get_version
21 | uses: battila7/get-version-action@v2
22 | - name: Pack
23 | run: dotnet pack src\Plugin.Maui.FormsMigration.sln -c Release -p:PackageVersion=${{ steps.get_version.outputs.version-without-v }}
24 | - name: Push
25 | run: dotnet nuget push src\Plugin.Maui.FormsMigration\bin\Release\Plugin.Maui.FormsMigration.${{ steps.get_version.outputs.version-without-v }}.nupkg -s https://api.nuget.org/v3/index.json -k ${{ secrets.NUGET_API_KEY }}
26 | env:
27 | GITHUB_TOKEN: ${{ secrets.NUGET_API_KEY }}
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 | .DS_Store
400 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Gerald Versluis
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | # Plugin.Maui.FormsMigration
3 |
4 | `Plugin.Maui.FormsMigration` provides helpers to make your transition from Xamarin.Forms to .NET MAUI easier.
5 |
6 | ## Install Plugin
7 |
8 | [](https://www.nuget.org/packages/Plugin.Maui.FormsMigration/)
9 |
10 | Available on [NuGet](http://www.nuget.org/packages/Plugin.Maui.FormsMigration).
11 |
12 | Install with the dotnet CLI: `dotnet add package Plugin.Maui.FormsMigration`, or through the NuGet Package Manager in Visual Studio.
13 |
14 | ### Supported Platforms
15 |
16 | The supported platforms for this library are Android, iOS and Windows.
17 |
18 | ## API Usage
19 |
20 | This library consists of three APIs that you can use for different scenarios:
21 |
22 | * [App Properties](#app-properties)
23 | * [SecureStorage](#securestorage)
24 | * [VersionTracking](#versiontracking)
25 |
26 | Each of these APIs will have their own way of using it. You can find the specifics below, or have a look at the [sample application](/samples/Plugin.Maui.FormsMigration.Sample/) that is included in this repository.
27 |
28 | > [!NOTE]
29 | > These APIs are meant for transition scenarios only. Use these APIs to retrieve data that is previously stored by your legacy Xamarin application and save them in a place where .NET MAUI can access that data from that point on. This is also the reason that these APIs are read-only.
30 |
31 | ### App Properties
32 |
33 | With Xamarin and Xamarin.Forms you had the possibility to save simple types through the `Properties` API like so: `Application.Current.Properties ["id"] = someClass.ID;`. In .NET MAUI, this is no longer possible.
34 |
35 | To help you transition from Xamarin to .NET MAUI, this library offers the `LegacyApplication` API to still be able to access previously saved properties. From there, save them through a newer API that is available in .NET MAUI. An example could be to use the [Preferences API](https://learn.microsoft.com/dotnet/maui/platform-integration/storage/preferences). See a simple example below.
36 |
37 | ```csharp
38 | int id;
39 | if (LegacyApplication.Current.Properties.ContainsKey("id"))
40 | {
41 | id = (int)LegacyApplication.Current.Properties["id"];
42 | Preferences.Set("id", id);
43 | }
44 | ```
45 |
46 | > [!NOTE]
47 | > For this API to work properly, you will have to make sure that the application identifier (or bundle identifier) is the same between your legacy Xamarin app and .NET MAUI app. This is needed so that the app gets installed in the same container on the operating system, which is needed to be able to read the property values that were stored previously.
48 |
49 | Also see this [Microsoft Learn Docs page](https://learn.microsoft.com/dotnet/maui/migration/app-properties) for more information.
50 |
51 | ### SecureStorage
52 |
53 | The [SecureStorage API](https://learn.microsoft.com/dotnet/maui/platform-integration/storage/secure-storage) is still available in .NET MAUI the same as it is in Xamarin and Xamarin.Forms. However, the name of the store where values were stored and some other details have changed which causes the .NET MAUI version of your app to not being able to retrieve the previously saved secure storage information.
54 |
55 | With the `LegacySecureStorage` you can retrieve the previously saved information in the secure storage of your legacy Xamarin application. From there you should resave them through the .NET MAUI secure storage API. An example of how to use this API can be found below.
56 |
57 | ```csharp
58 | // The code below assumes that there is a secure value saved with the key "oauth_token". Replace this key
59 | // with any value(s) you have stored in your legacy Xamarin app to get them out.
60 |
61 | string oauthToken = await LegacySecureStorage.GetAsync("oauth_token");
62 | bool result = LegacySecureStorage.Remove("oauth_token");
63 | await SecureStorage.SetAsync("oauth_token", oauthToken);
64 | ```
65 |
66 | > [!NOTE]
67 | > For this API to work properly, you will have to make sure that the application identifier (or bundle identifier) is the same between your legacy Xamarin app and .NET MAUI app. This is needed so that the app gets installed in the same container on the operating system, which is needed to be able to read the secure store values that were stored previously.
68 |
69 | > [!WARNING]
70 | > For iOS, make sure you have a `Entitlements.plist` with the following entry:
71 | >
72 | > `keychain-access-groups`
73 | >
74 | > `$(AppIdentifierPrefix)$(CFBundleIdentifier)`
75 | >
76 | > `$(AppIdentifierPrefix)$(CFBundleIdentifier)` can stay in place and will be replaced at build time or you can replace it with a hardcoded value.
77 | > Additionally make sure that the `Entitlements.plist` file is set in the Custom Entitlements field for Bundle Signing. For more information, refer to the [Microsoft Learn Docs page about entitlements](https://learn.microsoft.com/dotnet/maui/ios/entitlements).
78 |
79 | Also see this [Microsoft Learn Docs page](https://learn.microsoft.com/dotnet/maui/migration/secure-storage) for more information.
80 |
81 | ### VersionTracking
82 |
83 | The [VersionTracking API](https://learn.microsoft.com/dotnet/maui/platform-integration/appmodel/version-tracking) is still available in .NET MAUI the same as it is in Xamarin and Xamarin.Forms. However, the name of the store where values were stored and some other details have changed which causes the .NET MAUI version of your app to not being able to retrieve the previously saved version tracking information.
84 |
85 | > [!NOTE]
86 | > For this API to work properly, you will have to make sure that the application identifier (or bundle identifier) is the same between your legacy Xamarin app and .NET MAUI app. This is needed so that the app gets installed in the same container on the operating system, which is needed to be able to read the version information that was stored previously.
87 |
88 | > [!WARNING]
89 | > Make sure that the app version of your .NET MAUI app is **higher** than your legacy Xamarin application. Failing to do so might have unexpected results.
90 |
91 | Also see this [Microsoft Learn Docs page](https://learn.microsoft.com/dotnet/maui/migration/version-tracking) for more information.
92 |
93 | # Acknowledgements
94 |
95 | This project could not have came to be without these projects and people, thank you! <3
96 |
97 | The code in the plugin is mostly based on the original code in [Xamarin.Forms](https://github.com/xamarin/Xamarin.Forms) and [Xamarin.Essentials](https://github.com/xamarin/Essentials/). It has been adapted for the Microsoft Learn Docs by [David Britch](https://github.com/davidbritch).
98 |
--------------------------------------------------------------------------------
/nuget.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jfversluis/Plugin.Maui.FormsMigration/b6918d8c909a178f382d5cf9437d4087c112d030/nuget.png
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample.sln:
--------------------------------------------------------------------------------
1 | Microsoft Visual Studio Solution File, Format Version 12.00
2 | # Visual Studio Version 17
3 | VisualStudioVersion = 17.0.31611.283
4 | MinimumVisualStudioVersion = 10.0.40219.1
5 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Plugin.Maui.FormsMigration.Sample", "Plugin.Maui.FormsMigration.Sample\Plugin.Maui.FormsMigration.Sample.csproj", "{490BB138-9606-4FFF-8AAD-841C5B1ED059}"
6 | EndProject
7 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Plugin.Maui.FormsMigration", "..\src\Plugin.Maui.FormsMigration\Plugin.Maui.FormsMigration.csproj", "{B60F3174-E978-4F2B-B117-F6F0327594C8}"
8 |
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {490BB138-9606-4FFF-8AAD-841C5B1ED059}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {490BB138-9606-4FFF-8AAD-841C5B1ED059}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {490BB138-9606-4FFF-8AAD-841C5B1ED059}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
19 | {490BB138-9606-4FFF-8AAD-841C5B1ED059}.Release|Any CPU.ActiveCfg = Release|Any CPU
20 | {490BB138-9606-4FFF-8AAD-841C5B1ED059}.Release|Any CPU.Build.0 = Release|Any CPU
21 | {490BB138-9606-4FFF-8AAD-841C5B1ED059}.Release|Any CPU.Deploy.0 = Release|Any CPU
22 | {B60F3174-E978-4F2B-B117-F6F0327594C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {B60F3174-E978-4F2B-B117-F6F0327594C8}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {B60F3174-E978-4F2B-B117-F6F0327594C8}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {B60F3174-E978-4F2B-B117-F6F0327594C8}.Release|Any CPU.Build.0 = Release|Any CPU
26 | EndGlobalSection
27 | GlobalSection(SolutionProperties) = preSolution
28 | HideSolutionNode = FALSE
29 | EndGlobalSection
30 | GlobalSection(ExtensibilityGlobals) = postSolution
31 | SolutionGuid = {61F7FB11-1E47-470C-91E2-47F8143E1572}
32 | EndGlobalSection
33 | EndGlobal
34 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/App.xaml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/App.xaml.cs:
--------------------------------------------------------------------------------
1 | namespace Plugin.Maui.FormsMigration.Sample;
2 |
3 | public partial class App : Application
4 | {
5 | public App()
6 | {
7 | InitializeComponent();
8 |
9 | MainPage = new AppShell();
10 | }
11 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/AppShell.xaml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/AppShell.xaml.cs:
--------------------------------------------------------------------------------
1 | namespace Plugin.Maui.FormsMigration.Sample;
2 |
3 | public partial class AppShell : Shell
4 | {
5 | public AppShell()
6 | {
7 | InitializeComponent();
8 | }
9 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/MainPage.xaml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/MainPage.xaml.cs:
--------------------------------------------------------------------------------
1 | namespace Plugin.Maui.FormsMigration.Sample;
2 |
3 | public partial class MainPage : ContentPage
4 | {
5 | public MainPage()
6 | {
7 | InitializeComponent();
8 | }
9 |
10 | // SecureStorage Example
11 | async void SecureStorage_Clicked(object sender, EventArgs e)
12 | {
13 | // More information: https://learn.microsoft.com/dotnet/maui/migration/secure-storage
14 |
15 | // Xamarin.Essentials SecureStorage stores its data in $(AppInfo.PackageName).xamarinessentials
16 | // MAUI SecureStorage stores its data in $(AppInfo.PackageName).microsoft.maui.essentials.preferences
17 | // MAUI also uses different encryption for SecureStorage than used in Xamarin.Essentials.
18 |
19 | // $(AppInfo.PackageName) is referring to the Microsoft.Maui.ApplicationModel.AppInfo APIs and
20 | // will be replaced with your actual application ID. These should be the same for both your old app and new app.
21 |
22 | // The code below assumes that there is a secure value saved with the key "oauth_token". Replace this key
23 | // with any value(s) you have stored in your legacy Xamarin app to get them out.
24 |
25 | string oauthToken = await LegacySecureStorage.GetAsync("oauth_token");
26 | bool result = LegacySecureStorage.Remove("oauth_token");
27 | await SecureStorage.SetAsync("oauth_token", oauthToken);
28 | }
29 |
30 | // VersionTracking Example
31 | void VersionTracking_Clicked(object sender, EventArgs e)
32 | {
33 | // More information: https://learn.microsoft.com/dotnet/maui/migration/version-tracking
34 |
35 | // Retrieve values from your legacy Xamarin application through the LegacyVersionTracking class.
36 |
37 | // Read legacy version/build number information
38 | labelIsFirst.Text = LegacyVersionTracking.IsFirstLaunchEver.ToString();
39 | labelCurrentVersionIsFirst.Text = LegacyVersionTracking.IsFirstLaunchForCurrentVersion.ToString();
40 | labelCurrentBuildIsFirst.Text = LegacyVersionTracking.IsFirstLaunchForCurrentBuild.ToString();
41 | labelCurrentVersion.Text = LegacyVersionTracking.CurrentVersion.ToString();
42 | labelCurrentBuild.Text = LegacyVersionTracking.CurrentBuild.ToString();
43 | labelFirstInstalledVer.Text = LegacyVersionTracking.FirstInstalledVersion.ToString();
44 | labelFirstInstalledBuild.Text = LegacyVersionTracking.FirstInstalledBuild.ToString();
45 | labelVersionHistory.Text = string.Join(',', LegacyVersionTracking.VersionHistory);
46 | labelBuildHistory.Text = string.Join(',', LegacyVersionTracking.BuildHistory);
47 |
48 | // These two properties may be null if this is the first version
49 | labelPreviousVersion.Text = LegacyVersionTracking.PreviousVersion?.ToString() ?? "none";
50 | labelPreviousBuild.Text = LegacyVersionTracking.PreviousBuild?.ToString() ?? "none";
51 |
52 | // Transfer the full legacy Xamarin app version tracking information (version & build numbers)
53 | // to the .NET MAUI Version Tracking data store. Before doing so the *new* .NET MAUI Version Tracking
54 | // store will be cleared.
55 | LegacyVersionTracking.TransferHistory(true, true, true);
56 | }
57 |
58 | // Properties Example
59 | void AppProperties_Clicked(object sender, EventArgs e)
60 | {
61 | // More information: https://learn.microsoft.com/dotnet/maui/migration/app-properties
62 |
63 | // Retrieve values from your legacy Xamarin application through the LegacyApplication class.
64 |
65 | // The code below assumes that there is a property value saved with the key "id". Replace this key
66 | // with any value(s) you have stored in your legacy Xamarin app to get them out.
67 |
68 | int id;
69 | if (LegacyApplication.Current.Properties.ContainsKey("id"))
70 | {
71 | id = (int)LegacyApplication.Current.Properties["id"];
72 | Preferences.Set("id", id);
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/MauiProgram.cs:
--------------------------------------------------------------------------------
1 | namespace Plugin.Maui.FormsMigration.Sample;
2 |
3 | public static class MauiProgram
4 | {
5 | public static MauiApp CreateMauiApp()
6 | {
7 | var builder = MauiApp.CreateBuilder();
8 | builder
9 | .UseMauiApp()
10 | .ConfigureFonts(fonts =>
11 | {
12 | fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
13 | fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
14 | });
15 |
16 | builder.Services.AddTransient();
17 |
18 | return builder.Build();
19 | }
20 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Android/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Android/MainActivity.cs:
--------------------------------------------------------------------------------
1 | using Android.App;
2 | using Android.Content.PM;
3 | using Android.OS;
4 |
5 | namespace Plugin.Maui.FormsMigration.Sample;
6 |
7 | [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
8 | public class MainActivity : MauiAppCompatActivity
9 | {
10 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Android/MainApplication.cs:
--------------------------------------------------------------------------------
1 | using Android.App;
2 | using Android.Runtime;
3 |
4 | namespace Plugin.Maui.FormsMigration.Sample;
5 |
6 | [Application]
7 | public class MainApplication : MauiApplication
8 | {
9 | public MainApplication(IntPtr handle, JniHandleOwnership ownership)
10 | : base(handle, ownership)
11 | {
12 | }
13 |
14 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
15 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Android/Resources/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #512BD4
4 | #2B0B98
5 | #2B0B98
6 |
7 |
8 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/MacCatalyst/AppDelegate.cs:
--------------------------------------------------------------------------------
1 | using Foundation;
2 |
3 | namespace Plugin.Maui.FormsMigration.Sample;
4 |
5 | [Register("AppDelegate")]
6 | public class AppDelegate : MauiUIApplicationDelegate
7 | {
8 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
9 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/MacCatalyst/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | UIDeviceFamily
6 |
7 | 1
8 | 2
9 |
10 | UIRequiredDeviceCapabilities
11 |
12 | arm64
13 |
14 | UISupportedInterfaceOrientations
15 |
16 | UIInterfaceOrientationPortrait
17 | UIInterfaceOrientationLandscapeLeft
18 | UIInterfaceOrientationLandscapeRight
19 |
20 | UISupportedInterfaceOrientations~ipad
21 |
22 | UIInterfaceOrientationPortrait
23 | UIInterfaceOrientationPortraitUpsideDown
24 | UIInterfaceOrientationLandscapeLeft
25 | UIInterfaceOrientationLandscapeRight
26 |
27 | XSAppIconAssets
28 | Assets.xcassets/appicon.appiconset
29 |
30 |
31 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/MacCatalyst/Program.cs:
--------------------------------------------------------------------------------
1 | using ObjCRuntime;
2 | using UIKit;
3 |
4 | namespace Plugin.Maui.FormsMigration.Sample;
5 |
6 | public class Program
7 | {
8 | // This is the main entry point of the application.
9 | static void Main(string[] args)
10 | {
11 | // if you want to use a different Application Delegate class from "AppDelegate"
12 | // you can specify it here.
13 | UIApplication.Main(args, null, typeof(AppDelegate));
14 | }
15 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Tizen/Main.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.Maui;
3 | using Microsoft.Maui.Hosting;
4 |
5 | namespace Plugin.Maui.FormsMigration.Sample;
6 |
7 | class Program : MauiApplication
8 | {
9 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
10 |
11 | static void Main(string[] args)
12 | {
13 | var app = new Program();
14 | app.Run(args);
15 | }
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Tizen/tizen-manifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | maui-appicon-placeholder
7 |
8 |
9 |
10 |
11 | http://tizen.org/privilege/internet
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Windows/App.xaml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Windows/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.UI.Xaml;
2 |
3 | // To learn more about WinUI, the WinUI project structure,
4 | // and more about our project templates, see: http://aka.ms/winui-project-info.
5 |
6 | namespace Plugin.Maui.FormsMigration.Sample.WinUI;
7 |
8 | ///
9 | /// Provides application-specific behavior to supplement the default Application class.
10 | ///
11 | public partial class App : MauiWinUIApplication
12 | {
13 | ///
14 | /// Initializes the singleton application object. This is the first line of authored code
15 | /// executed, and as such is the logical equivalent of main() or WinMain().
16 | ///
17 | public App()
18 | {
19 | this.InitializeComponent();
20 | }
21 |
22 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
23 | }
24 |
25 |
26 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Windows/Package.appxmanifest:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
11 |
12 | $placeholder$
13 | User Name
14 | $placeholder$.png
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/Windows/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
11 | true/PM
12 | PerMonitorV2, PerMonitor
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/iOS/AppDelegate.cs:
--------------------------------------------------------------------------------
1 | using Foundation;
2 |
3 | namespace Plugin.Maui.FormsMigration.Sample;
4 |
5 | [Register("AppDelegate")]
6 | public class AppDelegate : MauiUIApplicationDelegate
7 | {
8 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
9 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/iOS/Entitlements.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | keychain-access-groups
6 | $(AppIdentifierPrefix)$(CFBundleIdentifier)
7 |
8 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/iOS/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | LSRequiresIPhoneOS
6 |
7 | UIDeviceFamily
8 |
9 | 1
10 | 2
11 |
12 | UIRequiredDeviceCapabilities
13 |
14 | arm64
15 |
16 | UISupportedInterfaceOrientations
17 |
18 | UIInterfaceOrientationPortrait
19 | UIInterfaceOrientationLandscapeLeft
20 | UIInterfaceOrientationLandscapeRight
21 |
22 | UISupportedInterfaceOrientations~ipad
23 |
24 | UIInterfaceOrientationPortrait
25 | UIInterfaceOrientationPortraitUpsideDown
26 | UIInterfaceOrientationLandscapeLeft
27 | UIInterfaceOrientationLandscapeRight
28 |
29 | XSAppIconAssets
30 | Assets.xcassets/appicon.appiconset
31 |
32 |
33 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Platforms/iOS/Program.cs:
--------------------------------------------------------------------------------
1 | using ObjCRuntime;
2 | using UIKit;
3 |
4 | namespace Plugin.Maui.FormsMigration.Sample;
5 |
6 | public class Program
7 | {
8 | // This is the main entry point of the application.
9 | static void Main(string[] args)
10 | {
11 | // if you want to use a different Application Delegate class from "AppDelegate"
12 | // you can specify it here.
13 | UIApplication.Main(args, null, typeof(AppDelegate));
14 | }
15 | }
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Plugin.Maui.FormsMigration.Sample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0-android;net8.0-ios;
5 | $(TargetFrameworks);net8.0-windows10.0.19041.0
6 | Exe
7 | Plugin.Maui.FormsMigration.Sample
8 | true
9 | true
10 | enable
11 |
12 |
13 | Plugin.Maui.FormsMigration.Sample
14 |
15 |
16 | com.companyname.pluginsample
17 | A20E30BB-3BF7-4ACB-89F2-596834136909
18 |
19 |
20 | 1.0
21 | 1
22 |
23 | 14.2
24 | 14.0
25 | 21.0
26 | 10.0.17763.0
27 | 10.0.17763.0
28 | 6.5
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "Windows Machine": {
4 | "commandName": "MsixPackage",
5 | "nativeDebugging": false
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/AppIcon/appicon.svg:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/AppIcon/appiconfg.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/Fonts/OpenSans-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jfversluis/Plugin.Maui.FormsMigration/b6918d8c909a178f382d5cf9437d4087c112d030/samples/Plugin.Maui.FormsMigration.Sample/Resources/Fonts/OpenSans-Regular.ttf
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/Fonts/OpenSans-Semibold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jfversluis/Plugin.Maui.FormsMigration/b6918d8c909a178f382d5cf9437d4087c112d030/samples/Plugin.Maui.FormsMigration.Sample/Resources/Fonts/OpenSans-Semibold.ttf
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/Raw/AboutAssets.txt:
--------------------------------------------------------------------------------
1 | Any raw assets you want to be deployed with your application can be placed in
2 | this directory (and child directories). Deployment of the asset to your application
3 | is automatically handled by the following `MauiAsset` Build Action within your `.csproj`.
4 |
5 |
6 |
7 | These files will be deployed with you package and will be accessible using Essentials:
8 |
9 | async Task LoadMauiAsset()
10 | {
11 | using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt");
12 | using var reader = new StreamReader(stream);
13 |
14 | var contents = reader.ReadToEnd();
15 | }
16 |
17 |
18 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/Raw/ukelele.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jfversluis/Plugin.Maui.FormsMigration/b6918d8c909a178f382d5cf9437d4087c112d030/samples/Plugin.Maui.FormsMigration.Sample/Resources/Raw/ukelele.mp3
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/Splash/splash.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/Styles/Colors.xaml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 | #512BD4
8 | #DFD8F7
9 | #2B0B98
10 | White
11 | Black
12 | #E1E1E1
13 | #C8C8C8
14 | #ACACAC
15 | #919191
16 | #6E6E6E
17 | #404040
18 | #212121
19 | #141414
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | #F7B548
35 | #FFD590
36 | #FFE5B9
37 | #28C2D1
38 | #7BDDEF
39 | #C3F2F4
40 | #3E8EED
41 | #72ACF1
42 | #A7CBF6
43 |
44 |
45 |
--------------------------------------------------------------------------------
/samples/Plugin.Maui.FormsMigration.Sample/Resources/Styles/Styles.xaml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
10 |
11 |
15 |
16 |
21 |
22 |
25 |
26 |
47 |
48 |
63 |
64 |
82 |
83 |
102 |
103 |
122 |
123 |
128 |
129 |
147 |
148 |
165 |
166 |
170 |
171 |
191 |
192 |
207 |
208 |
226 |
227 |
230 |
231 |
252 |
253 |
273 |
274 |
280 |
281 |
300 |
301 |
304 |
305 |
333 |
334 |
352 |
353 |
357 |
358 |
370 |
371 |
376 |
377 |
383 |
384 |
385 |
386 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 25.0.1704.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Plugin.Maui.FormsMigration", "Plugin.Maui.FormsMigration\Plugin.Maui.FormsMigration.csproj", "{2012F564-B8C7-4CEB-8495-1BCB1B0EB638}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {2012F564-B8C7-4CEB-8495-1BCB1B0EB638}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {2012F564-B8C7-4CEB-8495-1BCB1B0EB638}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {2012F564-B8C7-4CEB-8495-1BCB1B0EB638}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {2012F564-B8C7-4CEB-8495-1BCB1B0EB638}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {9C1A5250-4B63-4ABE-9E4A-65064808F863}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/AppProperties/Extensions.windows.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 | using Windows.Foundation;
3 |
4 | namespace Plugin.Maui.FormsMigration;
5 |
6 | static class Extensions
7 | {
8 | public static ConfiguredTaskAwaitable DontSync(this IAsyncOperation self)
9 | {
10 | return self.AsTask().ConfigureAwait(false);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/AppProperties/LegacyApplication.shared.cs:
--------------------------------------------------------------------------------
1 | namespace Plugin.Maui.FormsMigration;
2 |
3 | ///
4 | /// The LegacyApplication allows you to access the values saved through Application.Current.Properties in your legacy Xamarin app.
5 | ///
6 | ///
7 | /// The Properties API is no longer available in .NET MAUI, use this API to retrieve values from your legacy Xamarin app and save them
8 | /// through .
9 | /// For more information, please refer to Microsoft Learn.
10 | ///
11 | public class LegacyApplication
12 | {
13 | readonly PropertiesDeserializer deserializer;
14 | Task>? propertiesTask;
15 |
16 | static LegacyApplication? current;
17 | public static LegacyApplication? Current
18 | {
19 | get
20 | {
21 | current ??= (LegacyApplication?)Activator.CreateInstance(typeof(LegacyApplication));
22 |
23 | return current;
24 | }
25 | }
26 |
27 | public LegacyApplication()
28 | {
29 | deserializer = new PropertiesDeserializer();
30 | }
31 |
32 | public IDictionary Properties
33 | {
34 | get
35 | {
36 | propertiesTask ??= GetPropertiesAsync();
37 | return propertiesTask.Result;
38 | }
39 | }
40 |
41 | async Task> GetPropertiesAsync()
42 | {
43 | var properties = await deserializer.DeserializePropertiesAsync().ConfigureAwait(false);
44 | properties ??= new Dictionary(4);
45 |
46 | return properties;
47 | }
48 | }
49 |
50 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/AppProperties/PropertiesDeserializer.android.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using System.IO.IsolatedStorage;
3 | using System.Runtime.Serialization;
4 | using System.Xml;
5 |
6 | namespace Plugin.Maui.FormsMigration;
7 |
8 | class PropertiesDeserializer
9 | {
10 | public Task> DeserializePropertiesAsync()
11 | {
12 | // Deserialize property dictionary to local storage
13 | return Task.Run(() =>
14 | {
15 | using IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
16 | if (!store.FileExists(Constants.propertyStoreFile))
17 | {
18 | return new Dictionary(4);
19 | }
20 |
21 | using IsolatedStorageFileStream stream = store.OpenFile(Constants.propertyStoreFile, FileMode.Open, FileAccess.Read);
22 | using XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max);
23 |
24 | if (stream.Length == 0)
25 | {
26 | return new Dictionary(4);
27 | }
28 |
29 | try
30 | {
31 | var dcs = new DataContractSerializer(typeof(Dictionary));
32 | var readObject = dcs.ReadObject(reader) as IDictionary;
33 | return readObject ?? new Dictionary(4);
34 | }
35 | catch (Exception e)
36 | {
37 | Debug.WriteLine("Could not deserialize properties: " + e.Message);
38 | Console.WriteLine($"PropertyStore Exception while reading Application properties: {e}");
39 | }
40 |
41 | return new Dictionary(4);
42 | });
43 | }
44 | }
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/AppProperties/PropertiesDeserializer.ios.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using System.IO.IsolatedStorage;
3 | using System.Runtime.Serialization;
4 | using System.Xml;
5 |
6 | namespace Plugin.Maui.FormsMigration;
7 |
8 | class PropertiesDeserializer
9 | {
10 | public Task> DeserializePropertiesAsync()
11 | {
12 | // Deserialize property dictionary to local storage
13 | return Task.Run(() =>
14 | {
15 | using var store = IsolatedStorageFile.GetUserStoreForApplication();
16 | using var stream = store.OpenFile(Constants.propertyStoreFile, FileMode.OpenOrCreate);
17 | using var reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max);
18 |
19 | if (stream.Length == 0)
20 | {
21 | return new Dictionary(4);
22 | }
23 |
24 | try
25 | {
26 | var dcs = new DataContractSerializer(typeof(Dictionary));
27 | var readObject = dcs.ReadObject(reader) as IDictionary;
28 |
29 | return readObject ?? new Dictionary(4);
30 | }
31 | catch (Exception e)
32 | {
33 | Debug.WriteLine("Could not deserialize properties: " + e.Message);
34 | Console.WriteLine($"PropertyStore Exception while reading Application properties: {e}");
35 | }
36 |
37 | return new Dictionary(4);
38 | });
39 | }
40 | }
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/AppProperties/PropertiesDeserializer.net.cs:
--------------------------------------------------------------------------------
1 | namespace Plugin.Maui.FormsMigration;
2 |
3 | class PropertiesDeserializer
4 | {
5 | public Task> DeserializePropertiesAsync()
6 | {
7 | throw new NotImplementedException();
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/AppProperties/PropertiesDeserializer.windows.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using System.Runtime.Serialization;
3 | using Windows.Storage;
4 |
5 | namespace Plugin.Maui.FormsMigration;
6 |
7 | class PropertiesDeserializer
8 | {
9 | public async Task> DeserializePropertiesAsync()
10 | {
11 | try
12 | {
13 | StorageFile file = await ApplicationData.Current.RoamingFolder.GetFileAsync(Constants.propertyStoreFile).DontSync();
14 | using Stream stream = (await file.OpenReadAsync().DontSync()).AsStreamForRead();
15 |
16 | if (stream.Length == 0)
17 | {
18 | return new Dictionary(4);
19 | }
20 |
21 | try
22 | {
23 | var serializer = new DataContractSerializer(typeof(IDictionary));
24 | var readObject = serializer.ReadObject(stream) as IDictionary;
25 |
26 | return readObject ?? new Dictionary(4);
27 | }
28 | catch (Exception e)
29 | {
30 | Debug.WriteLine("Could not deserialize properties: " + e.Message);
31 | Console.WriteLine($"PropertyStore Exception while reading Application properties: {e}");
32 | }
33 | return new Dictionary(4);
34 | }
35 | catch (FileNotFoundException)
36 | {
37 | return new Dictionary(4);
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/Constants.shared.cs:
--------------------------------------------------------------------------------
1 | namespace Plugin.Maui.FormsMigration;
2 |
3 | public static class Constants
4 | {
5 | // App Properties
6 | internal const string propertyStoreFile = "PropertyStore.forms";
7 | }
8 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/Plugin.Maui.FormsMigration.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0-android;net8.0-ios;net8.0
4 | $(TargetFrameworks);net8.0-windows10.0.19041.0
5 | true
6 | enable
7 | enable
8 | true
9 |
10 |
11 | 14.2
12 | 14.0
13 | 21.0
14 | 10.0.17763.0
15 | 10.0.17763.0
16 | 6.5
17 |
18 |
19 | Gerald Versluis
20 | Copyright © Gerald Versluis and contributors
21 | True
22 | https://github.com/jfversluis/Plugin.Maui.FormsMigration
23 | https://github.com/jfversluis/Plugin.Maui.FormsMigration
24 | git
25 | dotnet-maui;maui;plugin;migration;xamarin;xamarin-forms;
26 | True
27 | true
28 | true
29 | snupkg
30 | .NET MAUI Xamarin.Forms Migration Plugin
31 | Plugin.Maui.FormsMigration provides helpers to make your transition from Xamarin.Forms to .NET MAUI easier.
32 | MIT
33 | True
34 | portable
35 | icon.png
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/SecureStorage/AndroidKeyStore.android.cs:
--------------------------------------------------------------------------------
1 | using Android.Content;
2 | using Android.OS;
3 | using Android.Runtime;
4 | using Android.Security;
5 | using Android.Security.Keystore;
6 | using Java.Security;
7 | using Javax.Crypto;
8 | using Javax.Crypto.Spec;
9 | using Microsoft.Maui.ApplicationModel;
10 | using Microsoft.Maui.Storage;
11 | using System.Text;
12 |
13 | namespace Plugin.Maui.FormsMigration;
14 |
15 | class AndroidKeyStore
16 | {
17 | const string androidKeyStore = "AndroidKeyStore"; // this is an Android const value
18 | const string aesAlgorithm = "AES";
19 | const string cipherTransformationAsymmetric = "RSA/ECB/PKCS1Padding";
20 | const string cipherTransformationSymmetric = "AES/GCM/NoPadding";
21 | const string prefsMasterKey = "SecureStorageKey";
22 | const int initializationVectorLen = 12; // Android supports an IV of 12 for AES/GCM
23 |
24 | internal AndroidKeyStore(Context context, string keystoreAlias, bool alwaysUseAsymmetricKeyStorage)
25 | {
26 | alwaysUseAsymmetricKey = alwaysUseAsymmetricKeyStorage;
27 | appContext = context;
28 | alias = keystoreAlias;
29 |
30 | keyStore = KeyStore.GetInstance(androidKeyStore)
31 | ?? throw new Exception($"Could not retrieve instance of Android keystore with ID {androidKeyStore}");
32 |
33 | keyStore.Load(null);
34 | }
35 |
36 | readonly Context appContext;
37 | readonly string alias;
38 | readonly bool alwaysUseAsymmetricKey;
39 | readonly string useSymmetricPreferenceKey = "essentials_use_symmetric";
40 |
41 | KeyStore keyStore;
42 | bool useSymmetric = false;
43 |
44 | ISecretKey GetKey()
45 | {
46 | // check to see if we need to get our key from past-versions or newer versions.
47 | // we want to use symmetric if we are >= 23 or we didn't set it previously.
48 | var hasApiLevel = Build.VERSION.SdkInt >= BuildVersionCodes.M;
49 |
50 | useSymmetric = Preferences.Get(useSymmetricPreferenceKey, hasApiLevel, alias);
51 |
52 | // If >= API 23 we can use the KeyStore's symmetric key
53 | if (useSymmetric && !alwaysUseAsymmetricKey)
54 | {
55 | return GetSymmetricKey();
56 | }
57 |
58 | // NOTE: KeyStore in < API 23 can only store asymmetric keys
59 | // specifically, only RSA/ECB/PKCS1Padding
60 | // So we will wrap our symmetric AES key we just generated
61 | // with this and save the encrypted/wrapped key out to
62 | // preferences for future use.
63 | // ECB should be fine in this case as the AES key should be
64 | // contained in one block.
65 |
66 | // Get the asymmetric key pair
67 | var keyPair = GetAsymmetricKeyPair();
68 |
69 | var existingKeyStr = Preferences.Get(prefsMasterKey, null, alias);
70 |
71 | if (!string.IsNullOrEmpty(existingKeyStr))
72 | {
73 | try
74 | {
75 | var wrappedKey = Convert.FromBase64String(existingKeyStr);
76 |
77 | var unwrappedKey = UnwrapKey(wrappedKey, keyPair.Private);
78 | var kp = unwrappedKey.JavaCast();
79 |
80 | return kp;
81 | }
82 | catch (InvalidKeyException ikEx)
83 | {
84 | System.Diagnostics.Debug.WriteLine($"Unable to unwrap key: Invalid Key. This may be caused by system backup or upgrades. All secure storage items will now be removed. {ikEx.Message}");
85 | }
86 | catch (IllegalBlockSizeException ibsEx)
87 | {
88 | System.Diagnostics.Debug.WriteLine($"Unable to unwrap key: Illegal Block Size. This may be caused by system backup or upgrades. All secure storage items will now be removed. {ibsEx.Message}");
89 | }
90 | catch (BadPaddingException paddingEx)
91 | {
92 | System.Diagnostics.Debug.WriteLine($"Unable to unwrap key: Bad Padding. This may be caused by system backup or upgrades. All secure storage items will now be removed. {paddingEx.Message}");
93 | }
94 | LegacySecureStorage.RemoveAll();
95 | }
96 |
97 | var keyGenerator = KeyGenerator.GetInstance(aesAlgorithm);
98 | var defSymmetricKey = keyGenerator.GenerateKey();
99 |
100 | var newWrappedKey = WrapKey(defSymmetricKey, keyPair.Public);
101 |
102 | Preferences.Set(prefsMasterKey, Convert.ToBase64String(newWrappedKey), alias);
103 |
104 | return defSymmetricKey;
105 | }
106 |
107 | // API 23+ Only
108 | #pragma warning disable CA1416
109 | ISecretKey GetSymmetricKey()
110 | {
111 | Preferences.Set(useSymmetricPreferenceKey, true, alias);
112 |
113 | var existingKey = keyStore.GetKey(alias, null);
114 |
115 | if (existingKey != null)
116 | {
117 | var existingSecretKey = existingKey.JavaCast();
118 | return existingSecretKey;
119 | }
120 |
121 | var keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, androidKeyStore);
122 | var builder = new KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
123 | .SetBlockModes(KeyProperties.BlockModeGcm)
124 | .SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone)
125 | .SetRandomizedEncryptionRequired(false);
126 |
127 | keyGenerator.Init(builder.Build());
128 |
129 | return keyGenerator.GenerateKey();
130 | }
131 | #pragma warning restore CA1416
132 |
133 | KeyPair GetAsymmetricKeyPair()
134 | {
135 | // set that we generated keys on pre-m device.
136 | Preferences.Set(useSymmetricPreferenceKey, false, alias);
137 |
138 | var asymmetricAlias = $"{alias}.asymmetric";
139 |
140 | var privateKey = keyStore.GetKey(asymmetricAlias, null)?.JavaCast();
141 | var publicKey = keyStore.GetCertificate(asymmetricAlias)?.PublicKey;
142 |
143 | // Return the existing key if found
144 | if (privateKey != null && publicKey != null)
145 | {
146 | return new KeyPair(publicKey, privateKey);
147 | }
148 |
149 | var originalLocale = Java.Util.Locale.Default;
150 | try
151 | {
152 | // Force to english for known bug in date parsing:
153 | // https://issuetracker.google.com/issues/37095309
154 | SetLocale(Java.Util.Locale.English);
155 |
156 | // Otherwise we create a new key
157 | #pragma warning disable CA1416
158 | var generator = KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, androidKeyStore);
159 | #pragma warning restore CA1416
160 |
161 | var end = DateTime.UtcNow.AddYears(20);
162 | var startDate = new Java.Util.Date();
163 | #pragma warning disable CS0618 // Type or member is obsolete
164 | var endDate = new Java.Util.Date(end.Year, end.Month, end.Day);
165 | #pragma warning restore CS0618 // Type or member is obsolete
166 |
167 | #pragma warning disable CS0618
168 | var builder = new KeyPairGeneratorSpec.Builder(Platform.AppContext)
169 | .SetAlias(asymmetricAlias)
170 | .SetSerialNumber(Java.Math.BigInteger.One)
171 | .SetSubject(new Javax.Security.Auth.X500.X500Principal($"CN={asymmetricAlias} CA Certificate"))
172 | .SetStartDate(startDate)
173 | .SetEndDate(endDate);
174 |
175 | generator.Initialize(builder.Build());
176 | #pragma warning restore CS0618
177 |
178 | return generator.GenerateKeyPair();
179 | }
180 | finally
181 | {
182 | SetLocale(originalLocale);
183 | }
184 | }
185 |
186 | byte[] WrapKey(IKey keyToWrap, IKey withKey)
187 | {
188 | var cipher = Cipher.GetInstance(cipherTransformationAsymmetric);
189 | cipher.Init(CipherMode.WrapMode, withKey);
190 | return cipher.Wrap(keyToWrap);
191 | }
192 |
193 | #pragma warning disable CA1416
194 | IKey UnwrapKey(byte[] wrappedData, IKey withKey)
195 | {
196 | var cipher = Cipher.GetInstance(cipherTransformationAsymmetric);
197 | cipher.Init(CipherMode.UnwrapMode, withKey);
198 | var unwrapped = cipher.Unwrap(wrappedData, KeyProperties.KeyAlgorithmAes, KeyType.SecretKey);
199 | return unwrapped;
200 | }
201 | #pragma warning restore CA1416
202 |
203 | internal string Decrypt(byte[] data)
204 | {
205 | if (data.Length < initializationVectorLen)
206 | {
207 | return string.Empty;
208 | }
209 |
210 | var key = GetKey();
211 |
212 | // IV will be the first 16 bytes of the encrypted data
213 | var iv = new byte[initializationVectorLen];
214 | Buffer.BlockCopy(data, 0, iv, 0, initializationVectorLen);
215 |
216 | Cipher cipher;
217 |
218 | // Attempt to use GCMParameterSpec by default
219 | try
220 | {
221 | cipher = Cipher.GetInstance(cipherTransformationSymmetric);
222 | cipher.Init(CipherMode.DecryptMode, key, new GCMParameterSpec(128, iv));
223 | }
224 | catch (InvalidAlgorithmParameterException)
225 | {
226 | // If we encounter this error, it's likely an old bouncycastle provider version
227 | // is being used which does not recognize GCMParameterSpec, but should work
228 | // with IvParameterSpec, however we only do this as a last effort since other
229 | // implementations will error if you use IvParameterSpec when GCMParameterSpec
230 | // is recognized and expected.
231 | cipher = Cipher.GetInstance(cipherTransformationSymmetric);
232 | cipher.Init(CipherMode.DecryptMode, key, new IvParameterSpec(iv));
233 | }
234 |
235 | // Decrypt starting after the first 16 bytes from the IV
236 | var decryptedData = cipher.DoFinal(data, initializationVectorLen, data.Length - initializationVectorLen);
237 |
238 | return Encoding.UTF8.GetString(decryptedData);
239 | }
240 |
241 | internal void SetLocale(Java.Util.Locale locale)
242 | {
243 | Java.Util.Locale.Default = locale;
244 | var resources = appContext.Resources;
245 | var config = resources?.Configuration;
246 |
247 | if (config is null)
248 | {
249 | return;
250 | }
251 |
252 | if (OperatingSystem.IsAndroidVersionAtLeast(24))
253 | {
254 | config.SetLocale(locale);
255 | }
256 | else
257 | {
258 | config.Locale = locale;
259 | }
260 |
261 | if (OperatingSystem.IsAndroidVersionAtLeast(25))
262 | {
263 | Platform.AppContext.CreateConfigurationContext(config);
264 | }
265 | else
266 | {
267 | resources?.UpdateConfiguration(config, resources.DisplayMetrics);
268 | }
269 | }
270 | }
271 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/SecureStorage/KeyChain.ios.cs:
--------------------------------------------------------------------------------
1 | using Foundation;
2 | using Security;
3 |
4 | namespace Plugin.Maui.FormsMigration;
5 |
6 | class KeyChain
7 | {
8 | static SecRecord ExistingRecordForKey(string key, string service)
9 | {
10 | return new SecRecord(SecKind.GenericPassword)
11 | {
12 | Account = key,
13 | Service = service
14 | };
15 | }
16 |
17 | internal static string ValueForKey(string key, string service)
18 | {
19 | using var record = ExistingRecordForKey(key, service);
20 | using var match = SecKeyChain.QueryAsRecord(record, out var resultCode);
21 |
22 | if (resultCode == SecStatusCode.Success
23 | && !string.IsNullOrEmpty(match?.ValueData?.ToString()))
24 | {
25 | return NSString.FromData(match.ValueData, NSStringEncoding.UTF8)
26 | ?? string.Empty;
27 | }
28 | else
29 | {
30 | return string.Empty;
31 | }
32 | }
33 |
34 | internal static bool Remove(string key, string service)
35 | {
36 | using var record = ExistingRecordForKey(key, service);
37 | using var match = SecKeyChain.QueryAsRecord(record, out var resultCode);
38 |
39 | if (resultCode == SecStatusCode.Success)
40 | {
41 | RemoveRecord(record);
42 | return true;
43 | }
44 |
45 | return false;
46 | }
47 |
48 | internal static void RemoveAll(string service)
49 | {
50 | using var query = new SecRecord(SecKind.GenericPassword) { Service = service };
51 | SecKeyChain.Remove(query);
52 | }
53 |
54 | static bool RemoveRecord(SecRecord record)
55 | {
56 | var result = SecKeyChain.Remove(record);
57 | if (result != SecStatusCode.Success && result != SecStatusCode.ItemNotFound)
58 | {
59 | throw new Exception($"Error removing record: {result}");
60 | }
61 |
62 | return true;
63 | }
64 | }
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/SecureStorage/LegacySecureStorage.android.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Maui.ApplicationModel;
2 | using Microsoft.Maui.Storage;
3 |
4 | namespace Plugin.Maui.FormsMigration;
5 |
6 | ///
7 | /// The LegacySecureStorage class allows access to the secure values saved with Xamarin.Essentials.
8 | ///
9 | ///
10 | /// This functionality should only be used in migration scenarios from Xamarin to .NET MAUI.
11 | /// Existing values from the legacy application can be read through this functionality and should be (re)saved with .
12 | ///
13 | public static class LegacySecureStorage
14 | {
15 | internal static readonly string alias = $"{AppInfo.PackageName}.xamarinessentials";
16 |
17 | ///
18 | /// Gets and decrypts the value for a given key from the Xamarin.Essentials (legacy) SecureStorage store.
19 | ///
20 | /// The key to retrieve the value for.
21 | /// The decrypted string value or if a value was not found.
22 | public static Task GetAsync(string key)
23 | {
24 | ArgumentException.ThrowIfNullOrEmpty(nameof(key), nameof(key));
25 |
26 | string result = string.Empty;
27 |
28 | object locker = new();
29 | string? encVal = Preferences.Get(key, null, alias);
30 |
31 | if (!string.IsNullOrEmpty(encVal))
32 | {
33 | byte[] encData = Convert.FromBase64String(encVal);
34 | lock (locker)
35 | {
36 | AndroidKeyStore keyStore = new(Platform.AppContext, alias, false);
37 | result = keyStore.Decrypt(encData);
38 | }
39 | }
40 |
41 | return Task.FromResult(result);
42 | }
43 |
44 | ///
45 | /// Removes a key and its associated value if it exists from the Xamarin.Essentials (legacy) SecureStorage store.
46 | ///
47 | /// The key to remove.
48 | public static bool Remove(string key)
49 | {
50 | Preferences.Remove(key, alias);
51 |
52 | return true;
53 | }
54 |
55 | ///
56 | /// Removes all of the stored encrypted key/value pairs from the Xamarin.Essentials (legacy) SecureStorage store.
57 | ///
58 | public static void RemoveAll()
59 | {
60 | Preferences.Clear(alias);
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/SecureStorage/LegacySecureStorage.ios.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Maui.ApplicationModel;
2 |
3 | namespace Plugin.Maui.FormsMigration;
4 |
5 | ///
6 | /// The LegacySecureStorage class allows access to the secure values saved with Xamarin.Essentials.
7 | ///
8 | ///
9 | /// IMPORTANT - Make sure you have an Entitlements.plist with the following:
10 | /// <key>keychain-access-groups</key>
11 | /// <string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
12 | /// and that the Entitlements.plist is set in the Custom Entitlements field for Bundle Signing.
13 | /// This functionality should only be used in migration scenarios from Xamarin to .NET MAUI.
14 | /// Existing values from the legacy application can be read through this functionality and should be (re)saved with .
15 | ///
16 | public static class LegacySecureStorage
17 | {
18 | internal static readonly string alias = $"{AppInfo.PackageName}.xamarinessentials";
19 |
20 | ///
21 | /// Gets and decrypts the value for a given key from the Xamarin.Essentials (legacy) SecureStorage store.
22 | ///
23 | /// The key to retrieve the value for.
24 | /// The decrypted string value or if a value was not found.
25 | public static Task GetAsync(string key)
26 | {
27 | ArgumentException.ThrowIfNullOrEmpty(nameof(key), nameof(key));
28 |
29 | string result = KeyChain.ValueForKey(key, alias);
30 |
31 | return Task.FromResult(result);
32 | }
33 |
34 | ///
35 | /// Removes a key and its associated value if it exists from the Xamarin.Essentials (legacy) SecureStorage store.
36 | ///
37 | /// The key to remove.
38 | public static bool Remove(string key)
39 | {
40 | bool result = KeyChain.Remove(key, alias);
41 |
42 | return result;
43 | }
44 |
45 | ///
46 | /// Removes all of the stored encrypted key/value pairs from the Xamarin.Essentials (legacy) SecureStorage store.
47 | ///
48 | public static void RemoveAll()
49 | {
50 | KeyChain.RemoveAll(alias);
51 | }
52 | }
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/SecureStorage/LegacySecureStorage.windows.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices.WindowsRuntime;
2 | using System.Text;
3 | using Microsoft.Maui.ApplicationModel;
4 | using Windows.Security.Cryptography.DataProtection;
5 | using Windows.Storage;
6 |
7 | namespace Plugin.Maui.FormsMigration;
8 |
9 | ///
10 | /// The LegacySecureStorage class allows access to the secure values saved with Xamarin.Essentials.
11 | ///
12 | ///
13 | /// This functionality should only be used in migration scenarios from Xamarin to .NET MAUI.
14 | /// Existing values from the legacy application can be read through this functionality and should be (re)saved with .
15 | ///
16 | public partial class LegacySecureStorage
17 | {
18 | internal static readonly string alias = $"{AppInfo.PackageName}.xamarinessentials";
19 |
20 | ///
21 | /// Gets and decrypts the value for a given key from the Xamarin.Essentials (legacy) SecureStorage store.
22 | ///
23 | /// The key to retrieve the value for.
24 | /// The decrypted string value or if a value was not found.
25 | public static async Task GetAsync(string key)
26 | {
27 | var settings = GetSettings(alias);
28 |
29 | var encBytes = settings.Values[key] as byte[];
30 |
31 | if (encBytes == null)
32 | {
33 | return string.Empty;
34 | }
35 |
36 | var provider = new DataProtectionProvider();
37 |
38 | var buffer = await provider.UnprotectAsync(encBytes.AsBuffer());
39 |
40 | return Encoding.UTF8.GetString(buffer.ToArray());
41 | }
42 |
43 | ///
44 | /// Removes a key and its associated value if it exists from the Xamarin.Essentials (legacy) SecureStorage store.
45 | ///
46 | /// The key to remove.
47 | public static bool Remove(string key)
48 | {
49 | var settings = GetSettings(alias);
50 |
51 | if (settings.Values.ContainsKey(key))
52 | {
53 | settings.Values.Remove(key);
54 | return true;
55 | }
56 |
57 | return false;
58 | }
59 |
60 | ///
61 | /// Removes all of the stored encrypted key/value pairs from the Xamarin.Essentials (legacy) SecureStorage store.
62 | ///
63 | public static void RemoveAll()
64 | {
65 | var settings = GetSettings(alias);
66 |
67 | settings.Values.Clear();
68 | }
69 |
70 | static ApplicationDataContainer GetSettings(string name)
71 | {
72 | var localSettings = ApplicationData.Current.LocalSettings;
73 |
74 | if (!localSettings.Containers.ContainsKey(name))
75 | {
76 | localSettings.CreateContainer(name, ApplicationDataCreateDisposition.Always);
77 | }
78 |
79 | return localSettings.Containers[name];
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/VersionTracking/LegacyPreferences.android.cs:
--------------------------------------------------------------------------------
1 | using System.Globalization;
2 | using Android.Content;
3 | using Android.Preferences;
4 |
5 | namespace Plugin.Maui.FormsMigration;
6 |
7 | public static partial class LegacyPreferences
8 | {
9 | static readonly object locker = new();
10 |
11 | static bool PlatformContainsKey(string key, string sharedName)
12 | {
13 | lock (locker)
14 | {
15 | using var sharedPreferences = GetSharedPreferences(sharedName);
16 | return sharedPreferences.Contains(key);
17 | }
18 | }
19 |
20 | static void PlatformRemove(string key, string sharedName)
21 | {
22 | lock (locker)
23 | {
24 | using var sharedPreferences = GetSharedPreferences(sharedName);
25 | using var editor = sharedPreferences.Edit();
26 | editor.Remove(key).Apply();
27 | }
28 | }
29 |
30 | static T PlatformGet(string key, T defaultValue, string sharedName)
31 | {
32 | lock (locker)
33 | {
34 | object value = null;
35 | using (var sharedPreferences = GetSharedPreferences(sharedName))
36 | {
37 | if (defaultValue == null)
38 | {
39 | value = sharedPreferences.GetString(key, null);
40 | }
41 | else
42 | {
43 | switch (defaultValue)
44 | {
45 | case int i:
46 | value = sharedPreferences.GetInt(key, i);
47 | break;
48 | case bool b:
49 | value = sharedPreferences.GetBoolean(key, b);
50 | break;
51 | case long l:
52 | value = sharedPreferences.GetLong(key, l);
53 | break;
54 | case double d:
55 | var savedDouble = sharedPreferences.GetString(key, null);
56 | if (string.IsNullOrWhiteSpace(savedDouble))
57 | {
58 | value = defaultValue;
59 | }
60 | else
61 | {
62 | if (!double.TryParse(savedDouble, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var outDouble))
63 | {
64 | var maxString = Convert.ToString(double.MaxValue, CultureInfo.InvariantCulture);
65 | outDouble = savedDouble.Equals(maxString) ? double.MaxValue : double.MinValue;
66 | }
67 |
68 | value = outDouble;
69 | }
70 | break;
71 | case float f:
72 | value = sharedPreferences.GetFloat(key, f);
73 | break;
74 | case string s:
75 | // the case when the string is not null
76 | value = sharedPreferences.GetString(key, s);
77 | break;
78 | }
79 | }
80 | }
81 |
82 | return (T)value;
83 | }
84 | }
85 |
86 | static ISharedPreferences GetSharedPreferences(string sharedName)
87 | {
88 | var context = Platform.AppContext;
89 |
90 | return string.IsNullOrWhiteSpace(sharedName) ?
91 | #pragma warning disable CS0618 // Type or member is obsolete
92 | PreferenceManager.GetDefaultSharedPreferences(context) :
93 | #pragma warning restore CS0618 // Type or member is obsolete
94 | context.GetSharedPreferences(sharedName, FileCreationMode.Private);
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/VersionTracking/LegacyPreferences.ios.cs:
--------------------------------------------------------------------------------
1 | using System.Globalization;
2 | using Foundation;
3 |
4 | namespace Plugin.Maui.FormsMigration;
5 |
6 | public static partial class LegacyPreferences
7 | {
8 | static readonly object locker = new();
9 |
10 | static bool PlatformContainsKey(string key, string sharedName)
11 | {
12 | lock (locker)
13 | {
14 | return GetUserDefaults(sharedName)[key] != null;
15 | }
16 | }
17 |
18 | static void PlatformRemove(string key, string sharedName)
19 | {
20 | lock (locker)
21 | {
22 | using var userDefaults = GetUserDefaults(sharedName);
23 | if (userDefaults[key] != null)
24 | {
25 | userDefaults.RemoveObject(key);
26 | }
27 | }
28 | }
29 |
30 | static T PlatformGet(string key, T defaultValue, string sharedName)
31 | {
32 | object value = null;
33 |
34 | lock (locker)
35 | {
36 | using var userDefaults = GetUserDefaults(sharedName);
37 | if (userDefaults[key] == null)
38 | {
39 | return defaultValue;
40 | }
41 |
42 | switch (defaultValue)
43 | {
44 | case int i:
45 | value = (int)(nint)userDefaults.IntForKey(key);
46 | break;
47 | case bool b:
48 | value = userDefaults.BoolForKey(key);
49 | break;
50 | case long l:
51 | var savedLong = userDefaults.StringForKey(key);
52 | value = Convert.ToInt64(savedLong, CultureInfo.InvariantCulture);
53 | break;
54 | case double d:
55 | value = userDefaults.DoubleForKey(key);
56 | break;
57 | case float f:
58 | value = userDefaults.FloatForKey(key);
59 | break;
60 | case string s:
61 | // the case when the string is not null
62 | value = userDefaults.StringForKey(key);
63 | break;
64 | default:
65 | // the case when the string is null
66 | if (typeof(T) == typeof(string))
67 | {
68 | value = userDefaults.StringForKey(key);
69 | }
70 | break;
71 | }
72 | }
73 |
74 | return (T)value;
75 | }
76 |
77 | static NSUserDefaults GetUserDefaults(string sharedName)
78 | {
79 | if (!string.IsNullOrWhiteSpace(sharedName))
80 | {
81 | return new NSUserDefaults(sharedName, NSUserDefaultsType.SuiteName);
82 | }
83 |
84 | return NSUserDefaults.StandardUserDefaults;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/VersionTracking/LegacyPreferences.net.cs:
--------------------------------------------------------------------------------
1 | namespace Plugin.Maui.FormsMigration;
2 |
3 | public static partial class LegacyPreferences
4 | {
5 | static bool PlatformContainsKey(string key, string sharedName)
6 | {
7 | throw new NotImplementedException();
8 | }
9 |
10 | static void PlatformRemove(string key, string sharedName)
11 | {
12 | throw new NotImplementedException();
13 | }
14 |
15 | static T PlatformGet(string key, T defaultValue, string sharedName)
16 | {
17 | throw new NotImplementedException();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/VersionTracking/LegacyPreferences.shared.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Maui.ApplicationModel;
2 |
3 | namespace Plugin.Maui.FormsMigration;
4 |
5 | static partial class LegacyPreferences
6 | {
7 | internal static string GetPrivatePreferencesSharedName(string feature) =>
8 | $"{AppInfo.PackageName}.xamarinessentials.{feature}";
9 |
10 | internal static bool ContainsKey(string key, string sharedName) => PlatformContainsKey(key, sharedName);
11 | internal static void Remove(string key, string sharedName) => PlatformRemove(key, sharedName);
12 | internal static string Get(string key, string? defaultValue, string sharedName) => PlatformGet(key, defaultValue, sharedName);
13 | }
14 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/VersionTracking/LegacyPreferences.windows.cs:
--------------------------------------------------------------------------------
1 | using Windows.Storage;
2 |
3 | namespace Plugin.Maui.FormsMigration;
4 |
5 | static partial class LegacyPreferences
6 | {
7 | static readonly object locker = new();
8 |
9 | static bool PlatformContainsKey(string key, string sharedName)
10 | {
11 | lock (locker)
12 | {
13 | var appDataContainer = GetApplicationDataContainer(sharedName);
14 | return appDataContainer.Values.ContainsKey(key);
15 | }
16 | }
17 |
18 | static void PlatformRemove(string key, string sharedName)
19 | {
20 | lock (locker)
21 | {
22 | var appDataContainer = GetApplicationDataContainer(sharedName);
23 | if (appDataContainer.Values.ContainsKey(key))
24 | {
25 | appDataContainer.Values.Remove(key);
26 | }
27 | }
28 | }
29 |
30 | static T PlatformGet(string key, T defaultValue, string sharedName)
31 | {
32 | lock (locker)
33 | {
34 | var appDataContainer = GetApplicationDataContainer(sharedName);
35 | if (appDataContainer.Values.ContainsKey(key))
36 | {
37 | var tempValue = appDataContainer.Values[key];
38 | if (tempValue != null)
39 | {
40 | return (T)tempValue;
41 | }
42 | }
43 | }
44 |
45 | return defaultValue;
46 | }
47 |
48 | static ApplicationDataContainer GetApplicationDataContainer(string sharedName)
49 | {
50 | var localSettings = ApplicationData.Current.LocalSettings;
51 | if (string.IsNullOrWhiteSpace(sharedName))
52 | {
53 | return localSettings;
54 | }
55 |
56 | if (!localSettings.Containers.ContainsKey(sharedName))
57 | {
58 | localSettings.CreateContainer(sharedName, ApplicationDataCreateDisposition.Always);
59 | }
60 |
61 | return localSettings.Containers[sharedName];
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/Plugin.Maui.FormsMigration/VersionTracking/LegacyVersionTracking.shared.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Maui.ApplicationModel;
2 | using Microsoft.Maui.Storage;
3 |
4 | namespace Plugin.Maui.FormsMigration;
5 |
6 | ///
7 | /// The LegacyVersionTracking API can be used to access the legacy Xamarin application version tracking information in your .NET MAUI app.
8 | ///
9 | /// Important: make sure that your .NET MAUI app version is higher than the legacy application version number. Not doing so might have unexpected results.
10 | public static class LegacyVersionTracking
11 | {
12 | static string PrivateVersionTrackingSharedNameMaui =>
13 | $"{AppInfo.Current.PackageName}.microsoft.maui.essentials.versiontracking";
14 |
15 | const string versionsKey = "VersionTracking.Versions";
16 | const string buildsKey = "VersionTracking.Builds";
17 |
18 | static readonly string sharedName = LegacyPreferences.GetPrivatePreferencesSharedName("versiontracking");
19 |
20 | static Dictionary> versionTrail = new();
21 |
22 | static string VersionsKey => versionsKey;
23 | static string BuildsKey => buildsKey;
24 | static string SharedName => sharedName;
25 |
26 | static LegacyVersionTracking()
27 | {
28 | InitVersionTracking();
29 | }
30 |
31 | ///
32 | /// Transfers the version and/or build number information from the legacy Xamarin app to the .NET MAUI Version Tracking data store.
33 | ///
34 | /// Determines whether or not version number information should be included in the transfer.
35 | /// Determines whether or not build number information should be included in the transfer.
36 | /// Determines whether or not to clear the current .NET MAUI app version history before transferring the legacy Xamarin app history.
37 | /// When not setting to , newer version/build numbers might appear before the legacy version/build number history.
38 | public static void TransferHistory(bool includeVersionInfo, bool includeBuildInfo, bool clearMauiVersionHistory)
39 | {
40 | if (clearMauiVersionHistory)
41 | {
42 | Preferences.Default.Clear(PrivateVersionTrackingSharedNameMaui);
43 | }
44 |
45 | if (includeVersionInfo)
46 | {
47 | WriteVersionTrackingHistory(VersionsKey, LegacyVersionTracking.VersionHistory);
48 | }
49 |
50 | if (includeBuildInfo)
51 | {
52 | WriteVersionTrackingHistory(BuildsKey, LegacyVersionTracking.BuildHistory);
53 | }
54 | }
55 |
56 | ///
57 | /// Initialize VersionTracking module, load data and track current version.
58 | ///
59 | ///
60 | /// For internal use. Usually only called once in production code.
61 | ///
62 | internal static void InitVersionTracking()
63 | {
64 | IsFirstLaunchEver = !LegacyPreferences.ContainsKey(versionsKey, sharedName)
65 | || !LegacyPreferences.ContainsKey(buildsKey, sharedName);
66 | if (IsFirstLaunchEver)
67 | {
68 | versionTrail = new Dictionary>
69 | {
70 | { versionsKey, new List() },
71 | { buildsKey, new List() }
72 | };
73 | }
74 | else
75 | {
76 | versionTrail = new Dictionary>
77 | {
78 | { versionsKey, ReadHistory(versionsKey).ToList() },
79 | { buildsKey, ReadHistory(buildsKey).ToList() }
80 | };
81 | }
82 |
83 | IsFirstLaunchForCurrentVersion = !versionTrail[versionsKey].Contains(CurrentVersion)
84 | || CurrentVersion != LastInstalledVersion;
85 |
86 | if (IsFirstLaunchForCurrentVersion)
87 | {
88 | // Avoid duplicates and move current version to end of list if already present
89 | versionTrail[versionsKey].RemoveAll(v => v == CurrentVersion);
90 | versionTrail[versionsKey].Add(CurrentVersion);
91 | }
92 |
93 | IsFirstLaunchForCurrentBuild = !versionTrail[buildsKey].Contains(CurrentBuild)
94 | || CurrentBuild != LastInstalledBuild;
95 |
96 | if (IsFirstLaunchForCurrentBuild)
97 | {
98 | // Avoid duplicates and move current build to end of list if already present
99 | versionTrail[buildsKey].RemoveAll(b => b == CurrentBuild);
100 | versionTrail[buildsKey].Add(CurrentBuild);
101 | }
102 | }
103 |
104 | ///
105 | /// Gets a value indicating whether this is the first time this app has ever been launched on this device.
106 | ///
107 | public static bool IsFirstLaunchEver { get; private set; }
108 |
109 | ///
110 | /// Gets a value indicating if this is the first launch of the legacy Xamarin app for the current version number.
111 | ///
112 | public static bool IsFirstLaunchForCurrentVersion { get; private set; }
113 |
114 | ///
115 | /// Gets a value indicating if this is the first launch of the legacy Xamarin app for the current version number.
116 | ///
117 | public static bool IsFirstLaunchForCurrentBuild { get; private set; }
118 |
119 | ///
120 | /// Gets the current version number of the legacy Xamarin app.
121 | ///
122 | public static string CurrentVersion => AppInfo.VersionString;
123 |
124 | ///
125 | /// Gets the current build of the legacy Xamarin app.
126 | ///
127 | public static string CurrentBuild => AppInfo.BuildString;
128 |
129 | ///
130 | /// Gets the version number for the previously run version of the legacy Xamarin app.
131 | ///
132 | public static string? PreviousVersion => GetPrevious(versionsKey);
133 |
134 | ///
135 | /// Gets the build number for the previously run version of the legacy Xamarin app.
136 | ///
137 | public static string? PreviousBuild => GetPrevious(buildsKey);
138 |
139 | ///
140 | /// Gets the version number of the first version of the app legacy Xamarin that was installed on this device.
141 | ///
142 | public static string? FirstInstalledVersion => versionTrail[versionsKey].FirstOrDefault();
143 |
144 | ///
145 | /// Gets the build number of first version of the legacy Xamarin app that was installed on this device.
146 | ///
147 | public static string? FirstInstalledBuild => versionTrail[buildsKey].FirstOrDefault();
148 |
149 | ///
150 | /// Gets the collection of version numbers of the legacy Xamarin app that ran on this device.
151 | ///
152 | public static IEnumerable VersionHistory => versionTrail[versionsKey].ToArray();
153 |
154 | ///
155 | /// Gets the collection of build numbers of the legacy Xamarin app that ran on this device.
156 | ///
157 | public static IEnumerable BuildHistory => versionTrail[buildsKey].ToArray();
158 |
159 | ///
160 | /// Determines if this is the first launch of the app for a specified version number.
161 | ///
162 | /// The version number.
163 | /// if this is the first launch of the app for the specified version number; otherwise .
164 | public static bool IsFirstLaunchForVersion(string version)
165 | => CurrentVersion == version && IsFirstLaunchForCurrentVersion;
166 |
167 | ///
168 | /// Determines if this is the first launch of the app for a specified build number.
169 | ///
170 | /// The build number.
171 | /// if this is the first launch of the app for the specified build number; otherwise .
172 | public static bool IsFirstLaunchForBuild(string build)
173 | => CurrentBuild == build && IsFirstLaunchForCurrentBuild;
174 |
175 | static string[] ReadHistory(string key)
176 | => LegacyPreferences.Get(key, null, sharedName)?.Split(new[] { '|' },
177 | StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty();
178 |
179 | static string? GetPrevious(string key)
180 | {
181 | var trail = versionTrail[key];
182 | return (trail.Count >= 2) ? trail[trail.Count - 2] : null;
183 | }
184 |
185 | static string? LastInstalledVersion => versionTrail[versionsKey].LastOrDefault();
186 |
187 | static string? LastInstalledBuild => versionTrail[buildsKey].LastOrDefault();
188 |
189 | static void WriteVersionTrackingHistory(string key, IEnumerable history)
190 | {
191 | Preferences.Default.Set(key, string.Join("|", history),
192 | PrivateVersionTrackingSharedNameMaui);
193 | }
194 | }
195 |
--------------------------------------------------------------------------------