Skip to content

Commit

Permalink
samples(adt): misc minor clean-up from Azure SDK review (#12488)
Browse files Browse the repository at this point in the history
  • Loading branch information
David R. Williamson authored Jun 4, 2020
1 parent ad21e16 commit 772f886
Show file tree
Hide file tree
Showing 11 changed files with 171 additions and 197 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,19 @@ namespace Azure.DigitalTwins.Core.Samples
{
internal class ComponentSamples
{
private DigitalTwinsClient DigitalTwinsClient { get; }

public ComponentSamples(DigitalTwinsClient dtClient)
{
DigitalTwinsClient = dtClient;
}

/// <summary>
/// Creates a digital twin with Component and upates Component
/// </summary>
public async Task RunSamplesAsync()
public async Task RunSamplesAsync(DigitalTwinsClient client)
{
PrintHeader("COMPONENT SAMPLE");

// For the purpose of this example we will create temporary models using a random model Ids.
// We have to make sure these model Ids are unique within the DT instance.

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

string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.Replace(SamplesConstants.ComponentId, componentModelId);
Expand All @@ -43,9 +36,9 @@ public async Task RunSamplesAsync()
.Replace(SamplesConstants.ComponentId, componentModelId);

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

#region Snippet:DigitalTwinsSampleCreateBasicTwin
Expand All @@ -69,7 +62,7 @@ public async Task RunSamplesAsync()

string basicDtPayload = JsonSerializer.Serialize(basicDigitalTwin);

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

#endregion Snippet:DigitalTwinsSampleCreateBasicTwin
Expand All @@ -80,7 +73,7 @@ public async Task RunSamplesAsync()

#region Snippet:DigitalTwinsSampleGetBasicDigitalTwin

Response<string> getBasicDtResponse = await DigitalTwinsClient.GetDigitalTwinAsync(basicDtId).ConfigureAwait(false);
Response<string> getBasicDtResponse = await client.GetDigitalTwinAsync(basicDtId);
if (getBasicDtResponse.GetRawResponse().Status == (int)HttpStatusCode.OK)
{
BasicDigitalTwin basicDt = JsonSerializer.Deserialize<BasicDigitalTwin>(getBasicDtResponse.Value);
Expand All @@ -102,7 +95,7 @@ public async Task RunSamplesAsync()

#region Snippet:DigitalTwinsSampleCreateCustomTwin

string customDtId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, DigitalTwinsClient).ConfigureAwait(false);
string customDtId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, client);
var customDigitalTwin = new CustomDigitalTwin
{
Id = customDtId,
Expand All @@ -118,7 +111,7 @@ public async Task RunSamplesAsync()
};
string dt2Payload = JsonSerializer.Serialize(customDigitalTwin);

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

#endregion Snippet:DigitalTwinsSampleCreateCustomTwin
Expand All @@ -128,7 +121,7 @@ public async Task RunSamplesAsync()

#region Snippet:DigitalTwinsSampleGetCustomDigitalTwin

Response<string> getCustomDtResponse = await DigitalTwinsClient.GetDigitalTwinAsync(customDtId).ConfigureAwait(false);
Response<string> getCustomDtResponse = await client.GetDigitalTwinAsync(customDtId);
if (getCustomDtResponse.GetRawResponse().Status == (int)HttpStatusCode.OK)
{
CustomDigitalTwin customDt = JsonSerializer.Deserialize<CustomDigitalTwin>(getCustomDtResponse.Value);
Expand All @@ -146,7 +139,7 @@ public async Task RunSamplesAsync()
componentUpdateUtility.AppendReplaceOp("/ComponentProp1", "Some new value");
string updatePayload = componentUpdateUtility.Serialize();

Response<string> response = await DigitalTwinsClient.UpdateComponentAsync(basicDtId, "Component1", updatePayload);
Response<string> response = await client.UpdateComponentAsync(basicDtId, "Component1", updatePayload);

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

Expand All @@ -156,7 +149,7 @@ public async Task RunSamplesAsync()

#region Snippet:DigitalTwinsSampleGetComponent

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

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

Expand All @@ -166,8 +159,8 @@ public async Task RunSamplesAsync()

try
{
await DigitalTwinsClient.DeleteDigitalTwinAsync(basicDtId).ConfigureAwait(false);
await DigitalTwinsClient.DeleteDigitalTwinAsync(customDtId).ConfigureAwait(false);
await client.DeleteDigitalTwinAsync(basicDtId);
await client.DeleteDigitalTwinAsync(customDtId);
}
catch (RequestFailedException ex)
{
Expand All @@ -176,8 +169,8 @@ public async Task RunSamplesAsync()

try
{
await DigitalTwinsClient.DeleteModelAsync(modelId).ConfigureAwait(false);
await DigitalTwinsClient.DeleteModelAsync(componentModelId).ConfigureAwait(false);
await client.DeleteModelAsync(modelId);
await client.DeleteModelAsync(componentModelId);
}
catch (RequestFailedException ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
using Azure.DigitalTwins.Core.Queries;
using Azure.DigitalTwins.Core.Serialization;
using static Azure.DigitalTwins.Core.Samples.SampleLogger;
using static Azure.DigitalTwins.Core.Samples.UniqueIdHelper;

namespace Azure.DigitalTwins.Core.Samples
{
Expand Down Expand Up @@ -50,15 +49,15 @@ internal class DigitalTwinsLifecycleSamples
private static readonly string s_twinsPath = Path.Combine(s_dtdlDirectoryPath, "DigitalTwins");
private static readonly string s_relationshipsPath = Path.Combine(s_dtdlDirectoryPath, "Relationships");

private readonly string _eventhubEndpointName;
private readonly string _eventRouteId = $"sampleEventRouteId-{Guid.NewGuid()}";

private DigitalTwinsClient DigitalTwinsClient { get; }
private readonly string eventhubEndpointName;
private readonly DigitalTwinsClient client;

public DigitalTwinsLifecycleSamples(DigitalTwinsClient dtClient, string eventhubEndpointName)
{
_eventhubEndpointName = eventhubEndpointName;
DigitalTwinsClient = dtClient;
this.eventhubEndpointName = eventhubEndpointName;
client = dtClient;
}

/// <summary>
Expand All @@ -69,34 +68,34 @@ public DigitalTwinsLifecycleSamples(DigitalTwinsClient dtClient, string eventhub
public async Task RunSamplesAsync()
{
// Ensure existing twins with the same name are deleted first
await DeleteTwinsAsync().ConfigureAwait(false);
await DeleteTwinsAsync();

// Delete existing models
await DeleteAllModelsAsync().ConfigureAwait(false);
await DeleteAllModelsAsync();

// Create all the models
await AddAllModelsAsync().ConfigureAwait(false);
await AddAllModelsAsync();

// Get all models
await GetAllModelsAsync().ConfigureAwait(false);
await GetAllModelsAsync();

// Create twin counterparts for all the models
await CreateAllTwinsAsync().ConfigureAwait(false);
await CreateAllTwinsAsync();

// Get all twins
await QueryTwinsAsync().ConfigureAwait(false);
await QueryTwinsAsync();

// Create all the relationships
await ConnectTwinsTogetherAsync().ConfigureAwait(false);
await ConnectTwinsTogetherAsync();

// Creating event route
await CreateEventRoute().ConfigureAwait(false);
await CreateEventRoute();

// Get all event routes
await GetEventRoutes().ConfigureAwait(false);
await GetEventRoutes();

// Deleting event route
await DeleteEventRoute().ConfigureAwait(false);
await DeleteEventRoute();
}

/// <summary>
Expand All @@ -119,7 +118,7 @@ private async Task DeleteAllModelsAsync()

foreach (string modelId in models)
{
await DigitalTwinsClient.DeleteModelAsync(modelId).ConfigureAwait(false);
await client.DeleteModelAsync(modelId);
Console.WriteLine($"Deleted model {modelId}");
}
}
Expand Down Expand Up @@ -149,7 +148,7 @@ private async Task AddAllModelsAsync()

try
{
Response<IReadOnlyList<ModelData>> response = await DigitalTwinsClient.CreateModelsAsync(modelsToCreate).ConfigureAwait(false);
Response<IReadOnlyList<ModelData>> response = await client.CreateModelsAsync(modelsToCreate);
Console.WriteLine($"Created models status: {response.GetRawResponse().Status}");
}
catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict)
Expand All @@ -174,15 +173,15 @@ public async Task GetAllModelsAsync()

#region Snippet:DigitalTwinsSampleGetModels

AsyncPageable<ModelData> allModels = DigitalTwinsClient.GetModelsAsync();
AsyncPageable<ModelData> allModels = client.GetModelsAsync();
await foreach (ModelData model in allModels)
{
Console.WriteLine($"Model Id: {model.Id}, display name: {model.DisplayName["en"]}, upload time: {model.UploadTime}, is decommissioned: {model.Decommissioned}");
}

#endregion Snippet:DigitalTwinsSampleGetModels
}
catch (Exception ex)
catch (RequestFailedException ex)
{
FatalError($"Failed to get all the models due to:\n{ex}");
}
Expand All @@ -204,36 +203,36 @@ public async Task DeleteTwinsAsync()

#region Snippet:DigitalTwinsSampleGetRelationships

AsyncPageable<string> relationships = DigitalTwinsClient.GetRelationshipsAsync(twin.Key);
AsyncPageable<string> relationships = client.GetRelationshipsAsync(twin.Key);

#endregion Snippet:DigitalTwinsSampleGetRelationships

await foreach (var relationshipJson in relationships)
{
BasicRelationship relationship = JsonSerializer.Deserialize<BasicRelationship>(relationshipJson);
await DigitalTwinsClient.DeleteRelationshipAsync(twin.Key, relationship.Id).ConfigureAwait(false);
await client.DeleteRelationshipAsync(twin.Key, relationship.Id);
Console.WriteLine($"Found and deleted relationship {relationship.Id}");
}

// Delete any incoming relationships

#region Snippet:DigitalTwinsSampleGetIncomingRelationships

AsyncPageable<IncomingRelationship> incomingRelationships = DigitalTwinsClient.GetIncomingRelationshipsAsync(twin.Key);
AsyncPageable<IncomingRelationship> incomingRelationships = client.GetIncomingRelationshipsAsync(twin.Key);

#endregion Snippet:DigitalTwinsSampleGetIncomingRelationships

await foreach (IncomingRelationship incomingRelationship in incomingRelationships)
{
await DigitalTwinsClient.DeleteRelationshipAsync(incomingRelationship.SourceId, incomingRelationship.RelationshipId).ConfigureAwait(false);
await client.DeleteRelationshipAsync(incomingRelationship.SourceId, incomingRelationship.RelationshipId);
Console.WriteLine($"Found and deleted incoming relationship {incomingRelationship.RelationshipId}");
}

// Now the digital twin should be safe to delete

#region Snippet:DigitalTwinsSampleDeleteTwin

await DigitalTwinsClient.DeleteDigitalTwinAsync(twin.Key).ConfigureAwait(false);
await client.DeleteDigitalTwinAsync(twin.Key);

#endregion Snippet:DigitalTwinsSampleDeleteTwin

Expand Down Expand Up @@ -263,7 +262,7 @@ public async Task CreateAllTwinsAsync()
{
try
{
Response<string> response = await DigitalTwinsClient.CreateDigitalTwinAsync(twin.Key, twin.Value).ConfigureAwait(false);
Response<string> response = await client.CreateDigitalTwinAsync(twin.Key, twin.Value);

Console.WriteLine($"Created digital twin {twin.Key}. Create response status: {response.GetRawResponse().Status}");
Console.WriteLine($"Body: {response?.Value}");
Expand All @@ -287,7 +286,7 @@ public async Task QueryTwinsAsync()

// This code snippet demonstrates the simplest way to iterate over the digital twin results, where paging
// happens under the covers.
AsyncPageable<string> asyncPageableResponse = DigitalTwinsClient.QueryAsync("SELECT * FROM digitaltwins");
AsyncPageable<string> asyncPageableResponse = client.QueryAsync("SELECT * FROM digitaltwins");

// Iterate over the twin instances in the pageable response.
// The "await" keyword here is required because new pages will be fetched when necessary,
Expand All @@ -308,7 +307,7 @@ public async Task QueryTwinsAsync()
// the query API. It iterates over the response pages first to access to the query-charge header,
// and then the digital twin results within each page.

AsyncPageable<string> asyncPageableResponseWithCharge = DigitalTwinsClient.QueryAsync("SELECT * FROM digitaltwins");
AsyncPageable<string> asyncPageableResponseWithCharge = client.QueryAsync("SELECT * FROM digitaltwins");
int pageNum = 0;

// The "await" keyword here is required as a call is made when fetching a new page.
Expand Down Expand Up @@ -363,12 +362,10 @@ public async Task ConnectTwinsTogetherAsync()

string serializedRelationship = JsonSerializer.Serialize(relationship);

await DigitalTwinsClient
.CreateRelationshipAsync(
relationship.SourceId,
relationship.Id,
serializedRelationship)
.ConfigureAwait(false);
await client.CreateRelationshipAsync(
relationship.SourceId,
relationship.Id,
serializedRelationship);

#endregion Snippet:DigitalTwinsSampleCreateRelationship

Expand All @@ -392,7 +389,7 @@ public async Task GetEventRoutes()
{
#region Snippet:DigitalTwinsSampleGetEventRoutes

AsyncPageable<EventRoute> response = DigitalTwinsClient.GetEventRoutesAsync();
AsyncPageable<EventRoute> response = client.GetEventRoutesAsync();
await foreach (EventRoute er in response)
{
Console.WriteLine($"Event route: {er.Id}, endpoint name: {er.EndpointName}");
Expand All @@ -417,12 +414,12 @@ public async Task CreateEventRoute()
#region Snippet:DigitalTwinsSampleCreateEventRoute

string eventFilter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
var eventRoute = new EventRoute(_eventhubEndpointName)
var eventRoute = new EventRoute(eventhubEndpointName)
{
Filter = eventFilter
};

Response createEventRouteResponse = await DigitalTwinsClient.CreateEventRouteAsync(_eventRouteId, eventRoute).ConfigureAwait(false);
Response createEventRouteResponse = await client.CreateEventRouteAsync(_eventRouteId, eventRoute);

#endregion Snippet:DigitalTwinsSampleCreateEventRoute

Expand All @@ -444,7 +441,7 @@ public async Task DeleteEventRoute()
{
#region Snippet:DigitalTwinsSampleDeleteEventRoute

Response response = await DigitalTwinsClient.DeleteEventRouteAsync(_eventRouteId).ConfigureAwait(false);
Response response = await client.DeleteEventRouteAsync(_eventRouteId);

#endregion Snippet:DigitalTwinsSampleDeleteEventRoute

Expand Down
Loading

0 comments on commit 772f886

Please sign in to comment.