Microsoft Dynamics 365 Field Service Web API: Create a work order triggers a "code": "0x80040265", "message": "The Service Account is required.", - python-3.x

HTTP POST to create a new Work Order in Microsoft Dynamics 365 - Field Service (Empty body)
import requests
url = "https://{{my-env_name}}.{{my_region}}.dynamics.com/api/data/v9.0/msdyn_workorders"
payload = "{\n \n}"
headers = {
'Accept': 'application/json',
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'If-None-Match': 'null',
'Authorization': 'Bearer eyXXX',
'Content-Type': 'application/json',
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
Error received when the Body of the POST is empty
{
"error": {
"code": "0x80040265",
"message": "The Service Account is required.",
"innererror": {
"message": "The Service Account is required.",
"type": "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
"stacktrace": " at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.CreateInternal(Entity entity, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Dictionary`2 optionalParameters)\r\n
at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.CreateOrganizationResponse(Entity entity)\r\n
at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)\r\n
at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)\r\n
at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()\r\n
at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n
at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n
at lambda_method(Closure , Object , Object[] )\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n
--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n
--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n
--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
I add the Service Account into the body of the POST
Look at the model of a Work Order : https://learn.microsoft.com/en-us/dynamics365/customer-engagement/web-api/msdyn_workorder?view=dynamics-ce-odata-9
{
"msdyn_serviceaccount": "{{an existing account id}}"
}
Error received when the Body of the POST contains the msdyn_serviceaccount field
{
"error": {
"code": "0x0",
"message": "An error occurred while validating input parameters: Microsoft.OData.ODataException: A 'PrimitiveValue' node with non-null value was found when trying to read the value of the property 'msdyn_serviceaccount'; however, a 'StartArray' node, a 'StartObject' node, or a 'PrimitiveValue' node with null value was expected.\r\n
at Microsoft.OData.JsonLight.ODataJsonLightPropertyAndValueDeserializer.ValidateExpandedNestedResourceInfoPropertyValue(IJsonReader jsonReader, Nullable`1 isCollection, String propertyName)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadPropertyWithValue(IODataJsonLightReaderResourceState resourceState, String propertyName, Boolean isDeltaResourceSet)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.<>c__DisplayClass9_0.<ReadResourceContent>b__0(PropertyParsingResult propertyParsingResult, String propertyName)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightDeserializer.ProcessProperty(PropertyAndAnnotationCollector propertyAndAnnotationCollector, Func`2 readPropertyAnnotationValue, Action`2 handleProperty)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadResourceContent(IODataJsonLightReaderResourceState resourceState)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightReader.StartReadingResource()\r\n
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadResourceSetItemStart(PropertyAndAnnotationCollector propertyAndAnnotationCollector, SelectedPropertiesNode selectedProperties)\r\n at
Microsoft.OData.JsonLight.ODataJsonLightReader.ReadAtStartImplementationSynchronously(PropertyAndAnnotationCollector propertyAndAnnotationCollector)\r\n
at Microsoft.OData.ODataReaderCore.ReadImplementation()\r\n
at Microsoft.OData.ODataReaderCore.InterceptException[T](Func`1 action)\r\n
at System.Web.OData.Formatter.Deserialization.ODataReaderExtensions.ReadResourceOrResourceSet(ODataReader reader)\r\n
at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)\r\n
at System.Web.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)",
"innererror": {
"message": "An error occurred while validating input parameters: Microsoft.OData.ODataException: A 'PrimitiveValue' node with non-null value was found when trying to read the value of the property 'msdyn_serviceaccount'; however, a 'StartArray' node, a 'StartObject' node, or a 'PrimitiveValue' node with null value was expected.\r\n
at Microsoft.OData.JsonLight.ODataJsonLightPropertyAndValueDeserializer.ValidateExpandedNestedResourceInfoPropertyValue(IJsonReader jsonReader, Nullable`1 isCollection, String propertyName)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadPropertyWithValue(IODataJsonLightReaderResourceState resourceState, String propertyName, Boolean isDeltaResourceSet)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.<>c__DisplayClass9_0.<ReadResourceContent>b__0(PropertyParsingResult propertyParsingResult, String propertyName)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightDeserializer.ProcessProperty(PropertyAndAnnotationCollector propertyAndAnnotationCollector, Func`2 readPropertyAnnotationValue, Action`2 handleProperty)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadResourceContent(IODataJsonLightReaderResourceState resourceState)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightReader.StartReadingResource()\r\n
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadResourceSetItemStart(PropertyAndAnnotationCollector propertyAndAnnotationCollector, SelectedPropertiesNode selectedProperties)\r\n
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadAtStartImplementationSynchronously(PropertyAndAnnotationCollector propertyAndAnnotationCollector)\r\n
at Microsoft.OData.ODataReaderCore.ReadImplementation()\r\n
at Microsoft.OData.ODataReaderCore.InterceptException[T](Func`1 action)\r\n
at System.Web.OData.Formatter.Deserialization.ODataReaderExtensions.ReadResourceOrResourceSet(ODataReader reader)\r\n
at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)\r\n
at System.Web.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)",
"type": "Microsoft.Crm.CrmHttpException",
"stacktrace": " at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.ValidateInputParameters(ModelStateDictionary controllerModelState)\r\n
at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)\r\n
at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()\r\n
at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n
at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n
at lambda_method(Closure , Object , Object[] )\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n
--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n
--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
QUESTION: What is the expected JSON body by the Web API of Microsoft Dynamics 365 Field Service?

