web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested Answer

How to query sharepointdocument entity from C# ?

(0) ShareShare
ReportReport
Posted on by 5

Hello everybody,

SharePoint has been integrated in our Dynamics CRM Online (Settings > Document Management then Enable server-based SharePoint integration, etc...) and enabled for a few entities (i.e. contact or account).

I can query sharepointdocument entity with XrmToolbox

  
    
      
      
    
  

XrmToolBox-_2D00_-sharepointdocument.png

But the same query doesn't work from a .net core 6.0 application / Microsoft.PowerPlatform.Dataverse.Client latest stable (1.0.39), either console or webapp.

            string fetchquery =
                @"
                      
                        
                          
                          
                        
                      
                ";

            EntityCollection list = _svcClient.RetrieveMultiple(new FetchExpression(fetchquery));
            foreach (Entity entity in list.Entities) {
                // do something
            }

or with QueryExpression

            QueryExpression query = new QueryExpression("sharepointdocument");
            query.ColumnSet = new ColumnSet(true);
            var filter = new FilterExpression();

            filter.AddCondition(new ConditionExpression("regardingobjecttypecode", ConditionOperator.Equal, 2));
            Guid contactId = Guid.Parse("1053ec5b-b4ab-ed11-83fe-000d3a959720");
            filter.AddCondition(new ConditionExpression("regardingobjectid", ConditionOperator.Equal, contactId));

            query.Criteria = filter;
            query.AddOrder("fullname", OrderType.Ascending);

            EntityCollection list = _svcClient.RetrieveMultiple(query);
            foreach (Entity entity in list.Entities) {
                // Do something
            }

The error is

