Skip to content

Instantly share code, notes, and snippets.

@rido-min
Created April 13, 2021 20:31
Show Gist options
  • Save rido-min/875219fda5ceb983a2c35fcb61e8934c to your computer and use it in GitHub Desktop.
Save rido-min/875219fda5ceb983a2c35fcb61e8934c to your computer and use it in GitHub Desktop.
UpdateComplexObjectWithDT
using Microsoft.Azure.Devices;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Serialization;
using Microsoft.Azure.Devices.Shared;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
namespace rido_learn_WritableProperties
{
class Program
{
class CommandArguments : BasicDigitalTwin
{
[JsonProperty("$metadata")]
public new CommandArgumentsMetadata Metadata { get; set; }
public string CommandId { get; set; }
[JsonProperty("Arguments", NullValueHandling = NullValueHandling.Ignore)]
public string Arguments { get; set; }
[JsonProperty("Action", NullValueHandling = NullValueHandling.Ignore)]
public int? Action { get; set; }
}
class CommandArgumentsMetadata : DigitalTwinMetadata
{
[JsonProperty("CommandArguments")]
public WritableProperty CommandArguments { get; set; }
}
static async Task Main(string[] args)
{
var cs = "HostName=.azure-devices.net;DeviceId=osConfigDemo;SharedAccessKey=";
var client = DeviceClient.CreateFromConnectionString(cs,
Microsoft.Azure.Devices.Client.TransportType.Mqtt_WebSocket_Only,
new ClientOptions { ModelId = "dtmi:osconfig:commandrunner;1" });
await client.SetDesiredPropertyUpdateCallbackAsync(async (TwinCollection desiredProperties, object userContext) =>
{
Console.WriteLine(desiredProperties.ToJson(Formatting.Indented));
}, null);
await ServiceUpdate();
Console.ReadLine();
}
static async Task ServiceUpdate()
{
var scs = "HostName=.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=";
DigitalTwinClient dtc = DigitalTwinClient.CreateFromConnectionString(scs);
CommandArguments cmdArgs = new CommandArguments { CommandId = "One", Arguments = "argsOne", Action = 1 };
var updateOperation = new UpdateOperationsUtility();
updateOperation.AppendAddPropertyOp("/CommandArguments", cmdArgs);
var op = updateOperation.Serialize();
Console.WriteLine(op);
await dtc.UpdateDigitalTwinAsync("osConfigDemo", op);
}
}
}
@rido-min
Copy link
Author

this code sends

[
    {
        "op": "add",
        "path": "/CommandArguments",
        "value": {
            "$metadata": {},
            "CommandId": "One",
            "Arguments": "argsOne",
            "Action": 1
        }
    }
]

produces the next twin, note the __t:c marker that is not expected

{
  "CommandArguments": {
    "__t": "c",
    "CommandId": "One",
    "Arguments": "argsOne",
    "Action": 1
  },
  "$version": 11
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment