I'm searching to get some players infos from a database with events in C#.
When I try my script in game, this error message appears :
[ 9419687] [b2699_GTAProce] MainThrd/ System.NullReferenceException: Object reference not set to an instance of an object.
[ 9419687] [b2699_GTAProce] MainThrd/
[ 9419687] [b2699_GTAProce] MainThrd/
[ 9419687] [b2699_GTAProce] MainThrd/ Server stack trace:
[ 9419687] [b2699_GTAProce] MainThrd/ at CitizenFX.Core.InternalManager.PrintError (System.String where, System.Exception what) [0x00081] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:595
[ 9419687] [b2699_GTAProce] MainThrd/ at CitizenFX.Core.InternalManager.CallRef (System.Int32 refIndex, System.Byte[] argsSerialized, System.IntPtr& retvalSerialized, System.Int32& retvalSize) [0x000b6] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:527
[ 9419687] [b2699_GTAProce] MainThrd/ at (wrapper remoting-invoke-with-check) CitizenFX.Core.InternalManager:CallRef (int,byte[],intptr&,int&)
[ 9419687] [b2699_GTAProce] MainThrd/ at (wrapper xdomain-dispatch) CitizenFX.Core.InternalManager:CallRef (object,byte[]&,byte[]&,int,byte[],int&)
[ 9419687] [b2699_GTAProce] MainThrd/
[ 9419687] [b2699_GTAProce] MainThrd/ Exception rethrown at [0]:
[ 9419687] [b2699_GTAProce] MainThrd/ at (wrapper xdomain-invoke) CitizenFX.Core.InternalManager:CallRef (int,byte[],intptr&,int&)
[ 9419687] [b2699_GTAProce] MainThrd/ at (wrapper remoting-invoke-with-check) CitizenFX.Core.InternalManager:CallRef (int,byte[],intptr&,int&)
[ 9419687] [b2699_GTAProce] MainThrd/ at CitizenFX.Core.MonoScriptRuntime.CallRef (System.Int32 refIndex, System.Byte[] argsSerialized, System.Int32 argsSize, System.IntPtr& retvalSerialized, System.Int32& retvalSize) [0x00013] in C:\gl\builds\master\fivem\code\client\clrcore\MonoScriptRuntime.cs:228
If you want to see it, here is my two scripts, the first is in the client side, the second one is in the server side.
Client-side :
public void GetPlayerInformations()
{
TriggerServerEvent("MST_SV_GetInformationOfPlayer",new Action <string, int, string>((userId, department, callsign) =>
{
_Functions.SendTextToConsole(Functions.InfoType.Debug, $"UserId: {userId} | Department: {department} | Callsign: {callsign}");
if (userId != null)
{
UserId = userId;
Department = department;
Callsign = callsign;
}
}));
}
Server-side :
private static void GetInformationOfPlayer([FromSource] Player player, NetworkCallbackDelegate callback)
{
try
{
using (MySqlConnection connection = Database.GetConnection())
{
using (MySqlCommand command = connection.GetCommand())
{
command.CommandText = "select * from user where license = #identifier";
command.Parameters.AddWithValue("#identifier", player.Identifiers["license"]);
using (DbDataReader result = command.ExecuteReader())
{
if (result.Read())
{
_functions.SendTextToConsole(Functions.InfoType.Debug,$"License : {result["license"]}, Department : {result["department"]}, Callsign : {result["callsign"]}.");
callback.Invoke(Convert.ToString(result["license"]), Convert.ToInt32(result["department"]), Convert.ToString(result["callsign"]));
_functions.SendTextToConsole(Functions.InfoType.Info, $"Informations of player {player.Name} has been loaded successfully.");
result.Close();
}
else
{
// Other part of the script non related to my issue
}
}
}
}
} catch (Exception e)
{
_functions.SendTextToConsole(Functions.InfoType.Error, $"An error has occurred while loading informations of player {player.Name} : {e.Message}");
}
}
I already check the database connection (it is okay), differents variables types, and the three variables gave through the callback aren't null (checked with the Debug.WriteLine) ...
Related
for a while now I've been trying to connect to my local SQLite3 database through a C# project. The project is a FiveM (which is a modification of GtaV) resource, so it works with the CitizenFX framework.
In particular, I'm creating a server-side script that can execute a query using Microsoft.Data.Sqlite. As specified in the title, I'm using .NET Standard 2.0.
The main problem is that the error trace (runtime error) doesn't seem complete. Note that in the first part it reports
System.DllNotFoundException: e_sqlite3 assembly:
type: member:(null)
Below is my ServerMain.cs:
using System;
using System.Collections.Generic;
using CitizenFX.Core;
using static CitizenFX.Core.Native.API;
namespace database.Server
{
public class ServerMain : BaseScript
{
public ServerMain()
{
Database db = new Database();
RegisterCommand("dbTest", new Action<int, List<object>, string>((source, args, rawCommand) =>
{
List<Dictionary<string, object>> result = db.Query("SELECT * FROM example_table WHERE example=8;");
foreach (Dictionary<string, object> item in result)
{
foreach (KeyValuePair<string, object> kv in item)
{
Debug.WriteLine($"{kv.Key}: {kv.Value.GetType().Name}");
}
}
}), false);
}
}
}
This is the other file.cs:
using System.Collections.Generic;
using Microsoft.Data.Sqlite;
namespace database.Server
{
class Database
{
public SqliteConnection connection;
public Database()
{
SqliteConnectionStringBuilder builder = new SqliteConnectionStringBuilder();
builder.DataSource = "db.sqlite3";
connection = new SqliteConnection(builder.ConnectionString);
}
public List<Dictionary<string, object>> Query(string query, Dictionary<string, string> args=null)
{
connection.Open();
SqliteCommand command = connection.CreateCommand();
command.CommandText = query;
if (args!=null)
foreach (KeyValuePair<string, string> item in args)
command.Parameters.AddWithValue(item.Key, item.Value);
SqliteDataReader reader = command.ExecuteReader();
List<Dictionary<string, object>> result = Serialize(reader);
connection.Close();
return result;
}
public static List<Dictionary<string, object>> Serialize(SqliteDataReader reader)
{
Dictionary<string, int> columns = new Dictionary<string, int>();
List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
while (reader.Read())
{
int fields = reader.FieldCount;
Dictionary<string, object> row = new Dictionary<string, object>();
for (short i = 0; i < fields; i++)
{
string name = reader.GetName(i);
columns[name] = i;
row[name] = reader.GetValue(i);
}
result.Add(row);
}
return result;
}
}
}
The .csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<DebugType>portable</DebugType>
<TargetName>$(AssemblyName).net</TargetName>
<DefineConstants>SERVER</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CitizenFX.Core.Server" Version="1.0.*" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="7.0.3" />
<Compile Include="../Shared/**/*.cs" />
</ItemGroup>
</Project>
And finally the traceback:
[ c-scripting-core] Creating script environments for database
[ script:database] Failed to instantiate instance of script database.Server.ServerMain: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.DllNotFoundException: e_sqlite3 assembly:<unknown assembly> type:<unknown type> member:(null)
[ script:database] at (wrapper managed-to-native) SQLitePCL.SQLite3Provider_e_sqlite3+NativeMethods.sqlite3_libversion_number()
[ script:database] at SQLitePCL.SQLite3Provider_e_sqlite3.SQLitePCL.ISQLite3Provider.sqlite3_libversion_number () [0x00000] in <4449c65940e74ba7b1247a8a3c44b286>:0
[ script:database] at SQLitePCL.raw.SetProvider (SQLitePCL.ISQLite3Provider imp) [0x00008] in <40a4c727ed10429e9462ed3199f679d7>:0
[ script:database] at SQLitePCL.Batteries_V2.Init () [0x00005] in <155a967c9c00435ab07bcaf82817b9c1>:0
[ script:database] at (wrapper managed-to-native) System.Reflection.RuntimeMethodInfo.InternalInvoke(System.Reflection.RuntimeMethodInfo,object,object[],System.Exception&)
[ script:database] at System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x0006a] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] Exception_EndOfInnerExceptionStack
[ script:database] at System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00083] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at Microsoft.Data.Sqlite.SqliteConnection..cctor () [0x0003b] in <67ae02770bef4af48e4dbca605b09ddb>:0
[ script:database] Exception_EndOfInnerExceptionStack
[ script:database] at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_generic_class_init(intptr)
[ script:database] at database.Server.Database..ctor () [0x00017] in C:\Users\yuppi\Documents\Nico\Server FiveM\txData\ServerData\builders\database\Server\Database.cs:18
[ script:database] at database.Server.ServerMain..ctor () [0x0000c] in C:\Users\yuppi\Documents\Nico\Server FiveM\txData\ServerData\builders\database\Server\ServerMain.cs:13
[ script:database] at (wrapper managed-to-native) System.Reflection.RuntimeConstructorInfo.InternalInvoke(System.Reflection.RuntimeConstructorInfo,object,object[],System.Exception&)
[ script:database] at System.Reflection.RuntimeConstructorInfo.InternalInvoke (System.Object obj, System.Object[] parameters, System.Boolean wrapExceptions) [0x00005] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] Exception_EndOfInnerExceptionStack
[ script:database] at System.Reflection.RuntimeConstructorInfo.InternalInvoke (System.Object obj, System.Object[] parameters, System.Boolean wrapExceptions) [0x0001a] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at System.RuntimeType.CreateInstanceMono (System.Boolean nonPublic, System.Boolean wrapExceptions) [0x00095] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at System.RuntimeType.CreateInstanceSlow (System.Boolean publicOnly, System.Boolean wrapExceptions, System.Boolean skipCheckThis, System.Boolean fillCache) [0x00009] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at System.RuntimeType.CreateInstanceDefaultCtor (System.Boolean publicOnly, System.Boolean skipCheckThis, System.Boolean fillCache, System.Boolean wrapExceptions, System.Threading.StackCrawlMark& stackMark) [0x00027] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at System.Activator.CreateInstance (System.Type type, System.Boolean nonPublic, System.Boolean wrapExceptions) [0x00020] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at System.Activator.CreateInstance (System.Type type, System.Boolean nonPublic) [0x00000] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at System.Activator.CreateInstance (System.Type type) [0x00000] in <fbc4ec45371543bfba3678ebb82caf6d>:0
[ script:database] at CitizenFX.Core.InternalManager.CreateAssemblyInternal (System.String assemblyFile, System.Byte[] assemblyData, System.Byte[] symbolData) [0x0007b] in C:\gl\builds\4ff63adb\0\cfx\fivem\code\client\clrcore\InternalManager.cs:156
I tried to change the version of Microsoft.Data.Sqlite to 2.2.0, but I still got an error, this time a different one:
[ script:database] Failed to instantiate instance of script database.Server.ServerMain: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: This is the 'bait'. You probably need to add one of the SQLitePCLRaw.bundle_* nuget packages to your platform project.
As I guessed from the error, I then also installed the SQLitePCLRaw.bundle_green package, but the error remained the same.
I have this code that throws "Sequence contains no elements" exception:
autoRefreshWorker = new AutoRefreshWorker(AutoRefreshData, () => {
var items = ((DocumentListDataSource)TableView.Source).Items;
return items.Any()
? items.Aggregate((i1, i2) => i1.Id > i2.Id ? i1 : i2)
: items.FirstOrDefault();
},
AutoRefreshIntervalMs);
I was not able to reproduce the error myself. But on AppCenter I can see that lots of users experience this error very often and the stack trace shows the following:
Enumerable.Aggregate[TSource] (System.Collections.Generic.IEnumerable`1[T] source, System.Func`3[T1,T2,TResult] func)
DocumentsListViewController.<ViewDidAppear>b__38_0 ()
DocumentsListViewController+AutoRefreshWorker.<Start>b__6_1 ()
AsyncHelpers+<>c__DisplayClass0_0.<InvokeOnMainThreadAsync>b__0 ()
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state)
NSAsyncSynchronizationContextDispatcher.Apply ()
(wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName)
Application.Main (System.String[] args)
I know that calling Aggregate() on empty set throws that exception. But in my code I check if items contains any element before calling Aggregate. So it is not clear to me what can cause this exception in my code. Any ideas?
I'm getting an exception error: System.Threading.Tasks.TaskCanceledException, while trying to get some geolocation informations using Plugin.Geolocator.
here 's the exception that I get : System.Threading.Tasks.TaskCanceledException: A task was canceled.
at Plugin.Geolocator.GeolocatorImplementation.GetPositionAsync (System.Nullable1[T] timeout, System.Nullable1[T] cancelToken, System.Boolean includeHeading) [0x004d3] in :0
at interface_test.MainPage.CreateMainPageAsync () [0x0018b] in /Users/khalidharkati/Projects/interface_test/interface_test/MainPage.xaml.cs:140
at interface_test.App.OnStart () [0x0001a] in /Users/khalidharkati/Projects/interface_test/interface_test/App.xaml.cs:23
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in <58604b4522f748968296166e317b04b4>:0
at Android.App.SyncContext+<>c__DisplayClass2_0.b__0 () [0x00000] in <788a34f7a7b84486905dfde786529d42>:0
at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <788a34f7a7b84486905dfde786529d42>:0
at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <788a34f7a7b84486905dfde786529d42>:0
at at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.40(intptr,intptr)
To be able to use an async constructor, I made one with the position as an argument:
public MainPage(Plugin.Geolocator.Abstractions.Position position)
{
...
}
Then I added this method to get my position:
public static async Task<MainPage> CreateMainPageAsync()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
MainPage page = new MainPage(position);
return page;
}
In the app.xaml.cs file, I added this code to the OnStart() method:
protected override async void OnStart()
{
interface_test.MainPage main = await interface_test.MainPage.CreateMainPageAsync();
MainPage = main;
}
PS: Before I update some components, Xamarin and some packages, I start getting this error.
I solved it , actually , this might sound stupid , but I just forgot to turn my GPS on , on my phone . that's it .
I have an error with my C# code and MySQL.
Can you help me solve it please ?
Here is my code :
try
{
using (MySqlConnection dbcon = new MySqlConnection(SQLConnectionString))
{
dbcon.Open(); // ERROR HERE
string sql = "SELECT * FROM scp_patreons";
MySqlCommand command = new MySqlCommand();
command = dbcon.CreateCommand();
command.CommandText = sql;
using (MySqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
string fullname = (string)dr["fullname"];
plugin.Info("Name: " + fullname + "");
}
}
}
}
catch (Exception ex)
{
plugin.Info("SQL_ERROR: " + ex.Message + "\n" + ex.StackTrace);
}
string SQLConnectionString = "Server=*; Database=*; User ID = *; Password=*; Pooling=false;SslMode=None;";
and i'm getting the error :
SQL_ERROR: The type initializer for 'MySql.Data.MySqlClient.MySqlConnectAttrs' threw an exception.
at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_generic_class_init(intptr)
at MySql.Data.MySqlClient.NativeDriver.SetConnectAttrs () [0x00018] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.Authentication.MySqlAuthenticationPlugin.Authenticate (System.Boolean reset) [0x00080] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.NativeDriver.Authenticate (System.String authMethod, System.Boolean reset) [0x0002a] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.NativeDriver.Open () [0x0033f] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.Driver.Open () [0x0000e] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.Driver.Create (MySql.Data.MySqlClient.MySqlConnectionStringBuilder settings) [0x0004e] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.MySqlConnection.Open () [0x0016d] in <699dc28794d34867bd2008187eb8039c>:0
at PlayerXP.PlayerXP.OnEnable () [0x00021] in <80e302c4eac64aeebd42276ff4a14839>:0
I'm running 5.7.25 - MySQL Community Server (GPL)
Server : Localhost with UNIX socket
Protocol version : 10
User : root#localhost
Server char : UTF-8 Unicode (utf8)
Mono JIT compiler version 5.18.0.268
Connector/NET 8.0.15
I use Debian 9.6.
Thanks for your help.
EDIT :
The new error message :
System.TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.MySqlConnectAttrs' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
at MySql.Data.MySqlClient.MySqlConnectAttrs..cctor () [0x0000f] in <699dc28794d34867bd2008187eb8039c>:0
--- End of inner exception stack trace ---
at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_generic_class_init(intptr)
at MySql.Data.MySqlClient.NativeDriver.SetConnectAttrs () [0x00018] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.Authentication.MySqlAuthenticationPlugin.Authenticate (System.Boolean reset) [0x00080] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.NativeDriver.Authenticate (System.String authMethod, System.Boolean reset) [0x0002a] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.NativeDriver.Open () [0x0033f] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.Driver.Open () [0x0000e] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.Driver.Create (MySql.Data.MySqlClient.MySqlConnectionStringBuilder settings) [0x0004e] in <699dc28794d34867bd2008187eb8039c>:0
at MySql.Data.MySqlClient.MySqlConnection.Open () [0x0016d] in <699dc28794d34867bd2008187eb8039c>:0
at PlayerXP.PlayerXP.OnEnable () [0x00021] in <cc464d994e5a47c88df91f25374d2f29>:0
Thanks to #Bradley Grainger, my problem is solved. I have tried http://www.nuget.org/packages/MySqlConnector and it works !
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);
}
}
}
}