Unhandled exception: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault : At least 1 Claim must not be NULL, current claims are : nameid=;nii=urn:federation:microsoftonline (le détail de l'erreur est égal à Exception details:
ErrorCode: 0x80040216
Message: At least 1 Claim must not be NULL, current claims are : nameid=;nii=urn:federation:microsoftonline

Then I tried to set _svcClient.CallerId with admin user (which was not necessary in other queries in my app) but same error.

Am I missing something ? Is there a way to query sharepointdocument from C# ?

Thanks in advance !

I have the same question (0)
  • Suggested answer
    XM-22040801-0 Profile Picture
    11 on at

    Hi,

    I don't see any errors in your code snippet.

    Can you try with a simple WhoAmIRequest ? See learn.microsoft.com/.../microsoft.crm.sdk.messages.whoamirequest

    Bonus: You can add the <all-attributes /> node in your Fetch XML under entity.

  • vpaklee Profile Picture
    5 on at

    I can view the sharepointdocuments as json with a browser that is authenticated to my CRM resource (i.e. https://xxx.crm12.dynamics.com/api/data/v9.2/sharepointdocuments?fetchXml=...) so I tried to issue a HttpClient request with a bearer token. It works with a simple query (get all accounts) but not for sharepointdocuments

                string resource = "https://xxx.crm12.dynamics.com/";
                var tenantId = "XXX";
                var clientId = "XXX";
                var clientSecret = "XXX";
                var redirectUri = "http://localhost"; // Loopback for the interactive login.
                var scope = resource   "/.default";
                string[] scopes = { scope };
    
                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
                    .WithTenantId(tenantId)
                    .WithClientSecret(clientSecret)
                    .WithRedirectUri(redirectUri)
                .Build();
    
                AuthenticationResult token = await app.AcquireTokenForClient(scopes).ExecuteAsync();
    
                // Set up the HTTP client
                var client = new HttpClient {
                    BaseAddress = new Uri(resource   "api/data/v9.2/"),
                    Timeout = new TimeSpan(0, 2, 0)  // Standard two minute timeout.
                };
    
                HttpRequestHeaders headers = client.DefaultRequestHeaders;
                headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
                headers.Add("OData-MaxVersion", "4.0");
                headers.Add("OData-Version", "4.0");
                headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                // Simple web API call : OK
                string requestUri = @"accounts";
                var response = await client.GetAsync(requestUri);
                var content = await response.Content.ReadAsStringAsync();
                Console.Out.WriteLine(response);
    
                // Requesting sharepointdocument with Web API call : NOK, HTTP 400 Bad Request
                string fetchquery =
                    @"
                          
                            
                              
                              
                            
                          
                      ";
    
                requestUri = @"sharepointdocuments?fetchXml="   HttpUtility.UrlEncode(fetchquery);
                response = await client.GetAsync(requestUri);
                content = await response.Content.ReadAsStringAsync();
                Console.Out.WriteLine(response);

    Same error message

    code: "0x80040216"

    "At least 1 Claim must not be NULL, current claims are : nameid=;nii=urn:federation:microsoftonline "

  • Suggested answer
    XM-22040801-0 Profile Picture
    11 on at

    Does your application (clientid) have rights on SharePoint?

    Do you get the same error if you connect using the UserName flow ?

  • vpaklee Profile Picture
    5 on at

    WhoAmIRequest works. It also works when I query account or sharepointdocumentlocation but not sharepointdocument.

    I don't understand why the same FetchXML works in XrmToolbox and in a browser (see below) and not from C# app.

  • XM-22040801-0 Profile Picture
    11 on at

    What OAuth flow do you use with XrmToolBox ? Is it a clientid / clientsecret like in your code ?

  • vpaklee Profile Picture
    5 on at

    I have OAuth username / password with XrmToolBox and clientId / clientSecret in my C# app, that may be the reason.

    I tried IPublicClientApplication.AcquireTokenByUsernamePassword but then I have
    AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access
    but I can't disable MFA (I will ask tomorrow because I'm not a CRM admin).

    Also tried to give rights to my application (clientId / tenantId) in SharePoint as mentionned here : learn.microsoft.com/.../how-to-grant-permission-to-azure-managed-identity

    but there's already another application (which is probably Dynamics 365 online) and I can't add mine. Either app name or clientId or clientId@tenantId is unknown.

    Add-clientId-to-SharePoint.png

  • vpaklee Profile Picture
    5 on at

    Finally I did a workaround by sending an API request with HttpClient and token taken from the connected user like this :

    https://github.com/Azure-Samples/ms-identity-aspnet-webapi-onbehalfof

    Not fully satisfying because I will have to do the same with a console app or Azure function, therefore without user token.

    Tried to create an Azure group, add my app in this group and allow this group on SharePoint. The configuration seems ok but still the same error ("At least 1 Claim must not be NULL, current claims are : nameid=;nii=urn:federation:microsoftonline")

  • vpaklee Profile Picture
    5 on at

    I think I found a better solution :

    • With Dataverse ServiceClient : query sharepointdocumentlocation entity with regardingobjecttypecode / regardingobjectid from my search entity (e.g. account or contact or else)
    • With GraphServiceClient : query Sites and Drives, get the right Site / Drive for my entity, then  search the item whose name corresponds to the sharePointDocumentLocation.relativeUrl (at 1st step)

    ServiceClient and GraphServiceClient are injected with Azure API permissions and client id / client secret.

    I don't have time to write a proper C# example (mine has business specific code and cache functionnality) but I can do it later is someone is interested.

  • CU29041715-0 Profile Picture
    on at
    Did we found resolution for this issue?
     
    I'm facing same issue. Please suggest.

    At least 1 Claim must not be NULL, current claims are : nameid=;nii=urn:federation:microsoftonlin

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Congratulations to our 2025 Community Spotlights

Thanks to all of our 2025 Community Spotlight stars!

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
ManoVerse Profile Picture

ManoVerse 180 Super User 2026 Season 1

#2
11manish Profile Picture

11manish 123

#3
CU11031447-0 Profile Picture

CU11031447-0 100

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans