While updating the digitaltwin instance using the function app I am getting error :
ManagedIdentityCredential authentication failed: Service request failed.Status: 400 (Bad Request)Content:Headers:Date: Wed, 03 Aug 2022 17:24:18 GMTServer: KestrelTransfer-Encoding: chunkedX-CORRELATION-ID: REDACTEDContent-Type: application/json; charset=utf-8See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
A simple function app code :
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;
using Azure.DigitalTwins.Core;
using Azure.Identity;
using System.Net.Http;
using Azure.Core.Pipeline;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Azure;
namespace factorytwiningestfunction
{
public static class Function1
{
private static readonly string adtInstanceUrl = Environment.GetEnvironmentVariable("ADT_SERVICE_URL");
private static readonly HttpClient singletonHttpClientInstance = new HttpClient();
[FunctionName("IOTHubtoTwins")]
public async static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
{
if (adtInstanceUrl == null) log.LogError("Application setting \"ADT_SERVICE_URL\" not set");
try
{
var cred = new ManagedIdentityCredential("https://digitaltwins.azure.net");
var client = new DigitalTwinsClient(
new Uri(adtInstanceUrl),
cred,
new DigitalTwinsClientOptions
{
Transport = new HttpClientTransport(singletonHttpClientInstance)
});
log.LogInformation($"ADT service client connection created.");
if (eventGridEvent != null && eventGridEvent.Data != null)
{
log.LogInformation(eventGridEvent.Data.ToString());
// convert the message into a json object
JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
log.LogInformation($"object is :{deviceMessage.ToString()}");
// get our device id, temp and humidity from the object
string deviceId = (string)deviceMessage["systemProperties"]["iothub-connection-device-id"];
//var temperature = deviceMessage["body"]["Temperature"];
//var humidity = deviceMessage["body"]["Humidity"];
var distance = deviceMessage["body"]["Distance"];
//log the temperature and humidity
log.LogInformation($"Device:{deviceId} distance is:{distance}");
// Update twin with temperature and humidity fro our raspberry pi>
var updateTwinData = new JsonPatchDocument();
updateTwinData.AppendReplace("/Distance", distance.Value<int>());
await client.UpdateDigitalTwinAsync(deviceId, updateTwinData);
}
}
catch (Exception ex)
{
log.LogError($"Error in ingest function: {ex.Message}");
}
}
}
}
Please do advise what am I doing wrong?
Thank you.