CSOM

Microsoft.SharePoint.Client.ClientRuntimeContext.Load: type argument 'Microsoft.SharePoint.Client.Web' violates the constraint of type parameter 'T'

A provider-hosted app began to display this error when any CSOM call was made to SharePoint Online:

'Microsoft.SharePoint.Client.ClientRuntimeContext.Load: type argument 'Microsoft.SharePoint.Client.Web' violates the constraint of type parameter 'T'

This was thrown when any call was made using clientContext.Load(), regardless of the object being loaded, and despite the calls being wrapped in a try/catch block.

The root cause of this was that earlier in the day the project's assembly references in Visual Studio became corrupted, and building the project started throwing errors regarding invalid assemblies, for any member of Microsoft.SharePoint.Client (why this happened is still a mystery).

Removing the reference and re-adding it via Project > References made those build errors go away....


.... but that resulted in the nasty constraint violation error.

The reason for that was that the Microsoft.SharePoint.Client assembly references were originally added to the project by adding the NuGet package (Microsoft.SharePointOnline.CSOM). Although these DLLs have the same name as the ones you see in Project > References, they are different (or at least have different version numbers). Hence the request was asking for a slightly different data type than that returned by SharePoint Online.

You can solve this problem by uninstalling the NuGet package from the project, and reinstalling it. To remove the package you need to open the package manager console (Tools > NuGet Package Manager > Package Manager Console), type Uninstall-Package Microsoft.SharePointOnline.CSOM and hit Enter.

Once the package is removed you can then re-add it via the NuGet UI, or just type Install-Package Microsoft.SharePointOnline.CSOM to reinstall it. Use the -project switch if you don't want the package deployed to all the projects in your solution.