C# , Xamarin.Essentials Secure Storage - c#

After reviewing my options regarding saving JWT token, I chose Xamarin.Essentials Secure Storage.
Problem being that my app always breaks when trying to save a token within the storage with the following error:
"System.AggregateException has been thrown"
The details are as follow:
"Xamarin.Essentials.NotImplementedInReferenceAssemblyException
This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation."
This clearly means that something went wrong in the installaion of the nuget package, so I:
Uninstalled and reinstalled the xamarin.essentials package.
Upgraded .Netstandard to 2.0, thinking that 1.6 wasn't compatible.
Checked if the package is referenced within the csproj file.
So forth, nothing.
For now, I have a TokenStorageController with the following lines of codes :
public bool SaveToken(string token)
{
if(token != null)
{
Preferences.Set(key, token);
if(Preferences.ContainsKey(key))
{
return true;
}
}
return false;
}
The RestService class from where the controller gets called looks like this :
//await SecureStorage.SetAsync("oauth_token", "booommmmmm"); // changed to this simply to check if my controller was the problem
TokenStorageController tokenStorage = new TokenStorageController();
await tokenStorage.SaveToken("boommmmm"); // where I get an error
And here is the exact line where the error occurs:
var loginTask = Task.Run(() => restService.LoginAsync(user)).Result;
If no solutions, I will remove all packages and reinstall them all. ONE BY ONE! I swear I'll do it!
And if no solutions at all, I will store the token within SQL as I already have a controller in place to do so.
I am a Xamarin and C# noob so bear with me please.
FYI: I am using a macOS client for testing purposes, as the cause could be that SecureStorage doesn't work for macOS apps.
Thanks!

Xamarin.Mac is not currently a supported platform, just iOS, Android, UWP.
The code is available for review at:
https://github.com/xamarin/Essentials/tree/master/Xamarin.Essentials/SecureStorage

Related

Is calling System.Diagnostics.Process.Start() truly problematic?

In the Validation Result that I get when readying my app for submission to the Microsoft Store (which my app "PASSED WITH WARNINGS"), I got this "Fail" under the "Package Sanity Test" section:
The code which contains such a call is:
private void myMapsHelpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://ramblingnotesofageezer.substack.com/p/map-o-matic-overview");
}
I am using that code due to the recommendation to do so here. How do I start a process from C#?
Is this truly a problem? If so, what should I use instead of the call to System.Diagnostics.Process.Start()?
I find it odd that it is classified as a failed part of the test, yet the overall results are that my app passed (albeit with warnings).
UPDATE
I checked out the link in the comment from Codexer, where it says, "Starting a utility can often provide a convenient way to obtain information from the operating system, access the registry, or access system capabilities. However, you can use UWP APIs to accomplish these sorts of tasks instead."
If this is the solution, do the UWP APIs have an equivalent to System.Diagnostics.Process.Start()?
UPDATE 2
I followed the steps in the answer, but the solution still doesn't compile, due to an error with this line of code:
await Windows.System.Launcher.LaunchUriAsync(uri);
In fact, even when I comment out the offending line, the project will no longer compile, but doesn't give me any information about how to solve the problem, just this:
I set the Package Management Format to PackageReference, and installed version 10.0.18362.2005 of Microsoft.Windows.SDK.Contracts, but it is complaining about needing a package reference...?!? I tried adding using Windows.System;
and using Microsoft.Windows.SDK.Contracts; but neither is recognized.
The package is installed for the project, as you can see here:
UPDATE 3
Regarding the "Must Use Package Reference" err msg, I have three questions revolving around what I see here:
The verbiage below Microsoft.Windows.SDK.Contracts says I can update versions of this package - should I?
I do not see a Reference to Microsoft.Windows.SDK.Contracts in my project's References, although it has been installed. Do I need to add one - if so, from where?
The context menu on my References affords me the ability to "Migrate packages.config to PackageReference..." should I do that?
If you were developing an uwp application, for opening open a web uri, it is recommended to use Launcher.LaunchUriAsync(Uri) method instead, this method starts the default browser to open the specified URI.
For example:
private async void button_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("http://www.google.com");
await Windows.System.Launcher.LaunchUriAsync(uri);
}
Update:
As Codexer mentioned, you could refer to this document to use uwp api in winform app.
I have created a winform project, its target framework is .Net Framework4.8. For earlier versions of .NET(.NET Core 3.x, .NET 5 Preview 7 (or earlier), or .NET Framework), you could refer to my steps.
1.Click Tools->NuGet Package Manager-> Package Manager Settings-> Change Default package management format to PackageReference. As follows:
2.Install the Microsoft.Windows.SDK.Contracts package, note that you need to install the appropriate version. Please check the corresponding version below. (Installation details: Right click Reference-> Manage NuGet Packages->Browse->Search Microsoft.Windows.SDK.Contracts->install)
10.0.19041.xxxx: Choose this for Windows 10, version 2004, version 20H2
10.0.18362.xxxx: Choose this for Windows 10, version 1903.
10.0.17763.xxxx: Choose this for Windows 10, version 1809.
10.0.17134.xxxx: Choose this for Windows 10, version 1803.
3.Run the project

