Skip to content

Commit

Permalink
fix(adt): fix BasicDigitalTwin and use in an example (#12428)
Browse files Browse the repository at this point in the history
  • Loading branch information
David R. Williamson authored Jun 2, 2020
1 parent be83d78 commit 96f7858
Show file tree
Hide file tree
Showing 13 changed files with 181 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,11 @@ public static partial class QueryChargeHelper
}
namespace Azure.DigitalTwins.Core.Serialization
{
public partial class BasicDigitalTwin
public partial class BasicDigitalTwin : Azure.DigitalTwins.Core.Serialization.ModelProperties
{
public BasicDigitalTwin() { }
[System.Text.Json.Serialization.JsonExtensionDataAttribute]
public System.Collections.Generic.IDictionary<string, object> CustomProperties { get { throw null; } set { } }
[System.Text.Json.Serialization.JsonPropertyNameAttribute("$dtId")]
public string Id { get { throw null; } set { } }
[System.Text.Json.Serialization.JsonPropertyNameAttribute("$metadata")]
public Azure.DigitalTwins.Core.Serialization.DigitalTwinMetadata Metadata { get { throw null; } set { } }
}
public partial class BasicRelationship
{
Expand All @@ -152,7 +148,15 @@ public DigitalTwinMetadata() { }
[System.Text.Json.Serialization.JsonPropertyNameAttribute("$model")]
public string ModelId { get { throw null; } set { } }
[System.Text.Json.Serialization.JsonExtensionDataAttribute]
public System.Collections.Generic.IDictionary<string, object> ModelProperties { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, object> WriteableProperties { get { throw null; } set { } }
}
public partial class ModelProperties
{
public ModelProperties() { }
[System.Text.Json.Serialization.JsonExtensionDataAttribute]
public System.Collections.Generic.IDictionary<string, object> CustomProperties { get { throw null; } set { } }
[System.Text.Json.Serialization.JsonPropertyNameAttribute("$metadata")]
public Azure.DigitalTwins.Core.Serialization.DigitalTwinMetadata Metadata { get { throw null; } set { } }
}
public partial class UpdateOperationsUtility
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.DigitalTwins.Core.Serialization;
using static Azure.DigitalTwins.Core.Samples.SampleLogger;
Expand Down Expand Up @@ -30,54 +32,69 @@ public async Task RunSamplesAsync()

string componentModelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryComponentModelPrefix, DigitalTwinsClient).ConfigureAwait(false);
string modelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryModelPrefix, DigitalTwinsClient).ConfigureAwait(false);
string twinId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, DigitalTwinsClient).ConfigureAwait(false);
string dtId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, DigitalTwinsClient).ConfigureAwait(false);

string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.Replace(SamplesConstants.ComponentId, componentModelId);

string newModelPayload = SamplesConstants.TemporaryModelPayload
string newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.Replace(SamplesConstants.ModelId, modelId)
.Replace(SamplesConstants.ComponentId, componentModelId);

// Then we create models
await DigitalTwinsClient.CreateModelsAsync(new[] { newComponentModelPayload, newModelPayload }).ConfigureAwait(false);
Console.WriteLine($"Successfully created models with Ids: {componentModelId}, {modelId}");
Response<IReadOnlyList<Models.ModelData>> createModelsResponse = await DigitalTwinsClient
.CreateModelsAsync(new[] { newComponentModelPayload, newModelPayload })
.ConfigureAwait(false);
Console.WriteLine($"Successfully created models Ids {componentModelId} and {modelId} with response {createModelsResponse.GetRawResponse().Status}.");

// Create digital twin with Component payload
string twinPayload = SamplesConstants.TemporaryTwinPayload
.Replace(SamplesConstants.ModelId, modelId)
.Replace(SamplesConstants.ComponentId, componentModelId);
#region Snippet:DigitalTwinsSampleCreateBasicTwin

await DigitalTwinsClient.CreateDigitalTwinAsync(twinId, twinPayload).ConfigureAwait(false);
Console.WriteLine($"Created digital twin {twinId}.");
// Create digital twin with Component payload using the BasicDigitalTwin serialization helper