You should use this, to put in a lookup (aka Entity reference, navigation property):
{
"msdyn_serviceaccount#odata.bind": "/accounts(guid)"
}
The basic payload with required fields to create work order is below:
{
"msdyn_serviceaccount#odata.bind": "/accounts(account_entity_guid_you_want_to_bind)",
"msdyn_pricelist#odata.bind": "/pricelevels(pricelevel_entity_guid_you_want_to_bind)",
"msdyn_systemstatus": "690970000",
}
Reference

Related

Acumatica API - 2nd step (Receipt) of Inventory Transfer

To complete the second step (Receipt) of a 2-step transfer, through the UI/browser, we select the corresponding Transfer (1st step) and in the detail section we select the Location into which the product is received. Rest of the information is populated from the Transfer by default.
If I try the same through API, it's giving an error about Location cannot be empty. I also included the Allocation detail, yet the error is same. What am I missing here? How should one post the data to create a receipt in Acumatica?
PUT https://ACUInstance/entity/ExtendedDefault/18.200.001/InventoryReceipt/
{
"TransferNbr": { "value": "06023267" },
"Details": [
{
"Location": { "value": "L100" }
}
]
}
I also tried:
{
"TransferNbr": { "value": "06023267" },
"Details": [
{
"Location": { "value": "L100" },
"Allocations":[
"Location": { "value": "L100" }
]
}
]
}
For both, the error is same:
{
"message": "An error has occurred.",
"exceptionMessage": "InventoryReceipt.Details[0].Allocations[0].Location: 'Location' cannot be empty.\nInventoryReceipt.Details[0].Location: 'Location' cannot be empty.\nInserting 'IN Transaction Split' record raised at least one error. Please review the errors.",
"exceptionType": "PX.Api.ContractBased.OutcomeEntityHasErrorsException",
"stackTrace": " at PX.Api.ContractBased.EntityService.GetOperationResult(EntityImpl entity, EntityExportContextBuilder entityExportContextBuilder, PXSYTable exportedKeys, PXOuterException contextError, Boolean throwOnError)\r\n at PX.Api.ContractBased.EntityService.Put(ISystemContract systemContract, String version, String name, EntityImpl entity, CbOperationContext operationContext, Boolean throwOnError)\r\n at PX.Api.ContractBased.Soap.SoapFacadeBase.PutImpl(EntityImpl entity, Boolean throwOnValidationError)\r\n at PX.Api.ContractBased.SystemContracts.V2.RestController.PutEntity(EntityImpl entity, String select, String filter, String expand, String custom)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
}

Azure IOT Device client method CompleteFileUploadAsync giving error 403 as forbidden when IsSuccess = true, works for IsSuccess = false

