Skip to content

Commit

Permalink
[TSI] Add a sample for Time Series Insights Instances (#20403)
Browse files Browse the repository at this point in the history
  • Loading branch information
Basel Rustum authored Apr 15, 2021
1 parent 7ecf582 commit 74b9aa0
Show file tree
Hide file tree
Showing 5 changed files with 289 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using static Azure.IoT.TimeSeriesInsights.Samples.SampleLogger;

namespace Azure.IoT.TimeSeriesInsights.Samples
{
internal class InstancesSamples
{
/// <summary>
/// </summary>
public async Task RunSamplesAsync(TimeSeriesInsightsClient client)
{
PrintHeader("TIME SERIES INSIGHTS INSTANCES SAMPLE");

// Figure out how many keys make up the Time Series Id
TimeSeriesModelSettings modelSettings = await client.ModelSettings.GetAsync().ConfigureAwait(false);

TimeSeriesId instanceId = modelSettings.TimeSeriesIdProperties.Count switch
{
1 => new TimeSeriesId("key1"),
2 => new TimeSeriesId("key1", "key2"),
3 => new TimeSeriesId("key1", "key2", "key3"),
_ => throw new Exception($"Invalid number of Time Series Insights Id properties."),
};

#region Snippet:TimeSeriesInsightsSampleCreateInstance

// Create a Time Series Instance object with the default Time Series Insights type Id.
// The default type Id can be obtained programmatically by using the ModelSettings client.
var instance = new TimeSeriesInstance(instanceId, "1be09af9-f089-4d6b-9f0b-48018b5f7393")
{
Name = "instance1",
};

var tsiInstancesToCreate = new List<TimeSeriesInstance>
{
instance,
};

Response<TimeSeriesOperationError[]> createInstanceErrors = await client
.Instances
.CreateOrReplaceAsync(tsiInstancesToCreate)
.ConfigureAwait(false);

// The response of calling the API contains a list of error objects corresponding by position to the input parameter
// array in the request. If the error object is set to null, this means the operation was a success.
if (createInstanceErrors.Value[0] == null)
{
Console.WriteLine($"Created Time Series Insights instance with Id '{instanceId}'.");
}
else
{
Console.WriteLine($"Failed to create a Time Series Insights instance: {createInstanceErrors.Value[0].Message}.");
}

#endregion Snippet:TimeSeriesInsightsSampleCreateInstance

#region Snippet:TimeSeriesInsightsGetAllInstances

// Get all instances for the Time Series Insigths environment
AsyncPageable<TimeSeriesInstance> tsiInstances = client.Instances.GetAsync();
await foreach (TimeSeriesInstance tsiInstance in tsiInstances)
{
Console.WriteLine($"Retrieved Time Series Insights instance with Id '{tsiInstance.TimeSeriesId}' and name '{tsiInstance.Name}'.");
}

#endregion Snippet:TimeSeriesInsightsGetAllInstances

#region Snippet:TimeSeriesInsightsReplaceInstance

// Get Time Series Insights instances by Id
var instanceIdsToGet = new List<TimeSeriesId>
{
instanceId,
};

Response<InstancesOperationResult[]> getInstancesByIdResult = await client.Instances.GetAsync(instanceIdsToGet).ConfigureAwait(false);

TimeSeriesInstance instanceResult = getInstancesByIdResult.Value[0].Instance;
Console.WriteLine($"Retrieved Time Series Insights instance with Id '{instanceResult.TimeSeriesId}' and name '{instanceResult.Name}'.");

// Now let's replace the instance with an updated name
instanceResult.Name = "newInstanceName";

var instancesToReplace = new List<TimeSeriesInstance>
{
instanceResult,
};

Response<InstancesOperationResult[]> replaceInstancesResult = await client.Instances.ReplaceAsync(instancesToReplace).ConfigureAwait(false);

// The response of calling the API contains a list of error objects corresponding by position to the input parameter
// array in the request. If the error object is set to null, this means the operation was a success.
if (replaceInstancesResult.Value[0].Error != null)
{
Console.WriteLine($"Failed to retrieve a Time Series Insights instnace with Id '{replaceInstancesResult.Value[0].Error.Message}'.");
}

#endregion Snippet:TimeSeriesInsightsReplaceInstance

#region Snippet:TimeSeriesInsightsGetnstancesById

// Get Time Series Insights instances by Id
var timeSeriesIds = new List<TimeSeriesId>
{
instanceId,
};

Response<InstancesOperationResult[]> getInstancesByNameResult = await client.Instances.GetAsync(timeSeriesIds).ConfigureAwait(false);

/// The response of calling the API contains a list of instance or error objects corresponding by position to the array in the request.
/// Instance object is set when operation is successful and error object is set when operation is unsuccessful.
InstancesOperationResult getInstanceByIdResult = getInstancesByNameResult.Value[0];
if (getInstanceByIdResult.Instance != null)
{
Console.WriteLine($"Retrieved Time Series Insights instance with Id '{getInstanceByIdResult.Instance.TimeSeriesId}' and name '{getInstanceByIdResult.Instance.Name}'.");
}
else if (getInstanceByIdResult.Error != null)
{
Console.WriteLine($"Failed to retrieve a Time Series Insights instnace with Id '{getInstanceByIdResult.Error.Message}'.");
}

#endregion Snippet:TimeSeriesInsightsGetnstancesById

// Clean up
try
{
#region Snippet:TimeSeriesInsightsSampleDeleteInstance

Response<TimeSeriesOperationError[]> deleteInstanceErrors = await client
.Instances
.DeleteAsync(new List<TimeSeriesId> { instanceId })
.ConfigureAwait(false);

// The response of calling the API contains a list of error objects corresponding by position to the input parameter
// array in the request. If the error object is set to null, this means the operation was a success.
if (deleteInstanceErrors.Value[0] == null)
{
Console.WriteLine($"Deleted Time Series Insights instance with Id '{instanceId}'.");
}
else
{
Console.WriteLine($"Failed to delete a Time Series Insights instance: {deleteInstanceErrors.Value[0].Message}.");
}

#endregion Snippet:TimeSeriesInsightsSampleDeleteInstance
}
catch (Exception ex)
{
Console.WriteLine($"Failed to delete Time Series Insights instance: {ex.Message}");
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,19 @@ public static async Task Main(string[] args)
});

// Instantiate the client
TimeSeriesInsightsClient dtClient = GetTimeSeriesInsightsClient(
TimeSeriesInsightsClient tsiClient = GetTimeSeriesInsightsClient(
options.TenantId,
options.ClientId,
options.ClientSecret,
options.TsiEnvironmentFqdn);

// Run the samples

var tsiLifecycleSamples = new TimeSeriesInsightsLifecycleSamples(dtClient, options.TsiEnvironmentFqdn);
var tsiLifecycleSamples = new TimeSeriesInsightsLifecycleSamples(tsiClient, options.TsiEnvironmentFqdn);
await tsiLifecycleSamples.RunSamplesAsync();

var tsiInstancesSamples = new InstancesSamples();
await tsiInstancesSamples.RunSamplesAsync(tsiClient);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ namespace Azure.IoT.TimeSeriesInsights.Samples
{
internal static class SampleLogger
{
internal static void PrintHeader(string message)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine($"\n\n==={message.ToUpperInvariant()}===\n");
Console.ResetColor();
}

internal static void FatalError(string message)
{
Console.ForegroundColor = ConsoleColor.Red;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
Expand Down Expand Up @@ -44,6 +44,16 @@ internal InstancesClient(TimeSeriesInstancesRestClient instancesRestClient, Clie
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsGetAllInstances">
/// // Get all instances for the Time Series Insigths environment
/// AsyncPageable&lt;TimeSeriesInstance&gt; tsiInstances = client.Instances.GetAsync();
/// await foreach (TimeSeriesInstance tsiInstance in tsiInstances)
/// {
/// Console.WriteLine($&quot;Retrieved Time Series Insights instance with Id &apos;{tsiInstance.TimeSeriesId}&apos; and name &apos;{tsiInstance.Name}&apos;.&quot;);
/// }
/// </code>
/// </example>
public virtual AsyncPageable<TimeSeriesInstance> GetAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
Expand Down Expand Up @@ -271,6 +281,29 @@ public virtual Response<InstancesOperationResult[]> Get(
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsGetnstancesById">
/// // Get Time Series Insights instances by Id
/// var timeSeriesIds = new List&lt;TimeSeriesId&gt;
/// {
/// instanceId,
/// };
///
/// Response&lt;InstancesOperationResult[]&gt; getInstancesByNameResult = await client.Instances.GetAsync(timeSeriesIds).ConfigureAwait(false);
///
/// /// The response of calling the API contains a list of instance or error objects corresponding by position to the array in the request.
/// /// Instance object is set when operation is successful and error object is set when operation is unsuccessful.
/// InstancesOperationResult getInstanceByIdResult = getInstancesByNameResult.Value[0];
/// if (getInstanceByIdResult.Instance != null)
/// {
/// Console.WriteLine($&quot;Retrieved Time Series Insights instance with Id &apos;{getInstanceByIdResult.Instance.TimeSeriesId}&apos; and name &apos;{getInstanceByIdResult.Instance.Name}&apos;.&quot;);
/// }
/// else if (getInstanceByIdResult.Error != null)
/// {
/// Console.WriteLine($&quot;Failed to retrieve a Time Series Insights instnace with Id &apos;{getInstanceByIdResult.Error.Message}&apos;.&quot;);
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>.
/// </exception>
Expand Down Expand Up @@ -445,6 +478,37 @@ public virtual Response<SearchSuggestion[]> GetSearchSuggestions(string searchSt
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsSampleCreateInstance">
/// // Create a Time Series Instance object with the default Time Series Insights type Id.
/// // The default type Id can be obtained programmatically by using the ModelSettings client.
/// var instance = new TimeSeriesInstance(instanceId, &quot;1be09af9-f089-4d6b-9f0b-48018b5f7393&quot;)
/// {
/// Name = &quot;instance1&quot;,
/// };
///
/// var tsiInstancesToCreate = new List&lt;TimeSeriesInstance&gt;
/// {
/// instance,
/// };
///
/// Response&lt;TimeSeriesOperationError[]&gt; createInstanceErrors = await client
/// .Instances
/// .CreateOrReplaceAsync(tsiInstancesToCreate)
/// .ConfigureAwait(false);
///
/// // The response of calling the API contains a list of error objects corresponding by position to the input parameter
/// // array in the request. If the error object is set to null, this means the operation was a success.
/// if (createInstanceErrors.Value[0] == null)
/// {
/// Console.WriteLine($&quot;Created Time Series Insights instance with Id &apos;{instanceId}&apos;.&quot;);
/// }
/// else
/// {
/// Console.WriteLine($&quot;Failed to create a Time Series Insights instance: {createInstanceErrors.Value[0].Message}.&quot;);
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>.
/// </exception>
Expand Down Expand Up @@ -552,6 +616,37 @@ public virtual Response<TimeSeriesOperationError[]> CreateOrReplace(
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsReplaceInstance">
/// // Get Time Series Insights instances by Id
/// var instanceIdsToGet = new List&lt;TimeSeriesId&gt;
/// {
/// instanceId,
/// };
///
/// Response&lt;InstancesOperationResult[]&gt; getInstancesByIdResult = await client.Instances.GetAsync(instanceIdsToGet).ConfigureAwait(false);
///
/// TimeSeriesInstance instanceResult = getInstancesByIdResult.Value[0].Instance;
/// Console.WriteLine($&quot;Retrieved Time Series Insights instance with Id &apos;{instanceResult.TimeSeriesId}&apos; and name &apos;{instanceResult.Name}&apos;.&quot;);
///
/// // Now let&apos;s replace the instance with an updated name
/// instanceResult.Name = &quot;newInstanceName&quot;;
///
/// var instancesToReplace = new List&lt;TimeSeriesInstance&gt;
/// {
/// instanceResult,
/// };
///
/// Response&lt;InstancesOperationResult[]&gt; replaceInstancesResult = await client.Instances.ReplaceAsync(instancesToReplace).ConfigureAwait(false);
///
/// // The response of calling the API contains a list of error objects corresponding by position to the input parameter
/// // array in the request. If the error object is set to null, this means the operation was a success.
/// if (replaceInstancesResult.Value[0].Error != null)
/// {
/// Console.WriteLine($&quot;Failed to retrieve a Time Series Insights instnace with Id &apos;{replaceInstancesResult.Value[0].Error.Message}&apos;.&quot;);
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>.
/// </exception>
Expand Down Expand Up @@ -650,6 +745,25 @@ public virtual Response<InstancesOperationResult[]> Replace(
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsSampleDeleteInstance">
/// Response&lt;TimeSeriesOperationError[]&gt; deleteInstanceErrors = await client
/// .Instances
/// .DeleteAsync(new List&lt;TimeSeriesId&gt; { instanceId })
/// .ConfigureAwait(false);
///
/// // The response of calling the API contains a list of error objects corresponding by position to the input parameter
/// // array in the request. If the error object is set to null, this means the operation was a success.
/// if (deleteInstanceErrors.Value[0] == null)
/// {
/// Console.WriteLine($&quot;Deleted Time Series Insights instance with Id &apos;{instanceId}&apos;.&quot;);
/// }
/// else
/// {
/// Console.WriteLine($&quot;Failed to delete a Time Series Insights instance: {deleteInstanceErrors.Value[0].Message}.&quot;);
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>.
/// </exception>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ await TestRetryHelper.RetryAsync<Response<InstancesOperationResult[]>>(async ()
{
// Create TSI instances
Response<TimeSeriesOperationError[]> createInstancesResult = await client
.Instances
.CreateOrReplaceAsync(timeSeriesInstances)
.ConfigureAwait(false);
.Instances
.CreateOrReplaceAsync(timeSeriesInstances)
.ConfigureAwait(false);

// Assert that the result error array does not contain any object that is set
createInstancesResult.Value.Should().OnlyContain((errorResult) => errorResult == null);
Expand Down

0 comments on commit 74b9aa0

Please sign in to comment.