Hello everyone,
I had a C# code that allowed me to upload a file to SharePoint. Initially, I created this code using a class library. Later, I changed it to a Windows application to test it, and it worked perfectly. Then, I changed it back to a class library to get the DLL.
However, I need to use this code in my X++ project to upload a stream to a SharePoint library. I tried two approaches:
1-Using the DLL of the C# project I created.
2-Embedding the C# code directly within my X++ project.
Despite these efforts, I still encounter an error. The error message says:
Error: An error occurred while uploading the file: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. â> System.TypeLoadException: Could not load type âMicrosoft.Graph.Models.UploadSessionâ from assembly âMicrosoft.Graph, Version=4.24.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35â. at MSGraphConnection.MSGraphApi.uploadFileToSharepointOnlineAsync() at Dynamics.AX.Application.uploadFile.`uploadmethod in xppSource://Source/Model\AxClass_uploadFile.xpp:line 60 â End of inner exception stack trace â
Could anyone help me resolve this issue?
///////////////////////////////////////////////////////////////////
the C# code is :
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Drives.Item.Items.Item.CreateUploadSession;
using Microsoft.Graph.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Dynamics.Ax.Xpp;
namespace MSGraphConnection
{
public class MSGraphApi
{
public static async Task uploadFileToSharepointOnlineAsync()
{
try
{
var tenantId = âyour-tenant-idâ;
var clientId = âyour-client-idâ;
var clientSecret = âyour-client-secretâ;
string site = âyour-sharepoint-siteâ;
string siteId = âyour-site-idâ;
var driveId = âyour-drive-idâ;
var fileName = âtest.txtâ;
var filePath = âC:/path/to/your/file.txtâ;
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var scopes = new[] { "https://graph.microsoft.com/.default" };
GraphServiceClient graphClient = new GraphServiceClient(clientSecretCredential, scopes);
using (var localFileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
CreateUploadSessionPostRequestBody uploadSessionRequestBody = new CreateUploadSessionPostRequestBody
{
Item = new DriveItemUploadableProperties
{
AdditionalData = new Dictionary<string, object>
{
{ "@microsoft.graph.conflictBehavior", "replace" }, // fail, replace, or rename
},
},
};
var uploadSession = await graphClient.Drives[driveId]
.Items["root"]
.ItemWithPath($"TEST/{fileName}")
.CreateUploadSession
.PostAsync(uploadSessionRequestBody);
int maxSliceSize = 320 * 1024;
Microsoft.Graph.LargeFileUploadTask<Microsoft.Graph.Models.DriveItem> fileUploadTask = new Microsoft.Graph.LargeFileUploadTask<Microsoft.Graph.Models.DriveItem>(uploadSession, localFileStream, maxSliceSize, graphClient.RequestAdapter);
long totalLength = localFileStream.Length;
System.IProgress<long> progress = new System.Progress<long>(prog => Console.WriteLine($"Uploaded {prog} bytes of {totalLength} bytes"));
try
{
Microsoft.Graph.UploadResult<Microsoft.Graph.Models.DriveItem> uploadResult = await fileUploadTask.UploadAsync(progress);
return "success";
}
catch (ServiceException ex)
{
return "failed";
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return "failed something";
}
}
}
}
////////////////////////////////////////////////////////////////////
and x++ code is :
io.writeExp(lineData);
stream = io.getStream();
stream.Position = 0;
reader = new System.IO.StreamReader(stream);
fileContent = reader.ReadToEnd();
str fileName = âtestfile.csvâ;
File::SendStringAsFileToUser(fileContent, fileName, System.Text.Encoding::UTF8);
var task = MSGraphConnection.MSGraphApi::uploadFileToSharepointOnlineAsync();
task.Wait();
// Get the result of the task
str result = task.get_Result();
info(result);
//////////////////////////////////////////////////////////////////