I can not figure out why it is returning this error, I am beginning to think that there is some bug in Visual Studio for Mac that keeps something in memory, I have dumped the Bin and obj folders and that did not make a difference I have all my packages up to date.
Stack Trace...
System.InvalidCastException: Specified cast is not valid.
at at (wrapper castclass) System.Object:__castclass_with_cache (object,intptr,intptr)
at Xamarin.Forms.Internals.Registrar1[TRegistrable].GetHandler (System.Type type) [0x0001b] in D:\agent_work\2\s\Xamarin.Forms.Core\Registrar.cs:37 at Xamarin.Forms.Internals.Registrar1[TRegistrable].GetHandlerForObject[TOut] (System.Object obj) [0x0002c] in D:\agent_work\2\s\Xamarin.Forms.Core\Registrar.cs:81
at Xamarin.Forms.Platform.iOS.Platform.CreateRenderer (Xamarin.Forms.VisualElement element) [0x00005] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.OnChildAdded (Xamarin.Forms.VisualElement view) [0x0002a] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.Load () [0x0001e] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementRenderer1[TElement].SetElement (TElement element) [0x000cc] in <9a5948fff8254b13a3d593c76c73b9b1>:0 at Xamarin.Forms.Platform.iOS.VisualElementRenderer1[TElement].Xamarin.Forms.Platform.iOS.IVisualElementRenderer.SetElement (Xamarin.Forms.VisualElement element) [0x00000] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.Platform.CreateRenderer (Xamarin.Forms.VisualElement element) [0x00014] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.OnChildAdded (Xamarin.Forms.VisualElement view) [0x0002a] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.Load () [0x0001e] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementRenderer1[TElement].SetElement (TElement element) [0x000cc] in <9a5948fff8254b13a3d593c76c73b9b1>:0 at Xamarin.Forms.Platform.iOS.VisualElementRenderer1[TElement].Xamarin.Forms.Platform.iOS.IVisualElementRenderer.SetElement (Xamarin.Forms.VisualElement element) [0x00000] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.Platform.CreateRenderer (Xamarin.Forms.VisualElement element) [0x00014] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.OnChildAdded (Xamarin.Forms.VisualElement view) [0x0002a] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.Load () [0x0001e] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.PageRenderer.ViewDidLoad () [0x00086] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at at (wrapper managed-to-native) ObjCRuntime.Messaging:IntPtr_objc_msgSendSuper (intptr,intptr)
at UIKit.UIViewController.get_View () [0x00030] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/build/ios/native/UIKit/UIViewController.g.cs:2983
at Xamarin.Forms.Platform.iOS.PageRenderer.get_NativeView () [0x00008] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.PageRenderer.SetElement (Xamarin.Forms.VisualElement element) [0x0004f] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.Platform.CreateRenderer (Xamarin.Forms.VisualElement element) [0x00014] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.NavigationRenderer.CreateViewControllerForPage (Xamarin.Forms.Page page) [0x00008] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.NavigationRenderer+d__45.MoveNext () [0x00016] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
at Xamarin.Forms.Platform.iOS.NavigationRenderer+d.MoveNext () [0x00067] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1018
at UIKit.UIKitSynchronizationContext+c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/UIKit/UIKitSynchronizationContext.cs:24
at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/Foundation/NSAction.cs:163
at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/UIKit/UIApplication.cs:79
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/UIKit/UIApplication.cs:63
at EssentialsProMobile.iOS.Application.Main (System.String[] args) [0x00001] in /Users/odisharkins/Projects/EssentialsProMobile/iOS/Main.cs:17
This is the MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SignaturePadDemo"
xmlns:signatures="clr-namespace:SignaturePad.Forms;assembly=SignaturePad.Forms"
x:Class="EssentialsProMobile.MainPage"
Title="Draw Signature">
<Grid Padding="20" RowSpacing="20">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<signatures:SignaturePadView
x:Name="signaturePad"
VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
Grid.Row="0" />
<Button
HorizontalOptions="FillAndExpand"
Text="Show Image"
Clicked="OnShowImage"
Grid.Row="1" />
</Grid>
MainPage.xaml.cs
using System;
using Xamarin.Forms;
using SignaturePad.Forms;
using PCLStorage;
namespace EssentialsProMobile
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void OnShowImage(object sender, EventArgs e)
{
// get the file name
var folder = FileSystem.Current.LocalStorage;
var file = await folder.CreateFileAsync($"signature.jpg", CreationCollisionOption.GenerateUniqueName);
// create some settings to control the output
var settings = new ImageConstructionSettings
{
BackgroundColor = Color.White,
StrokeColor = Color.Black,
};
// write the signature stream to the file stream
using (var stream = await signaturePad.GetImageStreamAsync(SignatureImageFormat.Jpeg, settings))
using (var fileStream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
// copy the bytes
await stream.CopyToAsync(fileStream);
}
// success
await DisplayAlert("Signature Saved", "Signature file saved successfully.\nLoading preview...", "OK");
// show the image preview
var previewPage = new ContentPage
{
Title = "View Signature",
Content = new Image
{
Source = ImageSource.FromFile(file.Path),
Margin = new Thickness(20)
}
};
await Navigation.PushAsync(previewPage);
}
}
}
And the App.xaml.cs
namespace EssentialsProMobile
{
public partial class App : Application
{
readonly Services.IAuthenticationService _AuthenticationService;
static Application app;
static Data.EssentialsProDatabase database;
public static Application CurrentApp
{
get { return app; }
}
public App()
{
InitializeComponent();
app = this;
_AuthenticationService = DependencyService.Get<Services.IAuthenticationService>();
// If the App.IsAuthenticated property is false, modally present the SplashPage.
if (!_AuthenticationService.IsAuthenticated)
{
//Load Login Page
var page = new SplashPage();
//Testing....
//var page = new Services.SignaturePadView();
NavigationPage.SetHasNavigationBar(page, false);
MainPage = new NavigationPage(new MainPage());
}
else
{
GoToRoot();
}
Related
I am trying to use AzureAD (mono only) to authenticate as an AD app-user to make requests to SharePoint.
The Azure AD app user basically requires you provide [clientID, certificate path, certificate password].
The following code works on Windows:
string siteUrl = "https://xxxxxxx.sharepoint.com";
string clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx";
string domain = "xxxxxxx.onmicrosoft.com";
string certificatePath = "/path/to/xxxxxxx.pfx";
string certificatePassword = "xxxxxxx";
using (var cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteUrl, clientId, domain, certificatePath, certificatePassword)) {
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
};
But on Mono you get this error:
System.Security.Cryptography.CryptographicException: Keyset does not exist
Seems to be related to:
https://bugzilla.xamarin.com/show_bug.cgi?id=57691
https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/509
But these are supposedly fixed, yet I'm still having these problems.
Full error stack:
System.Security.Cryptography.CryptographicException: Keyset does not exist
at System.Security.Cryptography.RSACryptoServiceProvider.Common (System.Security.Cryptography.CspParameters p) [0x00039] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Security.Cryptography.RSACryptoServiceProvider..ctor (System.Int32 dwKeySize, System.Security.Cryptography.CspParameters parameters) [0x0001d] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Security.Cryptography.RSACryptoServiceProvider..ctor (System.Security.Cryptography.CspParameters parameters) [0x00000] in <bb7b695b8c6246b3ac1646577aea7650>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.CryptographyHelper.GetCryptoProviderForSha256 (System.Security.Cryptography.RSACryptoServiceProvider rsaProvider) [0x0007e] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.CryptographyHelper.SignWithCertificate (System.String message, System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate) [0x0001b] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate.Sign (System.String message) [0x00007] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.JsonWebToken.Sign (Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate credential) [0x0002b] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.RequestParameters.AddClientKey (Microsoft.IdentityModel.Clients.ActiveDirectory.ClientKey clientKey) [0x000b7] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.RequestParameters..ctor (System.String resource, Microsoft.IdentityModel.Clients.ActiveDirectory.ClientKey clientKey) [0x0001a] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase+<SendTokenRequestAsync>d__9.MoveNext () [0x00024] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <bb7b695b8c6246b3ac1646577aea7650>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase+<RunAsync>d__0.MoveNext () [0x004f3] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask[T] (System.Threading.Tasks.Task`1[TResult] task) [0x00031] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireToken (System.String resource, Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate clientCertificate) [0x00014] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at pnp_test_2.Program.Main (System.String[] args) [0x000a8] in <8c5b1bd4cf9047a3868c8cacd6143dd1>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.Security.Cryptography.CryptographicException: Keyset does not exist
at System.Security.Cryptography.RSACryptoServiceProvider.Common (System.Security.Cryptography.CspParameters p) [0x00039] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Security.Cryptography.RSACryptoServiceProvider..ctor (System.Int32 dwKeySize, System.Security.Cryptography.CspParameters parameters) [0x0001d] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Security.Cryptography.RSACryptoServiceProvider..ctor (System.Security.Cryptography.CspParameters parameters) [0x00000] in <bb7b695b8c6246b3ac1646577aea7650>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.CryptographyHelper.GetCryptoProviderForSha256 (System.Security.Cryptography.RSACryptoServiceProvider rsaProvider) [0x0007e] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.CryptographyHelper.SignWithCertificate (System.String message, System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate) [0x0001b] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate.Sign (System.String message) [0x00007] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.JsonWebToken.Sign (Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate credential) [0x0002b] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.RequestParameters.AddClientKey (Microsoft.IdentityModel.Clients.ActiveDirectory.ClientKey clientKey) [0x000b7] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.RequestParameters..ctor (System.String resource, Microsoft.IdentityModel.Clients.ActiveDirectory.ClientKey clientKey) [0x0001a] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase+<SendTokenRequestAsync>d__9.MoveNext () [0x00024] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <bb7b695b8c6246b3ac1646577aea7650>:0
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <bb7b695b8c6246b3ac1646577aea7650>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase+<RunAsync>d__0.MoveNext () [0x004f3] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask[T] (System.Threading.Tasks.Task`1[TResult] task) [0x00031] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireToken (System.String resource, Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate clientCertificate) [0x00014] in <211fb7a0ce9049e5a2768849f2fd6a88>:0
at pnp_test_2.Program.Main (System.String[] args) [0x000a8] in <8c5b1bd4cf9047a3868c8cacd6143dd1>:0
How can I authenticate with Azure AD app-only accounts + pfx key on mono?
See my comment here: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/509
I have gotten the work-around to work for SharePoint Online now:
You can remove the CorePNP library if you want. But do not use the OfficeDevPnP.Core.AuthenticationManager for Linux because it won't work! That library does work great for Windows however.
Add nuget dependencies:
Microsoft.IdentityModel.Clients.ActiveDirectory
Microsoft.IdentityModel.Tokens
c# code to get a client context with the auth correctly:
using System;
using System.Text;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using Microsoft.SharePoint.Client;
namespace PnpTest {
class ClientAssertionCertificate : IClientAssertionCertificate {
X509Certificate2 certificate;
public string ClientId { get; private set; }
public string Thumbprint {
get {
return Base64UrlEncoder.Encode(certificate.GetCertHash());
}
}
public ClientAssertionCertificate(string clientId, X509Certificate2 certificate) {
ClientId = clientId;
this.certificate = certificate;
}
public byte[] Sign(string message) {
using (var key = certificate.GetRSAPrivateKey()) {
return key.SignData(Encoding.UTF8.GetBytes(message), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
}
}
class Program {
static void Main(string[] args) {
string siteUrl = "https://xxxxxxxxxxxxxxx.sharepoint.com";
string clientId = "xxxxxxxxxxxxxxx";
string tenant = "xxxxxxxxxxxxxxx.onmicrosoft.com";
string certificatePath = "resources/xxxxxxxx.pfx";
string certificatePassword = "xxxxxxxx";
var certfile = System.IO.File.OpenRead(certificatePath);
var certificateBytes = new byte[certfile.Length];
certfile.Read(certificateBytes, 0, (int)certfile.Length);
var certificate = new X509Certificate2(
certificateBytes,
certificatePassword,
X509KeyStorageFlags.Exportable |
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet);
var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate);
string authority = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/", "https://login.windows.net", tenant);
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
var host = new Uri(siteUrl);
using (var clientContext = new ClientContext(siteUrl)) {
clientContext.ExecutingWebRequest += (sender, webRequestArgs) => {
var arFuture = authContext.AcquireTokenAsync(host.Scheme + "://" + host.Host + "/", clientAssertionCertificate);
var ar = arFuture.Result;
webRequestArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ar.AccessToken;
};
clientContext.Load(clientContext.Web, p => p.Title);
clientContext.ExecuteQuery();
Console.WriteLine(clientContext.Web.Title);
}
}
}
}
In Xamarin.Forms:
I have a ListView which is being populated with certain objects. In each of the rows of the ListView I also have a Switch, which the user can use to select or deselect that item.
My problem is that I can't figure out how to pass the specific item in the ListView to the toggled event of the Switch, so that the users' preferences can then be saved.
i.e. How does each Switch know which object it shares a row with in the ListView? (In the code below, the objects I am trying to pass are the Survey objects.)
What I found so far:
I have found this question which is exactly what I am after, but I can't quite understand the answer:
https://forums.xamarin.com/discussion/64197/switch-inside-listview-get-listview-item-on-toggle
Following the post above, I have tried the following:
Extended the Switch class:
public class ListSwitch : Switch
{
public static BindableProperty SurveyItemProperty = BindableProperty.Create(
propertyName: "SurveyItem",
returnType: typeof(Survey),
declaringType: typeof(ListSwitch),
defaultValue: null);
public Survey SurveyItem
{
get { return (Survey)GetValue(SurveyItemProperty); }
set { SetValue(SurveyItemProperty, value); }
}
}
Added this to my View codebehind:
mySwitch.SetBinding(ListSwitch.SurveyItemProperty, "SurveyItem");
mySwitch.Toggled += (sender, e) =>
{
var item = (Survey)((ListSwitch)sender).SurveyItem;
_vm.WatchSurveyCommand.Execute(item);
};
When I try this I get the following error:
System.NullReferenceException: Object reference not set to an instance of an object
at ConsensusCloud.MainViewModel+<ExecuteWatchSurveyCommand>c__async1.MoveNext () [0x00033] in /Users/Lambros/Dropbox/XamarinProjects/ConsensusCloud/ConsensusCloud/ViewModels/MainViewModel.cs:65
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113
at ConsensusCloud.MainViewModel+<>c__async6.MoveNext () [0x00021] in /Users/Lambros/Dropbox/XamarinProjects/ConsensusCloud/ConsensusCloud/ViewModels/MainViewModel.cs:57
at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/src/UIKit/UIApplication.cs:79
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/src/UIKit/UIApplication.cs:63
at ConsensusCloud.iOS.Application.Main (System.String[] args) [0x00008] in /Users/Lambros/Dropbox/XamarinProjects/ConsensusCloud/iOS/Main.cs:17
What is "SurveyItem"? It would have to be a public property on the individual items that are contained in your list's ItemsSource. If you want to access the current item, just bind to ".", which is the current item.
In ListView, the binding context for the template that is used for the items, is the currently processed item. See the documentation for more details on this topic.
I'm trying to add Realm to my app (Xamarin Android). Starting with emulator first (Xaamrin android player - Nexus 5 with Android Lollipop).
Github Issue here
My code:
protected override async void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.MyActivitylayout);
....
try
{
var path = AndroidIoHelper.CreateFileInAppFolder(AndroidIoHelper.GetAppDataFolder(), "tlm_db", "realm");
var realm = Realm.GetInstance(path);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
.......
}
Exception I'm getting:
Realms.RealmFileAccessErrorException: Operation not permitted at
Realms.NativeCommon.ExceptionThrower (IntPtr exceptionCode, IntPtr
utf8String, IntPtr stringLen) [0x0003b] in :0 at
(wrapper native-to-managed) Realms.NativeCommon:ExceptionThrower
(intptr,intptr,intptr) at (wrapper managed-to-native)
Realms.NativeSharedRealm:open
(Realms.SchemaHandle,string,intptr,intptr,intptr,byte[],ulong) 05-15
12:57:18.384 I/mono-stdout( 5250):
Realms.RealmFileAccessErrorException: Operation not permitted 05-15
12:57:18.384 I/mono-stdout( 5250): at
Realms.NativeCommon.ExceptionThrower (IntPtr exceptionCode, IntPtr
utf8String, IntPtr stringLen) [0x0003b] in :0 05-15
12:57:18.384 I/mono-stdout( 5250): at (wrapper native-to-managed)
Realms.NativeCommon:ExceptionThrower (intptr,intptr,intptr) 05-15
12:57:18.385 I/mono-stdout( 5250): at (wrapper managed-to-native)
Realms.NativeSharedRealm:open
(Realms.SchemaHandle,string,intptr,intptr,intptr,byte[],ulong) 05-15
12:57:18.385 I/mono-stdout( 5250): at Realms.Realm.GetInstance
(Realms.RealmConfiguration config) [0x0010c] in :0
05-15 12:57:18.385 I/mono-stdout( 5250): at Realms.Realm.GetInstance
(System.String databasePath) [0x00019] in :0 05-15
12:57:18.385 I/mono-stdout( 5250): at
MyApp.Activities.SplashScreenActivity+d__4.MoveNext ()
[0x00116] in
C:\Users***\Source\Repos\AppName\MyApp\Activities\SplashScreenActivity.cs:66
at Realms.Realm.GetInstance (Realms.RealmConfiguration config)
[0x0010c] in :0 at Realms.Realm.GetInstance
(System.String databasePath) [0x00019] in :0 at
MyApp.Activities.SplashScreenActivity+d__4.MoveNext ()
[0x00116] in
C:\Users***\Source\Repos\AppName\MyApp\Activities\SplashScreenActivity.cs:66
If I don't specify path I'm getting (var realm = Realm.GetInstance();):
System.ArgumentNullException: Value cannot be null. Parameter name:
type at System.Activator.CreateInstance (System.Type type, Boolean
nonPublic) [0x00006] in
/Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/mscorlib/system/activator.cs:205
05-15 13:05:05.257 I/mono-stdout( 5474): System.ArgumentNullException:
Value cannot be null. 05-15 13:05:05.257 I/mono-stdout( 5474):
Parameter name: type 05-15 13:05:05.257 I/mono-stdout( 5474): at
System.Activator.CreateInstance (System.Type type, Boolean nonPublic)
[0x00006] in
/Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/mscorlib/system/activator.cs:205
05-15 13:05:05.257 I/mono-stdout( 5474): at
System.Activator.CreateInstance (System.Type type) [0x00000] in
/Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/mscorlib/system/activator.cs:147
at System.Activator.CreateInstance (System.Type type) [0x00000] in
/Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/mscorlib/system/activator.cs:147
at Realms.Realm.CreateRealmObjectMetadata (System.Type
realmObjectType) [0x0001e] in :0 at
System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement]
(IEnumerable1 source, System.Func2 keySelector, System.Func2
elementSelector, IEqualityComparer1 comparer) [0x0004d] in
/Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/System.Core/System/Linq/Enumerable.cs:855
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement]
(IEnumerable1 source, System.Func2 keySelector, System.Func2
elementSelector) [0x00000] in
/Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/System.Core/System/Linq/Enumerable.cs:847
at Realms.Realm..ctor (Realms.SharedRealmHandle sharedRealmHandle,
Realms.RealmConfiguration config) [0x00037] in <filename unknown>:0
at Realms .Realm.GetInstance (Realms.RealmConfiguration config)
[0x00171] in <filename unknown>:0 at
MyApp.Activities.SplashScreenActivity+<OnCreate>d__4.MoveNext ()
[0x00116] in
C:\Users\***\Source\Repos\AppName\MyApp\Activities\SplashScreenActivity.cs:66
05-15 13:05:05.257 I/mono-stdout( 5474): at
Realms.Realm.CreateRealmObjectMetadata (System.Type realmObjectType)
[0x0001e] in <filename unknown>:0 05-15 13:05:05.257 I/mono-stdout(
5474): at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement]
(IEnumerable1 source, System.Func2 keySelector, System.Func2
elementSelector, IEqualityComparer1 comparer) [0x0004d] in
/Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/System.Core/System/Linq/Enumerable.cs:855
05-15 13:05:05.257 I/mono-stdout( 5474): at
System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement]
(IEnumerable1 source, System.Func2 keySelector, System.Func2
elementSelector) [0x00000] in
/Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/System.Core/System/Linq/Enumerable.cs:847
05-15 13:05:05.257 I/mono-stdout( 5474): at Realms.Realm..ctor
(Realms.SharedRealmHandle sharedRealmHandle, Realms.RealmConfiguration
config) [0x00037] in :0 05-15 13:05:05.257
I/mono-stdout( 5474): at Realms.Realm.GetInstance
(Realms.RealmConfiguration config) [0x00171] in :0
05-15 13:05:05.257 I/mono-stdout( 5474): at
MyApp.Activities.SplashScreenActivity+d__4.MoveNext ()
[0x00116] in
C:\Users***\Source\Repos\AppName\MyApp\Activities\SplashScreenActivity.cs:66
The app has Write external storage permission.
Realm and Fody nuget packages installed properly, Fody weavers are present as expected..
It also crashes with same exception using HTC One X with Android 4.2
The above attempt had other issues. There is a real bug currently in Realm with storage on external storage - see the issue https://github.com/realm/realm-dotnet/issues/554 which is proving awkward to debug.
From this code a Null exception is throw and I'm pusled as to why that is. The line that throws the NullReferenceException is this one,
if (await dbConn.FindAsync<ShoppingList>(x => x.Name == insertedList.Name) != null)
Here is the whole method:
public async Task<string> SaveSingleShoppingList(IShoppingList shoppingList)
{
try
{
var dbConn = new SQLiteAsyncConnection(dbPath);
ShoppingList insertedList = (ShoppingList)shoppingList;
await SaveGroceries(shoppingList.Groceries, shoppingList.Name, dbConn);
if(await dbConn.FindAsync<ShoppingList>(x => x.Name == insertedList.Name) != null)
await dbConn.UpdateAsync(insertedList);
else
await dbConn.InsertAsync(insertedList);
return "Shopping list Saved!";
}
catch (SQLiteException ex)
{
return ex.Message;
}
catch(NullReferenceException nre)
{
return nre.Message;
}
}
Below is the full extent of the exception message
{System.NullReferenceException: Object reference not set to an
instance of an object at
SQLite.TableQuery1[ShoppingAssistant.ShoppingList].CompileExpr
(System.Linq.Expressions.Expression expr,
System.Collections.Generic.List1 queryArgs) [0x00000] in :0
at SQLite.TableQuery1[ShoppingAssistant.ShoppingList].CompileExpr
(System.Linq.Expressions.Expression expr,
System.Collections.Generic.List1 queryArgs) [0x00000] in :0
at
SQLite.TableQuery1[ShoppingAssistant.ShoppingList].GenerateCommand
(System.String selectionList) [0x00000] in <filename unknown>:0 at
SQLite.TableQuery1[ShoppingAssistant.ShoppingList].GetEnumerator ()
[0x00000] in :0
at
System.Collections.Generic.List1[ShoppingAssistant.ShoppingList].AddEnumerable
(IEnumerable1 enumerable) [0x00000] in :0
at
System.Collections.Generic.List1[ShoppingAssistant.ShoppingList]..ctor
(IEnumerable1 collection) [0x00000] in :0
at System.Linq.Enumerable.ToList[ShoppingList] (IEnumerable`1
source) [0x00000] in :0
at
SQLite.TableQuery`1[ShoppingAssistant.ShoppingList].FirstOrDefault ()
[0x00000] in :0
at SQLite.SQLiteConnection.Find[ShoppingList]
(System.Linq.Expressions.Expression`1 predicate) [0x00000] in
:0
at
SQLite.SQLiteAsyncConnection+c__AnonStorey7`1[ShoppingAssistant.ShoppingList].<>m__0
() [0x00000] in :0
at
System.Threading.Tasks.TaskActionInvoker+FuncInvoke`1[ShoppingAssistant.ShoppingList].Invoke
(System.Threading.Tasks.Task owner, System.Object state,
System.Threading.Tasks.Task context) [0x00000] in :0
at System.Threading.Tasks.Task.InnerInvoke () [0x00000] in :0 at System.Threading.Tasks.Task.ThreadStart () [0x00000]
in :0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ()
[0x00000] in :0 at
System.Runtime.CompilerServices.TaskAwaiter`1[ShoppingAssistant.ShoppingList].GetResult
() [0x00000] in :0 at
ShoppingAssistant.SQLiteDataAcces+d__2d.MoveNext
() [0x0009d] in
c:\Users\kaj\Desktop\dbTest\dbTest\SQLiteDataAcces.cs:187
} System.NullReferenceException
I have a storyboard. Because I load a view in code (depending on conditions) I haven't used the segue anymore. Now I want to load another view but I'm getting the following error:
System.Reflection.TargetInvocationException was thrown
Exception has been thrown by the target of an invocation.
ListButton.TouchUpInside += (object sender, EventArgs e) => {
MyListController myListController = this.Storyboard.InstantiateViewController ("MyListController") as MyListController;
myListController.EdgesForExtendedLayout = UIRectEdge.None;
if (myListController != null) {
this.NavigationController.PushViewController (myListController, true);
}
};
When the button (ListButton) is pressed the view should be loaded onto the navigation stack. The error occurs with InstantiateViewController.
How can I solve that?
Edit:
I went into MyListController and if I comment the following out the view gets loaded:
public MyListController (IntPtr handle) : base (handle)
{
TableView.RegisterClassForCellReuse (typeof(UITableViewCell), listCellId);
TableView.Source = new MyListDataSource (this);
MyList = new List<string> ();
}
Log:
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.Exception: Object
reference not set to an instance of an object at
TestApp.MyListController.ViewDidLoad () [0x0004c] in
/Users/xxx/Projects/TestApp/TestApp/TestApp/MyListController.cs:78
at at (wrapper managed-to-native)
MonoTouch.ObjCRuntime.Messaging:IntPtr_objc_msgSendSuper
(intptr,intptr) at
MonoTouch.UIKit.UITableViewController.get_TableView () [0x00000] in
:0 at TestApp.MyListController..ctor (IntPtr
handle) [0x00009] in
/Users/xxx/Projects/TestApp/TestApp/TestApp/MyListController.cs:17
at at (wrapper managed-to-native)
System.Reflection.MonoCMethod:InternalInvoke
(System.Reflection.MonoCMethod,object,object[],System.Exception&) at
System.Reflection.MonoCMethod.InternalInvoke (System.Object obj,
System.Object[] parameters) [0x00002] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:537
--- End of inner exception stack trace --- at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj,
System.Object[] parameters) [0x00016] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:543
at System.Reflection.MonoCMethod.DoInvoke (System.Object obj,
BindingFlags invokeAttr, System.Reflection.Binder binder,
System.Object[] parameters, System.Globalization.CultureInfo culture)
[0x00095] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:528
at System.Reflection.MonoCMethod.Invoke (BindingFlags invokeAttr,
System.Reflection.Binder binder, System.Object[] parameters,
System.Globalization.CultureInfo culture) [0x00000] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:556
at System.Reflection.ConstructorInfo.Invoke (System.Object[]
parameters) [0x00000] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/ConstructorInfo.cs:62
at MonoTouch.ObjCRuntime.Runtime.ConstructNSObject[NSObject] (IntPtr
ptr, System.Type type, MissingCtorResolution missingCtorResolution)
[0x00000] in :0 at
MonoTouch.ObjCRuntime.Runtime.ConstructNSObject (IntPtr ptr, IntPtr
klass, MissingCtorResolution missingCtorResolution) [0x00000] in
:0 at MonoTouch.ObjCRuntime.Runtime.GetNSObject
(IntPtr ptr, MissingCtorResolution missingCtorResolution) [0x00000] in
:0 at MonoTouch.ObjCRuntime.Runtime.GetNSObject
(IntPtr ptr) [0x00000] in :0 at
MonoTouch.UIKit.UIStoryboard.InstantiateViewController (System.String
identifier) [0x00000] in :0 at
TestApp.StartScreenViewController.m__1 (System.Object
sender, System.EventArgs e) [0x0000c] in
/Users/xxx/Projects/TestApp/TestApp/TestApp/StartScreenViewController.cs:57
at MonoTouch.UIKit.UIControlEventProxy.Activated () [0x00000] in
:0 at at (wrapper managed-to-native)
MonoTouch.UIKit.UIApplication:UIApplicationMain
(int,string[],intptr,intptr) at MonoTouch.UIKit.UIApplication.Main
(System.String[] args, System.String principalClassName, System.String
delegateClassName) [0x00000] in :0 at
TestApp.Application.Main (System.String[] args) [0x00008] in
/Users/xxx/Projects/TestApp/TestApp/TestApp/Main.cs:17
Try:
Hmm, now I added a new UITableViewController to the storyboard, changed some classes to public, changed variable names to starting with lower case. Also the old UITableviewController had a problem with an added SearchController. Now I made everything new and the problem only relied in the viewDidLoad but that was not the original problem. It was one of these steps (perhaps the SearchController problem).
Problematic Code:
this.NavigationController.ToolbarHidden = false;
It seems that he can't find the NavigationController ... How do I addd the navigation controller to the new created view?