Base Code Issues (?) with ASP.NET Core OAuth

I'm using the ASP.NET Core Authentication.OAuth package (version 2.2.0) to develop middleware for a unique authentication flow in my web app. I am using .NET Core 3.1. I'm running into several issues where it seems that there are constructors/methods missing from the package's base code, creating missing method exceptions that I cannot resolve (for example, this exception, which I've gotten around but haven't truly resolved: "MissingMethodException: Method not found: 'Void Microsoft.AspNetCore.Authentication.OAuth.OAuth CreatingTicketContext..ctor" which I got when trying to instantiate an OnCreatingTicketContext object). I've tried uninstalling and re-installing the OAuth package, so I don't believe it's a problem with my specific installation. Although I've managed to work around some of these errors, I'm presently unable to instantiate new OAuthTokenResponse objects in my extended OAuthHandler class.
Calling OAuthTokenResponse.Success(response) produces a missing method exception ("Method not found: 'Microsoft.AspNetCore.Authentication.OAuth.OAuthTokenResponse Microsoft.AspNetCore.Authentication.OAuth.OAuthTokenResponse.Success(Newtonsoft.Json.Linq.JObject)'"). If I try to directly specify each of the object's fields (as below), I am met with another error: "'OAuthTokenResponse' does not contain a constructor that takes 0 arguments".
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var result = new OAuthTokenResponse()
{
Response = payload,
AccessToken = payload.Value<string>("access_token"),
TokenType = payload.Value<string>("token_type"),
RefreshToken = payload.Value<string>("refresh_token"),
ExpiresIn = payload.Value<string>("expires_in")
};
Indeed, it seems from the class definition that there is no constructor defined taking any number of arguments, though I suspect that it exists and just isn't accessible, so maybe that's to be expected. Whatever the case may be, I don't know what to do and I can't tell whether it's something I'm doing wrong or it's a problem with the package itself. Any insights?
This problem sprouted from having multiple references to the same set of packages. I had not realized that ASP.NET Core versions after 2.2 were not referenced by inclusion of Nuget packages and that the .NET Core 3.1 framework supplied the most recent versions. I uninstalled/deleted references to the version 2.2 packages and the problem vanished.

Stores and C# assembly dll files not being loaded