#region Snippet:DigitalTwinsSampleUpdateComponent
var basicDigitalTwin = new BasicDigitalTwin();
basicDigitalTwin.Metadata.ModelId = modelId;
basicDigitalTwin.CustomProperties.Add("Prop1", "Value1");
basicDigitalTwin.CustomProperties.Add("Prop2", "Value2");

var componentMetadata = new ModelProperties();
componentMetadata.Metadata.ModelId = componentModelId;
componentMetadata.CustomProperties.Add("ComponentProp1", "ComponentValue1");
componentMetadata.CustomProperties.Add("ComponentProp2", "ComponentValue2");

// Update Component with replacing property value
string propertyPath = "/ComponentProp1";
string propValue = "New Value";
basicDigitalTwin.CustomProperties.Add("Component1", componentMetadata);

string dtPayload = JsonSerializer.Serialize(basicDigitalTwin, new JsonSerializerOptions { IgnoreNullValues = true });

Response<string> createDtResponse = await DigitalTwinsClient.CreateDigitalTwinAsync(dtId, dtPayload).ConfigureAwait(false);
Console.WriteLine($"Created digital twin {dtId} with response {createDtResponse.GetRawResponse().Status}.");

#endregion Snippet:DigitalTwinsSampleCreateBasicTwin

#region Snippet:DigitalTwinsSampleUpdateComponent

// Update Component1 by replacing the property ComponentProp1 value
var componentUpdateUtility = new UpdateOperationsUtility();
componentUpdateUtility.AppendReplaceOp(propertyPath, propValue);
componentUpdateUtility.AppendReplaceOp("/ComponentProp1", "Some new value");
string updatePayload = componentUpdateUtility.Serialize();

Response<string> response = await DigitalTwinsClient.UpdateComponentAsync(twinId, SamplesConstants.ComponentPath, componentUpdateUtility.Serialize());
Response<string> response = await DigitalTwinsClient.UpdateComponentAsync(dtId, "Component1", updatePayload);

#endregion Snippet:DigitalTwinsSampleUpdateComponent
Console.WriteLine($"Updated component for digital twin {dtId}. Update response status: {response.GetRawResponse().Status}");

Console.WriteLine($"Updated component for digital twin {twinId}. Update response status: {response.GetRawResponse().Status}");
#endregion Snippet:DigitalTwinsSampleUpdateComponent

// Get Component

#region Snippet:DigitalTwinsSampleGetComponent

response = await DigitalTwinsClient.GetComponentAsync(twinId, SamplesConstants.ComponentPath).ConfigureAwait(false);

#endregion Snippet:DigitalTwinsSampleGetComponent
response = await DigitalTwinsClient.GetComponentAsync(dtId, SamplesConstants.ComponentPath).ConfigureAwait(false);

Console.WriteLine($"Get component for digital twin: \n{response.Value}. Get response status: {response.GetRawResponse().Status}");

#endregion Snippet:DigitalTwinsSampleGetComponent

// Now delete a Twin
await DigitalTwinsClient.DeleteDigitalTwinAsync(twinId).ConfigureAwait(false);
await DigitalTwinsClient.DeleteDigitalTwinAsync(dtId).ConfigureAwait(false);

// Delete models
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,12 +263,8 @@ public async Task CreateAllTwinsAsync()
{
try
{
#region Snippet:DigitalTwinsSampleCreateTwin

Response<string> response = await DigitalTwinsClient.CreateDigitalTwinAsync(twin.Key, twin.Value).ConfigureAwait(false);

#endregion Snippet:DigitalTwinsSampleCreateTwin

Console.WriteLine($"Created digital twin {twin.Key}. Create response status: {response.GetRawResponse().Status}");
Console.WriteLine($"Body: {response?.Value}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public async Task RunSamplesAsync()
string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.Replace(SamplesConstants.ComponentId, newComponentModelId);

string newModelPayload = SamplesConstants.TemporaryModelPayload
string newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.Replace(SamplesConstants.ModelId, sampleModelId)
.Replace(SamplesConstants.ComponentId, newComponentModelId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task RunSamplesAsync()
string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.Replace(SamplesConstants.ComponentId, componentModelId);

string newModelPayload = SamplesConstants.TemporaryModelPayload
string newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.Replace(SamplesConstants.ModelId, modelId)
.Replace(SamplesConstants.ComponentId, componentModelId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static class SamplesConstants
/// <summary>
/// The application/json description of a temporary model
/// </summary>
public const string TemporaryModelPayload = @"
public const string TemporaryModelWithComponentPayload = @"
{
""@id"": ""MODEL_ID"",
""@type"": ""Interface"",
Expand Down
37 changes: 28 additions & 9 deletions sdk/digitaltwins/Azure.DigitalTwins.Core/samples/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,25 @@ catch (Exception ex)

For Creating Twin you will need to provide Id of a digital Twin such as `myTwin` and the application/json digital twin based on the model created earlier. You can look at sample application/json [here](https://github.com/Azure/azure-sdk-for-net-pr/tree/feature/IoT-ADT/sdk/digitaltwins/Azure.DigitalTwins.Core/samples/DigitalTwinsClientSample/DTDL/DigitalTwins "DigitalTwin").

```C# Snippet:DigitalTwinsSampleCreateTwin
Response<string> response = await DigitalTwinsClient.CreateDigitalTwinAsync(twin.Key, twin.Value).ConfigureAwait(false);
```C# Snippet:DigitalTwinsSampleCreateBasicTwin
// Create digital twin with Component payload using the BasicDigitalTwin serialization helper
var basicDigitalTwin = new BasicDigitalTwin();
basicDigitalTwin.Metadata.ModelId = modelId;
basicDigitalTwin.CustomProperties.Add("Prop1", "Value1");
basicDigitalTwin.CustomProperties.Add("Prop2", "Value2");

var componentMetadata = new ModelProperties();
componentMetadata.Metadata.ModelId = componentModelId;
componentMetadata.CustomProperties.Add("ComponentProp1", "ComponentValue1");
componentMetadata.CustomProperties.Add("ComponentProp2", "ComponentValue2");

basicDigitalTwin.CustomProperties.Add("Component1", componentMetadata);

string dtPayload = JsonSerializer.Serialize(basicDigitalTwin, new JsonSerializerOptions { IgnoreNullValues = true });

Response<string> createDtResponse = await DigitalTwinsClient.CreateDigitalTwinAsync(dtId, dtPayload).ConfigureAwait(false);
Console.WriteLine($"Created digital twin {dtId} with response {createDtResponse.GetRawResponse().Status}.");
```

### Query Digital Twin
Expand Down Expand Up @@ -190,22 +207,24 @@ await DigitalTwinsClient.DeleteDigitalTwinAsync(twin.Key).ConfigureAwait(false);
To update a component or in other words to replace, remove and/or add a component property or subproperty within Digital Twin, you would need id of a digital twin, component name and application/json-patch+json operations to be performed on the specified digital twin's component. Here is the sample code on how to do it.

```C# Snippet:DigitalTwinsSampleUpdateComponent
// Update Component with replacing property value
string propertyPath = "/ComponentProp1";
string propValue = "New Value";

// Update Component1 by replacing the property ComponentProp1 value
var componentUpdateUtility = new UpdateOperationsUtility();
componentUpdateUtility.AppendReplaceOp(propertyPath, propValue);
componentUpdateUtility.AppendReplaceOp("/ComponentProp1", "Some new value");
string updatePayload = componentUpdateUtility.Serialize();

Response<string> response = await DigitalTwinsClient.UpdateComponentAsync(twinId, SamplesConstants.ComponentPath, componentUpdateUtility.Serialize());
Response<string> response = await DigitalTwinsClient.UpdateComponentAsync(dtId, "Component1", updatePayload);

Console.WriteLine($"Updated component for digital twin {dtId}. Update response status: {response.GetRawResponse().Status}");
```

### Get Digital Twin Component

Get a component by providing name of a component and id of digital twin it belongs to.

```C# Snippet:DigitalTwinsSampleGetComponent
response = await DigitalTwinsClient.GetComponentAsync(twinId, SamplesConstants.ComponentPath).ConfigureAwait(false);
response = await DigitalTwinsClient.GetComponentAsync(dtId, SamplesConstants.ComponentPath).ConfigureAwait(false);

Console.WriteLine($"Get component for digital twin: \n{response.Value}. Get response status: {response.GetRawResponse().Status}");
```

## Create and list Digital Twin edges
Expand Down
Loading

0 comments on commit 96f7858

Please sign in to comment.