I have enabled private endpoint for iot hub and azure storage account and restricted the public traffic, when i am uploading a file it gets uploaded successfully but when calling CompleteFileUploadAsync method of device client i am getting error 403 as forbidden. But when passing the IsSuccess = false its working with current configuration, i changed the Allow access from to "All networks" then its working.
I want to make sure that its notifying within private network when file uploaded successfully as its working when file upload fails.
Code:
private static async Task SendToBlobAsync(DeviceClient deviceClient, string fileName)
{
Console.WriteLine("Uploading file: {0}", fileName);
var watch = System.Diagnostics.Stopwatch.StartNew();
var sas = await deviceClient.GetFileUploadSasUriAsync(new FileUploadSasUriRequest { BlobName = fileName });
var blob = new CloudBlockBlob(sas.GetBlobUri());
await blob.UploadFromFileAsync(fileName);
await deviceClient.CompleteFileUploadAsync(new FileUploadCompletionNotification { CorrelationId = sas.CorrelationId, IsSuccess = true });
watch.Stop();
Console.WriteLine("Time to upload file: {0}ms\n", watch.ElapsedMilliseconds);
}
The method throwing the below error message :
{
"Message":"{\"errorCode\":400020,\"trackingId\":\"72f35ff2b08f4312bc0e9f9d36be1061-G:0-TimeStamp:02/23/2021 14:24:46\",\"message\":\"BadRequest\",\"timestampUtc\":\"2021-02-23T14:24:46.3420546Z\"}",
"ExceptionMessage":"ErrorCode: InvalidStorageEndpointOrBlob\r\nMessage: Storage endpoint '$default' or blob name device001/image.jpg is invalid\r\nTimestamp: 02/23/2021 14:24:46\r\nTracking ID: 72f35ff2b08f4312bc0e9f9d36be1061-G:0-TimeStamp:02/23/2021 14:24:46\r\nPublic Message: \r\nPublic Info: null\r\nException: Microsoft.Azure.Devices.Common.Core.Exceptions.IotHubException: Storage endpoint '$default' or blob name device001/image.jpg is invalid ---> Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (403) Forbidden. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.\r\n at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase`1 cmd, Exception ex)\r\n at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.<>c__DisplayClass22.<FetchAttributesImpl>b__21(RESTCommand`1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx)\r\n at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult)\r\n --- End of inner exception stack trace ---\r\n at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result)\r\n at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass7.<CreateCallbackVoid>b__5(IAsyncResult ar)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Azure.Devices.Gateway.Runtime.FileUpload.IotHubFileUploadManager.<GenerateFileUploadNotificationAsync>d__10.MoveNext() in C:\\source\\gateway\\runtime\\FileUpload\\IotHubFileUploadManager.cs:line 153\r\n --- End of inner exception stack trace ---\r\n at Microsoft.Azure.Devices.Gateway.Runtime.FileUpload.IotHubFileUploadManager.<GenerateFileUploadNotificationAsync>d__10.MoveNext() in C:\\source\\gateway\\runtime\\FileUpload\\IotHubFileUploadManager.cs:line 180\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Azure.Devices.Gateway.Runtime.Http.HttpRuntimeProvider.<UpdateAndNotifyFileUploadStatusAsync>d__41.MoveNext() in C:\\source\\gateway\\runtime\\Http\\HttpRuntimeProvider.cs:line 1215\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Azure.Devices.Gateway.Runtime.Http.HttpRuntimeActionResult`1.<ExecuteAsync>d__7.MoveNext() in C:\\source\\gateway\\mgmt\\Http\\HttpRuntimeActionResult.cs:line 153\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Azure.Devices.Gateway.Management.ActionFilters.GlobalActionFilter.<ExecuteActionFilterAsync>d__0.MoveNext() in C:\\source\\gateway\\mgmt\\ActionFilters\\GlobalActionFilter.cs:line 42\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__3.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__6.MoveNext()",
"ExceptionType":"Microsoft.Azure.Devices.Common.Core.Exceptions.IotHubException",
"StackTrace":" at Microsoft.Azure.Devices.Gateway.Runtime.FileUpload.IotHubFileUploadManager.<GenerateFileUploadNotificationAsync>d__10.MoveNext() in C:\\source\\gateway\\runtime\\FileUpload\\IotHubFileUploadManager.cs:line 180\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Azure.Devices.Gateway.Runtime.Http.HttpRuntimeProvider.<UpdateAndNotifyFileUploadStatusAsync>d__41.MoveNext() in C:\\source\\gateway\\runtime\\Http\\HttpRuntimeProvider.cs:line 1215\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Azure.Devices.Gateway.Runtime.Http.HttpRuntimeActionResult`1.<ExecuteAsync>d__7.MoveNext() in C:\\source\\gateway\\mgmt\\Http\\HttpRuntimeActionResult.cs:line 153\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Azure.Devices.Gateway.Management.ActionFilters.GlobalActionFilter.<ExecuteActionFilterAsync>d__0.MoveNext() in C:\\source\\gateway\\mgmt\\ActionFilters\\GlobalActionFilter.cs:line 42\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__3.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__6.MoveNext()",
"InnerException":{
"Message":"An error has occurred.",
"ExceptionMessage":"The remote server returned an error: (403) Forbidden.",
"ExceptionType":"Microsoft.WindowsAzure.Storage.StorageException",
"StackTrace":" at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result)\r\n at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass7.<CreateCallbackVoid>b__5(IAsyncResult ar)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Azure.Devices.Gateway.Runtime.FileUpload.IotHubFileUploadManager.<GenerateFileUploadNotificationAsync>d__10.MoveNext() in C:\\source\\gateway\\runtime\\FileUpload\\IotHubFileUploadManager.cs:line 153",
"InnerException":{
"Message":"An error has occurred.",
"ExceptionMessage":"The remote server returned an error: (403) Forbidden.",
"ExceptionType":"System.Net.WebException",
"StackTrace":" at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase`1 cmd, Exception ex)\r\n at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.<>c__DisplayClass22.<FetchAttributesImpl>b__21(RESTCommand`1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx)\r\n at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult)"
}
}
}

401 when creating a modern site using App-Only using Office Pnp Sites Core

So, I am using method number 2 here:
https://www.vrdmn.com/2019/01/working-with-application-permissions.html
My code is as follows:
string siteUrl = "https://xx.sharepoint.com/sites/test212/";
string siteUrl2 = "https://xx.sharepoint.com/sites/test2122/";
//Client id and Client secret created through appregnew.aspx and permissions granted through appinv.aspx
var authManager = new OfficeDevPnP.Core.AuthenticationManager();
//PnP Core method
ClientContext clientContext = authManager.GetAppOnlyAuthenticatedContext(siteUrl, "xx", "xx");
var teamNoGroupSiteResult = await clientContext.CreateSiteAsync(new OfficeDevPnP.Core.Sites.TeamNoGroupSiteCollectionCreationInformation()
{
Url = siteUrl,
Title = "Team no group Site Test",
Description = "Site description",
Lcid = 1033
});
var communicationSiteResult = await clientContext.CreateSiteAsync(new OfficeDevPnP.Core.Sites.CommunicationSiteCollectionCreationInformation()
{
Url = siteUrl2,
Title = "Modern no group Site Test",
Description = "Site description",
Lcid
});
SO, I created the app only registration in my tenant, then I tried this code and it says I am unauthorized.
The error I get is:
{
"Message": "An error has occurred.",
"ExceptionMessage": "Token request failed.",
"ExceptionType": "Microsoft.IdentityModel.SecurityTokenService.RequestFailedException",
"StackTrace": " at SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl, OAuth2AccessTokenRequest oauth2Request)\r\n at OfficeDevPnP.Core.Utilities.TokenHelper.GetAppOnlyAccessToken(String targetPrincipalName, String targetHost, String targetRealm)\r\n at OfficeDevPnP.Core.AuthenticationManager.EnsureToken(String siteUrl, String realm, String appId, String appSecret, String acsHostUrl, String globalEndPointPrefix)\r\n at OfficeDevPnP.Core.AuthenticationManager.GetAppOnlyAuthenticatedContext(String siteUrl, String realm, String appId, String appSecret, String acsHostUrl, String globalEndPointPrefix)\r\n at OfficeDevPnP.Core.AuthenticationManager.GetAppOnlyAuthenticatedContext(String siteUrl, String appId, String appSecret)\r\n at LuloWebApi.Controllers.TenantController.<Test>d__1.MoveNext() in C:\\Users\\levalencia30\\Source\\Repos\\LuloBackend\\TenantManagementWebApi\\Controllers\\TenantController.cs:line 42\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "The remote server returned an error: (401) Unauthorized.",
"ExceptionType": "System.Net.WebException",
"StackTrace": " at System.Net.HttpWebRequest.GetResponse()\r\n at SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2WebRequest.GetResponse()\r\n at SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl, OAuth2AccessTokenRequest oauth2Request)"
}
}
According to this issue it isn't possible using PnP as of yet. There is code change to address it in the Dev branch though so you could copy it and create your own CreateSiteAsync extension method and copy the sitecollection.cs into your own project.
Failing that you could call the Rest API yourself based on the code in the relevant CreateAsync method.
Edit: I could never get app only with a ClientId and secret to work. Try ClientId and Cert method outlined here
You cant do that PnP. You can try a code that changes it in the dev branch. This would allow you to copy it and make a CreateSiteAsync extension method and simply copy sitecollction.cs to your project.