I have recently tried adding In App Purchase into my Unity project. Unfortunately, it didn't show in the Components drop down menu. I could use the option to create IAP Button and perform code-less IAP configuration but it wasn't there in the menu. So I decided to configure IAP through script. But the script too throws some errors. The error goes like this:
"Assembly 'Library/ScriptAssemblies/Assembly-CSharp-firstpass.dll' will not be loaded due to errors: Reference has errors 'Stores'."
Four errors just like the above one shows up for Assembly-CSharp.dll, Editor.dll and Assembly-CSharp-firstpass.dll
And then this one:
"Assembly 'Assets/Plugins/UnityPurchasing/Bin/Stores.dll' will not be loaded due to errors:
Unable to resolve reference 'UnityEngine.UI'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector."
I have tried re-installing In App Purchase package.
I have tried changing the API from .NET Standard 2.0 to .NET 4.x (and did the vice versa and still did not work)
Downgrading unity project isn't really a good idea but anyways I gave it a try but it just added to the already existing errors.
Upgrading to newer Unity version (alpha version) didn't help.
The error occurs whenever I initialize the ConfigurationBuilder referring StandardPurchasingModule.
public void InitializePurchasing()
{
// If we have already connected to Purchasing ...
if (IsInitialized())
{
// ... we are done here.
return;
}
var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
builder.AddProduct(TWO_BOLTS, ProductType.Consumable);
builder.AddProduct(FIVE_BOLTS, ProductType.NonConsumable);
UnityPurchasing.Initialize(this, builder);
}
The worst part is that I am unable to use my scripts after writing the ConfigurationBuilder initialization code. Unity asks me to fix any compiler errors and assign a valid script. I have searched for the answer for so long. I am really stuck in here. Please help.
Your issue seems to be related to verison of Unity you using. You can follow progress of this issue on official Unity issue tracker.
If this issue is showstopper for you than cosider downgrading as you using beta verions of Unity and as official site states:
As with any beta program, you’ll have early access to new features and
will be able to assist in the final steps of their development. That
means you’re likely to experience Unity as less stable than a final
version.

SQLite removing reference on rebuild

SQL Lite states that its added support for Xamrian Forms and .net standard and yet when I rebuild my project all references disappear what it the correct library I need to get SQL lite working in .net standard 2.0 I am using it to sync between a mobile app and the server.
public async Task SyncAllDeliverys()
{
Task<string> callTask = Task.Run(() => GetDeliverysFromAPi());
// Wait for it to finish
callTask.Wait();
// Get the result
string content = callTask.Result;
//Sends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation
deliverysItems = JsonConvert.DeserializeObject<List<DeliverysItems>>(content); //Deserializes or converts JSON String into a collection of Post
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(dbPath);
await conn.InsertAllAsync(deliverysItems);
}
As you see here my project is .net standard 2.0
Edit 2
To show the correct version that I have installed instead of the incorrect one I showed in the first graphic.
Edit 2
It would appear that this is a known bug and xamrian has submitted it as such in 2019 visual studio.
https://github.com/xamarin/Xamarin.Forms/issues/5983
You are looking at the wrong description of dependencies. The dependencies in the first screenshot(you circled in the right bottom) belongs to sqlite-net-pcl instead of SQLite.Net-PCL.
Package 'SQLite.Net-PCL 3.1.1' was restored using
'.NETFramework,Version=v4.6.1'.
You can try uninstall and install sqlite-net-pcl nuget, clean and rebuild your project.
what it the correct library I need to get SQL lite working in .net
standard 2.0
Use sqlite-net-pcl is the right way. (The fourth library in your screenshot).
There are a number of NuGet packages with similar names, the correct package has these attributes:
Created by: Frank A. Krueger
Id: sqlite-net-pcl
NuGet link: sqlite-net-pcl
Refer: databases

Ninject Portable in Xamarin results in NotImplementedException

When I use Portable.Ninject in a Xamarin.Forms app, instantiating the StandardKernel always results in a NotImplementedException.
I can consistently replicate the problem as follows:
Create Xamarin.Forms application (in VS2017: Cross Platform App (Xamarin))
Configure it to use PCL
I'm only interested in Android and for the sake of brevity, I removed all other platform projects.
Add NuGet Package Portable.Ninject to the PCL and Android platforms
Then, in App.xaml.cs I simply try the following:
public App()
{
InitializeComponent();
//ommitting NinjectModules for brevity
var kernel = new Ninject.StandardKernel(); //exception is thrown here
MainPage = new NavigationPage(new MainView());
}
What am I missing here?
Currently I'm using Portable.Ninject version 3.3.1.
I also tried the XLabs.IoC.Ninject package (which also uses Portable.Ninject) and got the same result.
For those who experience the same problem:
tldr; clean you projects, and rebuild.
Explanation: At first I had only added Ninject to my PCL, and had forgotten to add it to the Android project. Although I added the Ninject library to the Android project soon afterwards, it would still result in the exception being thrown.
The solution was to clean the projects and rebuild them. Sometimes it's just that easy!

Categories