About Microsoft.ServiceBus.Messaging.LeaseLostException

I got an exception of Microsoft.ServiceBus.Messaging.LeaseLostException, in my EventHub processor.
what does this exception mean? What is the possible root cause of this exception?
Following are stack track:
at Microsoft.ServiceBus.Messaging.BlobLeaseManager.d__24.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at Microsoft.ServiceBus.Messaging.BlobLeaseManager.d__25.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at MyEventHub.EventProcessor`1.d__6.MoveNext()\r\n\r\nMicrosoft.WindowsAzure.Storage.StorageException : \"The remote server returned an error: (409) Conflict.\":
at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 60\r\n
at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass4.b__3(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 115\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at Microsoft.ServiceBus.Messaging.BlobLeaseManager.d__24.MoveNext()\r\n\r\nSystem.Net.WebException : \"The remote server returned an error: (409) Conflict.\":
at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase1 cmd, Exception ex) in c:\\Program Files (x86)\\Jenkins\\workspace\\release_dotnet_master\\Lib\\Common\\Shared\\Protocol\\HttpResponseParsers.Common.cs:line 50\r\n
at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.<>c__DisplayClass33.<RenewLeaseImpl>b__32(RESTCommand1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 3186\r\n
at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 306"
And the only internal exception in my own code is:
at MyEventHub.EventProcessor`1.<< CloseAsync >> d__6.MoveNext()\r\n\r\nMicrosoft.WindowsAzure.Storage.StorageException : \"The remote server returned an error: (409) Conflict.\":
...
And here is the code of CloseAsync:
public async Task CloseAsync(PartitionContext context, CloseReason reason)
{
try
{
if (reason == CloseReason.Shutdown)
{
await context.CheckpointAsync();
}
}
catch (Exception ex)
{
this.HandleException(ex);
}
finally
{
this.configuration.DecrementOpenedPartitionCount?.Invoke();
}
}
MyEventHub is hosted in worker role which deployed 2 instance in Azure.
#Youxu , for your EventHub, how many receivers ( EventProcessorHost ) are configured?. As per my knowledge we can have only one active receiver with certain epoch. If we create a EventHub listener ( with default options) while one listener is already listing to a EventHub, newly created listener gets higher epoch and first listener gets disconnected due to LeaseLostException
Check if you are (accidentally) running more than one receiver for same EventHub concurrently.

IdentityServer3 DiscoveryDocument fails to load

I have an IdentityServer3 server setup and it's configured to use Entity Framework for getting client and scope information from the database.
When I add a new scope to the database (dbo.Scopes) if ShowInDiscoveryDocument = 0 then all is well and the well-known document loads correctly. However, if ShowInDiscoveryDocument = 1 then I get the following error:
Message: "An error has occurred.",
ExceptionMessage: "The type initializer for 'IdentityServer3.EntityFramework.Entities.EntitiesMap' threw an exception.",
ExceptionType: "System.TypeInitializationException",
StackTrace: " at IdentityServer3.EntityFramework.Entities.EntitiesMap.ToModel(Scope s) at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext() at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext() at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) at IdentityServer3.Core.Endpoints.DiscoveryEndpointController.d__11.MoveNext() in
c:\local\identity\server3\IdentityServer3\source\Core\Endpoints\Connect\DiscoveryEndpointController.cs:line 89 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Threading.Tasks.System.Web.Http908956.TaskHelpersExtensions.d__3`1.MoveNext() in c:\local\identity\server3\IdentityServer3\source\Core\Validation\ScopeValidator.cs:line 0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext() in c:\local\identity\server3\IdentityServer3\source\Core\Validation\ScopeValidator.cs:line 0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext() in c:\local\identity\server3\IdentityServer3\source\Core\Validation\ScopeValidator.cs:line 0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext() in c:\local\identity\server3\IdentityServer3\source\Core\Validation\ScopeValidator.cs:line 0",
InnerException: {
Message: "An error has occurred.",
ExceptionMessage: "Could not load type 'AutoMapper.IMapperConfiguration' from assembly 'AutoMapper, Version=5.0.2.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005'.",
ExceptionType: "System.TypeLoadException",
StackTrace: " at IdentityServer3.EntityFramework.Entities.EntitiesMap..cctor()"
this problem has been reported and I think fixed in the sources, I do not know if the nugget package has the fix yet.

Resources