/// <summary> /// This sample demonstrates querying for raw events, series and aggregate series data from a Time Series Insights environment. /// </summary> /// <remarks> /// The Query APIs make use Time Series Expressions (TSX) to build filters, value and aggregation expressions. Visit /// <see href="https://docs.microsoft.com/rest/api/time-series-insights/reference-time-series-expression-syntax"/> to learn more about TSX. /// </remarks> public async Task RunSamplesAsync(TimeSeriesInsightsClient client, DeviceClient deviceClient) { PrintHeader("TIME SERIES INSIGHTS QUERY SAMPLE"); // Figure out what keys make up the Time Series Id TimeSeriesInsightsModelSettings modelSettingsClient = client.GetModelSettingsClient(); TimeSeriesModelSettings modelSettings = await modelSettingsClient.GetAsync(); TimeSeriesId tsId = TimeSeriesIdHelper.CreateTimeSeriesId(modelSettings); TimeSeriesInsightsQueries queriesClient = client.GetQueriesClient(); // In order to query for data, let's first send events to the IoT Hub await SendEventsToIotHubAsync(deviceClient, tsId, modelSettings.TimeSeriesIdProperties.ToArray()); // Sleeping for a few seconds to allow data to fully propagate in the Time Series Insights service Thread.Sleep(TimeSpan.FromSeconds(3)); await RunQueryEventsSample(queriesClient, tsId); await RunQueryAggregateSeriesSample(queriesClient, tsId); await RunQuerySeriesSampleWithInlineVariables(queriesClient, tsId); await RunQuerySeriesSampleWithPreDefinedVariables(client, tsId); }
/// <summary> /// Main entry point to the sample. /// </summary> public static async Task Main(string[] args) { // Parse and validate paramters Options options = null; ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args) .WithParsed(parsedOptions => { options = parsedOptions; }) .WithNotParsed(errors => { Environment.Exit(1); }); // Instantiate the Time Series Insights client TimeSeriesInsightsClient tsiClient = GetTimeSeriesInsightsClient( options.TenantId, options.ClientId, options.ClientSecret, options.TsiEnvironmentFqdn); // Instantiate an IoT Hub device client client in order to send telemetry to the hub DeviceClient deviceClient = await GetDeviceClientAsync(options.IoTHubConnectionString).ConfigureAwait(false); // Figure out what keys make up the Time Series Id TimeSeriesInsightsModelSettings modelSettingsClient = tsiClient.GetModelSettingsClient(); TimeSeriesModelSettings modelSettings = await modelSettingsClient.GetAsync(); TimeSeriesId tsId = TimeSeriesIdHelper.CreateTimeSeriesId(modelSettings); // In order to query for data, let's first send events to the IoT Hub await SendEventsToIotHubAsync(deviceClient, tsId, modelSettings.TimeSeriesIdProperties.ToArray()); // Run the samples var tsiInstancesSamples = new InstancesSamples(); await tsiInstancesSamples.RunSamplesAsync(tsiClient); var tsiTypesSamples = new TypesSamples(); await tsiTypesSamples.RunSamplesAsync(tsiClient); var tsiHierarchiesSamples = new HierarchiesSamples(); await tsiHierarchiesSamples.RunSamplesAsync(tsiClient); var tsiModelSettingsSamples = new ModelSettingsSamples(); await tsiModelSettingsSamples.RunSamplesAsync(tsiClient); var querySamples = new QuerySamples(); await querySamples.RunSamplesAsync(tsiClient, tsId); }
internal static TimeSeriesId CreateTimeSeriesId(TimeSeriesModelSettings modelSettings) { int numOfIdKeys = modelSettings.TimeSeriesIdProperties.Count; // Create a Time Series Id where the number of keys that make up the Time Series Id is fetched from Model Settings var id = new List <string>(); for (int i = 0; i < numOfIdKeys; i++) { id.Add(Guid.NewGuid().ToString()); } TimeSeriesId tsId = numOfIdKeys switch { 1 => new TimeSeriesId(id[0]), 2 => new TimeSeriesId(id[0], id[1]), 3 => new TimeSeriesId(id[0], id[1], id[2]), _ => throw new Exception($"Invalid number of Time Series Insights Id properties."), }; return(tsId); }
internal ModelSettingsResponse(TimeSeriesModelSettings modelSettings) { ModelSettings = modelSettings; }
public async Task TimeSeriesInsightsQuery_GetEventsLifecycle() { // Arrange TimeSeriesInsightsClient tsiClient = GetClient(); DeviceClient deviceClient = await GetDeviceClient().ConfigureAwait(false); // Figure out what the Time Series Id is composed of TimeSeriesModelSettings modelSettings = await tsiClient.GetModelSettingsAsync().ConfigureAwait(false); // Create a Time Series Id where the number of keys that make up the Time Series Id is fetched from Model Settings TimeSeriesId tsiId = await GetUniqueTimeSeriesInstanceIdAsync(tsiClient, modelSettings.TimeSeriesIdProperties.Count) .ConfigureAwait(false); try { // Send some events to the IoT hub await QueryTestsHelper.SendEventsToHubAsync( deviceClient, tsiId, modelSettings.TimeSeriesIdProperties.ToArray(), 2) .ConfigureAwait(false); // Act // Get events from last 1 minute DateTimeOffset now = Recording.UtcNow; DateTimeOffset endTime = now.AddMinutes(10); DateTimeOffset startTime = now.AddMinutes(-10); // This retry logic was added as the TSI instance are not immediately available after creation await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { AsyncPageable <QueryResultPage> queryEventsPages = tsiClient.QueryEventsAsync(tsiId, startTime, endTime); await foreach (QueryResultPage eventPage in queryEventsPages) { eventPage.Timestamps.Should().HaveCount(2); eventPage.Timestamps.Should().OnlyContain(timeStamp => timeStamp >= startTime).And.OnlyContain(timeStamp => timeStamp <= endTime); eventPage.Properties.Should().NotBeEmpty(); eventPage.Properties.First().Should().NotBeNull(); } return(null); }, MaxNumberOfRetries, s_retryDelay); // Send more events to the hub await QueryTestsHelper.SendEventsToHubAsync( deviceClient, tsiId, modelSettings.TimeSeriesIdProperties.ToArray(), 2) .ConfigureAwait(false); // This retry logic was added as the TSI instance are not immediately available after creation await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { AsyncPageable <QueryResultPage> queryEventsPages = tsiClient.QueryEventsAsync(tsiId, startTime, endTime); await foreach (QueryResultPage eventPage in queryEventsPages) { eventPage.Timestamps.Should().HaveCount(4); eventPage.Timestamps.Should() .OnlyContain(timeStamp => timeStamp >= startTime) .And .OnlyContain(timeStamp => timeStamp <= endTime); eventPage.Properties.Should().NotBeEmpty(); eventPage.Properties.First().Should().NotBeNull(); } return(null); }, MaxNumberOfRetries, s_retryDelay); // Send 2 events with a special condition that can be used later to query on IDictionary <string, object> messageBase = QueryTestsHelper.BuildMessageBase(modelSettings.TimeSeriesIdProperties.ToArray(), tsiId); messageBase[QueryTestsHelper.Temperature] = 1.2; messageBase[QueryTestsHelper.Humidity] = 3.4; string messageBody = JsonSerializer.Serialize(messageBase); var message = new Message(Encoding.ASCII.GetBytes(messageBody)) { ContentType = "application/json", ContentEncoding = "utf-8", }; Func <Task> sendEventAct = async() => await deviceClient.SendEventAsync(message).ConfigureAwait(false); await sendEventAct.Should().NotThrowAsync(); // Send it again sendEventAct.Should().NotThrow(); // Query for the two events with a filter // Only project Temperature and one of the Id properties var queryRequestOptions = new QueryEventsRequestOptions { Filter = "$event.Temperature.Double = 1.2", StoreType = StoreType.WarmStore, }; queryRequestOptions.ProjectedProperties.Add( new EventProperty { Name = QueryTestsHelper.Temperature, Type = "Double", }); queryRequestOptions.ProjectedProperties.Add( new EventProperty { Name = modelSettings.TimeSeriesIdProperties.First().Name, Type = modelSettings.TimeSeriesIdProperties.First().Type.ToString(), }); await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { AsyncPageable <QueryResultPage> queryEventsPages = tsiClient.QueryEventsAsync(tsiId, startTime, endTime, queryRequestOptions); await foreach (QueryResultPage eventPage in queryEventsPages) { eventPage.Timestamps.Should().HaveCount(2); eventPage.Properties.Should().HaveCount(2); eventPage.Properties.First().Should().NotBeNull(); eventPage.Properties.First().Name.Should().Be(QueryTestsHelper.Temperature); eventPage.Properties[1].Name.Should().Be(modelSettings.TimeSeriesIdProperties.First().Name); } return(null); }, MaxNumberOfRetries, s_retryDelay); // Query for the two events with a filter, but only take 1 queryRequestOptions.MaximumNumberOfEvents = 1; AsyncPageable <QueryResultPage> queryEventsPagesWithFilter = tsiClient.QueryEventsAsync(tsiId, startTime, endTime, queryRequestOptions); await foreach (QueryResultPage eventPage in queryEventsPagesWithFilter) { eventPage.Timestamps.Should().HaveCount(1); eventPage.Properties.Should().HaveCount(2); eventPage.Properties.First().Should().NotBeNull(); eventPage.Properties.First().Name.Should().Be(QueryTestsHelper.Temperature); eventPage.Properties[1].Name.Should().Be(modelSettings.TimeSeriesIdProperties.First().Name); } await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { // Query for all the events using a timespan AsyncPageable <QueryResultPage> queryEventsPagesWithTimespan = tsiClient.QueryEventsAsync(tsiId, TimeSpan.FromMinutes(20), endTime); await foreach (QueryResultPage eventPage in queryEventsPagesWithTimespan) { eventPage.Timestamps.Should().HaveCount(6); eventPage.Timestamps.Should() .OnlyContain(timeStamp => timeStamp >= startTime) .And .OnlyContain(timeStamp => timeStamp <= endTime); eventPage.Properties.Should().NotBeEmpty(); eventPage.Properties.First().Should().NotBeNull(); } return(null); }, MaxNumberOfRetries, s_retryDelay); } finally { deviceClient?.Dispose(); } }
public async Task TimeSeriesInsightsQuery_AggregateSeriesWithNumericVariable() { // Arrange TimeSeriesInsightsClient tsiClient = GetClient(); DeviceClient deviceClient = await GetDeviceClient().ConfigureAwait(false); // Figure out what the Time Series Id is composed of TimeSeriesModelSettings modelSettings = await tsiClient.ModelSettings.GetAsync().ConfigureAwait(false); // Create a Time Series Id where the number of keys that make up the Time Series Id is fetched from Model Settings TimeSeriesId tsiId = await GetUniqueTimeSeriesInstanceIdAsync(tsiClient, modelSettings.TimeSeriesIdProperties.Count) .ConfigureAwait(false); try { // Send some events to the IoT hub with with a second between each event await QueryTestsHelper.SendEventsToHubAsync( deviceClient, tsiId, modelSettings.TimeSeriesIdProperties.ToArray(), 30) .ConfigureAwait(false); DateTimeOffset now = Recording.UtcNow; DateTimeOffset endTime = now.AddMinutes(10); DateTimeOffset startTime = now.AddMinutes(-10); var temperatureNumericVariable = new NumericVariable( new TimeSeriesExpression($"$event.{QueryTestsHelper.Temperature}"), new TimeSeriesExpression("avg($value)")); var queryAggregateSeriesRequestOptions = new QueryAggregateSeriesRequestOptions(); queryAggregateSeriesRequestOptions.InlineVariables[QueryTestsHelper.Temperature] = temperatureNumericVariable; queryAggregateSeriesRequestOptions.ProjectedVariables.Add(QueryTestsHelper.Temperature); // This retry logic was added as the TSI instance are not immediately available after creation await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { QueryAnalyzer queryAggregateSeriesPages = tsiClient.Queries.CreateAggregateSeriesQueryAnalyzer( tsiId, startTime, endTime, TimeSpan.FromSeconds(5), queryAggregateSeriesRequestOptions); var nonNullFound = false; await foreach (Page <TimeSeriesPoint> aggregateSeriesPage in queryAggregateSeriesPages.GetResultsAsync().AsPages()) { foreach (TimeSeriesPoint point in aggregateSeriesPage.Values) { point.GetUniquePropertyNames().Should().HaveCount(1).And.Contain((property) => property == QueryTestsHelper.Temperature); var value = (double?)point.GetValue(QueryTestsHelper.Temperature); if (value != null) { nonNullFound = true; } } nonNullFound.Should().BeTrue(); } queryAggregateSeriesPages.Progress.Should().Be(100); return(null); }, MaxNumberOfRetries, s_retryDelay); // Add an interpolated variable var linearInterpolationNumericVariable = new NumericVariable( new TimeSeriesExpression($"$event.{QueryTestsHelper.Temperature}"), new TimeSeriesExpression("left($value)")); linearInterpolationNumericVariable.Interpolation = new InterpolationOperation { Kind = InterpolationKind.Linear, Boundary = new InterpolationBoundary() { Span = TimeSpan.FromSeconds(1), }, }; const string linearInterpolation = "linearInterpolation"; queryAggregateSeriesRequestOptions.InlineVariables[linearInterpolation] = linearInterpolationNumericVariable; queryAggregateSeriesRequestOptions.ProjectedVariables.Add(linearInterpolation); await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { QueryAnalyzer queryAggregateSeriesPages = tsiClient.Queries.CreateAggregateSeriesQueryAnalyzer( tsiId, startTime, endTime, TimeSpan.FromSeconds(5), queryAggregateSeriesRequestOptions); await foreach (Page <TimeSeriesPoint> aggregateSeriesPage in queryAggregateSeriesPages.GetResultsAsync().AsPages()) { aggregateSeriesPage.Values.Should().HaveCountGreaterThan(0); foreach (var point in aggregateSeriesPage.Values) { point.GetUniquePropertyNames().Should().HaveCount(2) .And .Contain((property) => property == QueryTestsHelper.Temperature) .And .Contain((property) => property == linearInterpolation); } } return(null); }, MaxNumberOfRetries, s_retryDelay); // Send 2 events with a special condition that can be used later to query on IDictionary <string, object> messageBase = QueryTestsHelper.BuildMessageBase(modelSettings.TimeSeriesIdProperties.ToArray(), tsiId); messageBase[QueryTestsHelper.Temperature] = 1.2; messageBase[QueryTestsHelper.Humidity] = 3.4; string messageBody = JsonSerializer.Serialize(messageBase); var message = new Message(Encoding.ASCII.GetBytes(messageBody)) { ContentType = "application/json", ContentEncoding = "utf-8", }; Func <Task> sendEventAct = async() => await deviceClient.SendEventAsync(message).ConfigureAwait(false); sendEventAct.Should().NotThrow(); // Send it again sendEventAct.Should().NotThrow(); // Query for the two events with a filter queryAggregateSeriesRequestOptions.Filter = "$event.Temperature.Double = 1.2"; await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { QueryAnalyzer queryAggregateSeriesPages = tsiClient.Queries.CreateAggregateSeriesQueryAnalyzer( tsiId, startTime, endTime, TimeSpan.FromSeconds(5), queryAggregateSeriesRequestOptions); var valueFound = false; await foreach (TimeSeriesPoint point in queryAggregateSeriesPages.GetResultsAsync()) { point.GetUniquePropertyNames().Should().HaveCount(2) .And .Contain((property) => property == QueryTestsHelper.Temperature) .And .Contain((property) => property == linearInterpolation); var value = (double?)point.GetValue(QueryTestsHelper.Temperature); if (value == 1.2) { valueFound = true; } } valueFound.Should().BeTrue(); return(null); }, MaxNumberOfRetries, s_retryDelay); } finally { deviceClient?.Dispose(); } }
public async Task TimeSeriesInsightsQuery_AggregateSeriesWithCategoricalVariable() { // Arrange TimeSeriesInsightsClient tsiClient = GetClient(); DeviceClient deviceClient = await GetDeviceClient().ConfigureAwait(false); // Figure out what the Time Series Id is composed of TimeSeriesModelSettings modelSettings = await tsiClient.ModelSettings.GetAsync().ConfigureAwait(false); // Create a Time Series Id where the number of keys that make up the Time Series Id is fetched from Model Settings TimeSeriesId tsiId = await GetUniqueTimeSeriesInstanceIdAsync(tsiClient, modelSettings.TimeSeriesIdProperties.Count) .ConfigureAwait(false); try { // Send some events to the IoT hub with with a second between each event await QueryTestsHelper.SendEventsToHubAsync( deviceClient, tsiId, modelSettings.TimeSeriesIdProperties.ToArray(), 30) .ConfigureAwait(false); DateTimeOffset now = Recording.UtcNow; DateTimeOffset endTime = now.AddMinutes(10); DateTimeOffset startTime = now.AddMinutes(-10); var queryAggregateSeriesRequestOptions = new QueryAggregateSeriesRequestOptions(); var categoricalVariable = new CategoricalVariable( new TimeSeriesExpression($"tolong($event.{QueryTestsHelper.Temperature}.Double)"), new TimeSeriesDefaultCategory("N/A")); categoricalVariable.Categories.Add(new TimeSeriesAggregateCategory("good", new List <object> { 1 })); queryAggregateSeriesRequestOptions.InlineVariables["categorical"] = categoricalVariable; await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { QueryAnalyzer queryAggregateSeriesPages = tsiClient.Queries.CreateAggregateSeriesQueryAnalyzer( tsiId, startTime, endTime, TimeSpan.FromSeconds(5), queryAggregateSeriesRequestOptions); await foreach (TimeSeriesPoint point in queryAggregateSeriesPages.GetResultsAsync()) { point.GetUniquePropertyNames().Should().HaveCount(3) .And .Contain((property) => property == "categorical[good]") .And .Contain((property) => property == "categorical[N/A]"); } return(null); }, MaxNumberOfRetries, s_retryDelay); } finally { deviceClient?.Dispose(); } }
public async Task TimeSeriesInsightsQuery_AggregateSeriesWithAggregateVariable() { // Arrange TimeSeriesInsightsClient tsiClient = GetClient(); DeviceClient deviceClient = await GetDeviceClient().ConfigureAwait(false); // Figure out what the Time Series Id is composed of TimeSeriesModelSettings modelSettings = await tsiClient.ModelSettings.GetAsync().ConfigureAwait(false); // Create a Time Series Id where the number of keys that make up the Time Series Id is fetched from Model Settings TimeSeriesId tsiId = await GetUniqueTimeSeriesInstanceIdAsync(tsiClient, modelSettings.TimeSeriesIdProperties.Count) .ConfigureAwait(false); try { // Send some events to the IoT hub with with a second between each event await QueryTestsHelper.SendEventsToHubAsync( deviceClient, tsiId, modelSettings.TimeSeriesIdProperties.ToArray(), 30) .ConfigureAwait(false); // Query for temperature events with two calculateions. First with the temperature value as is, and the second // with the temperature value multiplied by 2. DateTimeOffset now = Recording.UtcNow; DateTimeOffset endTime = now.AddMinutes(10); DateTimeOffset startTime = now.AddMinutes(-10); var aggregateVariable = new AggregateVariable( new TimeSeriesExpression("count()")); var queryAggregateSeriesRequestOptions = new QueryAggregateSeriesRequestOptions(); queryAggregateSeriesRequestOptions.InlineVariables["Count"] = aggregateVariable; queryAggregateSeriesRequestOptions.ProjectedVariables.Add("Count"); // This retry logic was added as the TSI instance are not immediately available after creation await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { QueryAnalyzer queryAggregateSeriesPages = tsiClient.Queries.CreateAggregateSeriesQueryAnalyzer( tsiId, startTime, endTime, TimeSpan.FromSeconds(5), queryAggregateSeriesRequestOptions); long?totalCount = 0; await foreach (TimeSeriesPoint point in queryAggregateSeriesPages.GetResultsAsync()) { var currentCount = (long?)point.GetValue("Count"); totalCount += currentCount; } totalCount.Should().Be(30); return(null); }, MaxNumberOfRetries, s_retryDelay); } finally { deviceClient?.Dispose(); } }
/// <summary> /// This sample demonstrates usage of Time Series Insights types APIs. /// </summary> public async Task RunSamplesAsync(TimeSeriesInsightsClient client) { // For the purpose of keeping code snippets readable to the user, hardcoded string literals are used in place of assigned variables, eg Ids. // Despite not being a good code practice, this prevents code snippets from being out of context for the user when making API calls that accept Ids as parameters. PrintHeader("TIME SERIES INSIGHTS TYPES SAMPLE"); #region Snippet:TimeSeriesInsightsSampleCreateType // Create a type with an aggregate variable var timeSeriesTypes = new List <TimeSeriesType>(); var countExpression = new TimeSeriesExpression("count()"); var aggregateVariable = new AggregateVariable(countExpression); var variables = new Dictionary <string, TimeSeriesVariable>(); variables.Add("aggregateVariable", aggregateVariable); timeSeriesTypes.Add(new TimeSeriesType("Type1", variables) { Id = "Type1Id" }); timeSeriesTypes.Add(new TimeSeriesType("Type2", variables) { Id = "Type2Id" }); Response <TimeSeriesTypeOperationResult[]> createTypesResult = await client .Types .CreateOrReplaceAsync(timeSeriesTypes); // 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. for (int i = 0; i < createTypesResult.Value.Length; i++) { if (createTypesResult.Value[i].Error == null) { Console.WriteLine($"Created Time Series type successfully."); } else { Console.WriteLine($"Failed to create a Time Series Insights type: {createTypesResult.Value[i].Error.Message}."); } } #endregion Snippet:TimeSeriesInsightsSampleCreateType #region Snippet:TimeSeriesInsightsSampleGetTypeById // Code snippet below shows getting a default Type using Id // The default type Id can be obtained programmatically by using the ModelSettings client. TimeSeriesModelSettings modelSettings = await client.ModelSettings.GetAsync(); Response <TimeSeriesTypeOperationResult[]> getTypeByIdResults = await client .Types .GetByIdAsync(new string[] { modelSettings.DefaultTypeId }); // The response of calling the API contains a list of type or 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. for (int i = 0; i < getTypeByIdResults.Value.Length; i++) { if (getTypeByIdResults.Value[i].Error == null) { Console.WriteLine($"Retrieved Time Series type with Id: '{getTypeByIdResults.Value[i].TimeSeriesType.Id}'."); } else { Console.WriteLine($"Failed to retrieve a Time Series type due to '{getTypeByIdResults.Value[i].Error.Message}'."); } } #endregion Snippet:TimeSeriesInsightsSampleGetTypeById #region Snippet:TimeSeriesInsightsSampleReplaceType // Update variables with adding a new variable foreach (TimeSeriesType type in timeSeriesTypes) { type.Description = "Description"; } Response <TimeSeriesTypeOperationResult[]> updateTypesResult = await client .Types .CreateOrReplaceAsync(timeSeriesTypes); // 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. for (int i = 0; i < updateTypesResult.Value.Length; i++) { if (updateTypesResult.Value[i].Error == null) { Console.WriteLine($"Updated Time Series type successfully."); } else { Console.WriteLine($"Failed to update a Time Series Insights type due to: {updateTypesResult.Value[i].Error.Message}."); } } #endregion Snippet:TimeSeriesInsightsSampleReplaceType #region Snippet:TimeSeriesInsightsSampleGetAllTypes // Get all Time Series types in the environment AsyncPageable <TimeSeriesType> getAllTypesResponse = client.Types.GetTypesAsync(); await foreach (TimeSeriesType tsiType in getAllTypesResponse) { Console.WriteLine($"Retrieved Time Series Insights type with Id: '{tsiType?.Id}' and Name: '{tsiType?.Name}'"); } #endregion Snippet:TimeSeriesInsightsSampleGetAllTypes // Clean up try { #region Snippet:TimeSeriesInsightsSampleDeleteTypeById // Delete Time Series types with Ids var typesIdsToDelete = new List <string> { "Type1Id", " Type2Id" }; Response <TimeSeriesOperationError[]> deleteTypesResponse = await client .Types .DeleteByIdAsync(typesIdsToDelete); // 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. foreach (var result in deleteTypesResponse.Value) { if (result != null) { Console.WriteLine($"Failed to delete a Time Series Insights type: {result.Message}."); } else { Console.WriteLine($"Deleted a Time Series Insights type successfully."); } } #endregion Snippet:TimeSeriesInsightsSampleDeleteTypeById } catch (Exception ex) { Console.WriteLine($"Failed to delete Time Series Insights type: {ex.Message}"); } }
public async Task TimeSeriesInsightsQuery_GetSeriesLifecycle() { // Arrange TimeSeriesInsightsClient tsiClient = GetClient(); DeviceClient deviceClient = await GetDeviceClient().ConfigureAwait(false); // Figure out what the Time Series Id is composed of TimeSeriesModelSettings modelSettings = await tsiClient.ModelSettings.GetAsync().ConfigureAwait(false); // Create a Time Series Id where the number of keys that make up the Time Series Id is fetched from Model Settings TimeSeriesId tsiId = await GetUniqueTimeSeriesInstanceIdAsync(tsiClient, modelSettings.TimeSeriesIdProperties.Count) .ConfigureAwait(false); try { // Send some events to the IoT hub await QueryTestsHelper.SendEventsToHubAsync( deviceClient, tsiId, modelSettings.TimeSeriesIdProperties.ToArray(), 10) .ConfigureAwait(false); // Act // Query for temperature events with two calculateions. First with the temperature value as is, and the second // with the temperature value multiplied by 2. DateTimeOffset now = Recording.UtcNow; DateTimeOffset endTime = now.AddMinutes(10); DateTimeOffset startTime = now.AddMinutes(-10); var temperatureNumericVariable = new NumericVariable( new TimeSeriesExpression($"$event.{QueryTestsHelper.Temperature}"), new TimeSeriesExpression("avg($value)")); var temperatureNumericVariableTimesTwo = new NumericVariable( new TimeSeriesExpression($"$event.{QueryTestsHelper.Temperature} * 2"), new TimeSeriesExpression("avg($value)")); var temperatureTimesTwoVariableName = $"{QueryTestsHelper.Temperature}TimesTwo"; var querySeriesRequestOptions = new QuerySeriesRequestOptions(); querySeriesRequestOptions.InlineVariables[QueryTestsHelper.Temperature] = temperatureNumericVariable; querySeriesRequestOptions.InlineVariables[temperatureTimesTwoVariableName] = temperatureNumericVariableTimesTwo; // This retry logic was added as the TSI instance are not immediately available after creation await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { AsyncPageable <QueryResultPage> querySeriesEventsPages = tsiClient.Query.GetSeriesAsync( tsiId, startTime, endTime, querySeriesRequestOptions); await foreach (QueryResultPage seriesEventsPage in querySeriesEventsPages) { seriesEventsPage.Timestamps.Should().HaveCount(10); seriesEventsPage.Timestamps.Should().OnlyContain(timeStamp => timeStamp >= startTime) .And .OnlyContain(timeStamp => timeStamp <= endTime); seriesEventsPage.Properties.Count.Should().Be(3); // EventCount, Temperature and TemperatureTimesTwo seriesEventsPage.Properties.Should().Contain((property) => property.Name == QueryTestsHelper.Temperature) .And .Contain((property) => property.Name == temperatureTimesTwoVariableName); // Assert that the values for the Temperature property is equal to the values for the other property, multiplied by 2 var temperatureValues = seriesEventsPage .Properties .First((property) => property.Name == QueryTestsHelper.Temperature) .Values.Cast <double>().ToList(); var temperatureTimesTwoValues = seriesEventsPage .Properties .First((property) => property.Name == temperatureTimesTwoVariableName) .Values.Cast <double>().ToList(); temperatureTimesTwoValues.Should().Equal(temperatureValues.Select((property) => property * 2).ToList()); } return(null); }, MaxNumberOfRetries, s_retryDelay); // Query for all the series events using a timespan AsyncPageable <QueryResultPage> querySeriesEventsPagesWithTimespan = tsiClient.Query.GetSeriesAsync(tsiId, TimeSpan.FromMinutes(10), null, querySeriesRequestOptions); await foreach (QueryResultPage seriesEventsPage in querySeriesEventsPagesWithTimespan) { seriesEventsPage.Timestamps.Should().HaveCount(10); seriesEventsPage.Properties.Count.Should().Be(3); // EventCount, Temperature and TemperatureTimesTwo } // Query for temperature and humidity var humidityNumericVariable = new NumericVariable( new TimeSeriesExpression("$event.Humidity"), new TimeSeriesExpression("avg($value)")); querySeriesRequestOptions.InlineVariables[QueryTestsHelper.Humidity] = humidityNumericVariable; querySeriesRequestOptions.ProjectedVariables.Add(QueryTestsHelper.Temperature); querySeriesRequestOptions.ProjectedVariables.Add(QueryTestsHelper.Humidity); await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { AsyncPageable <QueryResultPage> querySeriesEventsPages = tsiClient.Query.GetSeriesAsync(tsiId, startTime, endTime, querySeriesRequestOptions); await foreach (QueryResultPage seriesEventsPage in querySeriesEventsPages) { seriesEventsPage.Timestamps.Should().HaveCount(10); seriesEventsPage.Timestamps.Should().OnlyContain(timeStamp => timeStamp >= startTime) .And .OnlyContain(timeStamp => timeStamp <= endTime); seriesEventsPage.Properties.Count.Should().Be(2); // Temperature and Humidity seriesEventsPage.Properties.Should().Contain((property) => property.Name == QueryTestsHelper.Temperature) .And .Contain((property) => property.Name == QueryTestsHelper.Humidity); } return(null); }, MaxNumberOfRetries, s_retryDelay); // Send 2 events with a special condition that can be used later to query on IDictionary <string, object> messageBase = QueryTestsHelper.BuildMessageBase(modelSettings.TimeSeriesIdProperties.ToArray(), tsiId); messageBase[QueryTestsHelper.Temperature] = 1.2; messageBase[QueryTestsHelper.Humidity] = 3.4; string messageBody = JsonSerializer.Serialize(messageBase); var message = new Message(Encoding.ASCII.GetBytes(messageBody)) { ContentType = "application/json", ContentEncoding = "utf-8", }; Func <Task> sendEventAct = async() => await deviceClient.SendEventAsync(message).ConfigureAwait(false); sendEventAct.Should().NotThrow(); // Send it again sendEventAct.Should().NotThrow(); // Query for the two events with a filter querySeriesRequestOptions.Filter = "$event.Temperature.Double = 1.2"; await TestRetryHelper.RetryAsync <AsyncPageable <QueryResultPage> >(async() => { AsyncPageable <QueryResultPage> querySeriesEventsPages = tsiClient.Query.GetSeriesAsync(tsiId, startTime, endTime, querySeriesRequestOptions); await foreach (QueryResultPage seriesEventsPage in querySeriesEventsPages) { seriesEventsPage.Timestamps.Should().HaveCount(2); seriesEventsPage.Properties.Should().HaveCount(2) .And .Contain((property) => property.Name == QueryTestsHelper.Temperature) .And .Contain((property) => property.Name == QueryTestsHelper.Humidity); var temperatureValues = seriesEventsPage .Properties .First((property) => property.Name == QueryTestsHelper.Temperature) .Values.Cast <double>().ToList(); temperatureValues.Should().AllBeEquivalentTo(1.2); } return(null); }, MaxNumberOfRetries, s_retryDelay); // Query for the two events with a filter, but only take 1 querySeriesRequestOptions.MaximumNumberOfEvents = 1; AsyncPageable <QueryResultPage> querySeriesEventsPagesWithFilter = tsiClient.Query.GetSeriesAsync(tsiId, startTime, endTime, querySeriesRequestOptions); await foreach (QueryResultPage seriesEventsPage in querySeriesEventsPagesWithFilter) { seriesEventsPage.Timestamps.Should().HaveCount(1); seriesEventsPage.Properties.Should().HaveCount(2) .And .Contain((property) => property.Name == QueryTestsHelper.Temperature) .And .Contain((property) => property.Name == QueryTestsHelper.Humidity); var temperatureValues = seriesEventsPage .Properties .First((property) => property.Name == QueryTestsHelper.Temperature) .Values.Cast <double>().ToList(); temperatureValues.Should().AllBeEquivalentTo(1.2); } } finally { deviceClient?.Dispose(); } }
public async Task TimeSeriesInsightsQuery_GetEventsLifecycle() { // Arrange TimeSeriesInsightsClient tsiClient = GetClient(); TimeSeriesInsightsModelSettings timeSeriesModelSettings = tsiClient.GetModelSettingsClient(); TimeSeriesInsightsInstances instancesClient = tsiClient.GetInstancesClient(); TimeSeriesInsightsQueries queriesClient = tsiClient.GetQueriesClient(); DeviceClient deviceClient = await GetDeviceClient().ConfigureAwait(false); // Figure out what the Time Series Id is composed of TimeSeriesModelSettings modelSettings = await timeSeriesModelSettings.GetAsync().ConfigureAwait(false); // Create a Time Series Id where the number of keys that make up the Time Series Id is fetched from Model Settings TimeSeriesId tsiId = await GetUniqueTimeSeriesInstanceIdAsync(instancesClient, modelSettings.TimeSeriesIdProperties.Count) .ConfigureAwait(false); try { var initialEventsCount = 50; // Send some events to the IoT hub await QueryTestsHelper.SendEventsToHubAsync( deviceClient, tsiId, modelSettings.TimeSeriesIdProperties.ToArray(), initialEventsCount) .ConfigureAwait(false); // Act // Get events from last 10 minute DateTimeOffset now = Recording.UtcNow; DateTimeOffset endTime = now.AddMinutes(10); DateTimeOffset startTime = now.AddMinutes(-10); // This retry logic was added as the TSI instance are not immediately available after creation await TestRetryHelper.RetryAsync <AsyncPageable <TimeSeriesPoint> >(async() => { TimeSeriesQueryAnalyzer queryEventsPages = queriesClient.CreateEventsQuery(tsiId, startTime, endTime); var count = 0; await foreach (TimeSeriesPoint timeSeriesPoint in queryEventsPages.GetResultsAsync()) { count++; timeSeriesPoint.Timestamp.Should().BeAfter(startTime).And.BeBefore(endTime); var temperatureValue = timeSeriesPoint.GetNullableDouble(QueryTestsHelper.Temperature); temperatureValue.Should().NotBeNull(); var humidityValue = (double?)timeSeriesPoint.GetValue(QueryTestsHelper.Humidity); humidityValue.Should().NotBeNull(); } count.Should().Be(initialEventsCount); return(null); }, MaxNumberOfRetries, s_retryDelay); // Send 2 events with a special condition that can be used later to query on IDictionary <string, object> messageBase = QueryTestsHelper.BuildMessageBase( modelSettings.TimeSeriesIdProperties.ToArray(), tsiId); messageBase[QueryTestsHelper.Temperature] = 1.2; messageBase[QueryTestsHelper.Humidity] = 3.4; string messageBody = JsonSerializer.Serialize(messageBase); var message = new Message(Encoding.ASCII.GetBytes(messageBody)) { ContentType = "application/json", ContentEncoding = "utf-8", }; Func <Task> sendEventAct = async() => await deviceClient.SendEventAsync(message).ConfigureAwait(false); await sendEventAct.Should().NotThrowAsync(); // Send it again sendEventAct.Should().NotThrow(); // Query for the two events with a filter // Only project Temperature and one of the Id properties var queryRequestOptions = new QueryEventsRequestOptions { Filter = new TimeSeriesExpression("$event.Temperature.Double = 1.2"), Store = StoreType.WarmStore, }; queryRequestOptions.ProjectedProperties.Add( new TimeSeriesInsightsEventProperty { Name = QueryTestsHelper.Temperature, PropertyValueType = "Double", }); queryRequestOptions.ProjectedProperties.Add( new TimeSeriesInsightsEventProperty { Name = modelSettings.TimeSeriesIdProperties.First().Name, PropertyValueType = modelSettings.TimeSeriesIdProperties.First().PropertyType.ToString(), }); await TestRetryHelper.RetryAsync <AsyncPageable <TimeSeriesPoint> >(async() => { TimeSeriesQueryAnalyzer queryEventsPages = queriesClient.CreateEventsQuery(tsiId, startTime, endTime, queryRequestOptions); await foreach (Page <TimeSeriesPoint> page in queryEventsPages.GetResultsAsync().AsPages()) { page.Values.Should().HaveCount(2); foreach (TimeSeriesPoint point in page.Values) { var value = (double?)point.GetValue(QueryTestsHelper.Temperature); value.Should().Be(1.2); } } return(null); }, MaxNumberOfRetries, s_retryDelay); // Query for the two events with a filter, but only take 1 queryRequestOptions.MaxNumberOfEvents = 1; TimeSeriesQueryAnalyzer queryEventsPagesWithFilter = queriesClient.CreateEventsQuery(tsiId, startTime, endTime, queryRequestOptions); await foreach (Page <TimeSeriesPoint> page in queryEventsPagesWithFilter.GetResultsAsync().AsPages()) { page.Values.Should().HaveCount(1); } await TestRetryHelper.RetryAsync <AsyncPageable <TimeSeriesPoint> >(async() => { // Query for all the events using a timespan TimeSeriesQueryAnalyzer queryEventsPagesWithTimespan = queriesClient .CreateEventsQuery(tsiId, TimeSpan.FromMinutes(20), endTime); await foreach (Page <TimeSeriesPoint> page in queryEventsPagesWithTimespan.GetResultsAsync().AsPages()) { page.Values.Should().HaveCount(52); foreach (TimeSeriesPoint point in page.Values) { point.Timestamp.Should().BeAfter(startTime).And.BeBefore(endTime); var temperatureValue = (double?)point.GetValue(QueryTestsHelper.Temperature); temperatureValue.Should().NotBeNull(); var humidityValue = (double?)point.GetValue(QueryTestsHelper.Humidity); humidityValue.Should().NotBeNull(); } } return(null); }, MaxNumberOfRetries, s_retryDelay); } finally { deviceClient?.Dispose(); } }
/// <summary> /// Creates a Time Series Insights instance /// Gets all instances for the environment /// Gets a specific instance by Id /// Replaces an instance /// Deletes an instance. /// </summary> public async Task RunSamplesAsync(TimeSeriesInsightsClient client) { PrintHeader("TIME SERIES INSIGHTS INSTANCES SAMPLE"); // Figure out what keys make up the Time Series Id TimeSeriesModelSettings modelSettings = await client.ModelSettings.GetAsync(); TimeSeriesId tsId = TimeSeriesIdHelper.CreateTimeSeriesId(modelSettings); string defaultTypeId = modelSettings.DefaultTypeId; #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. // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`. var instance = new TimeSeriesInstance(tsId, defaultTypeId) { Name = "instance1", }; var tsiInstancesToCreate = new List <TimeSeriesInstance> { instance, }; Response <TimeSeriesOperationError[]> createInstanceErrors = await client .Instances .CreateOrReplaceAsync(tsiInstancesToCreate); // 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. for (int i = 0; i < createInstanceErrors.Value.Length; i++) { TimeSeriesId tsiId = tsiInstancesToCreate[i].TimeSeriesId; if (createInstanceErrors.Value[i] == null) { Console.WriteLine($"Created Time Series Insights instance with Id '{tsiId}'."); } else { Console.WriteLine($"Failed to create a Time Series Insights instance with Id '{tsiId}', " + $"Error Message: '{createInstanceErrors.Value[i].Message}, " + $"Error code: '{createInstanceErrors.Value[i].Code}'."); } } #endregion Snippet:TimeSeriesInsightsSampleCreateInstance #region Snippet:TimeSeriesInsightsGetAllInstances // Get all instances for the Time Series Insights 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 // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`. var instanceIdsToGet = new List <TimeSeriesId> { tsId, }; Response <InstancesOperationResult[]> getInstancesByIdResult = await client.Instances.GetAsync(instanceIdsToGet); 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); // 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. for (int i = 0; i < replaceInstancesResult.Value.Length; i++) { TimeSeriesId tsiId = instancesToReplace[i].TimeSeriesId; TimeSeriesOperationError currentError = replaceInstancesResult.Value[i].Error; if (currentError != null) { Console.WriteLine($"Failed to replace Time Series Insights instance with Id '{tsiId}'," + $" Error Message: '{currentError.Message}', Error code: '{currentError.Code}'."); } else { Console.WriteLine($"Replaced Time Series Insights instance with Id '{tsiId}'."); } } #endregion Snippet:TimeSeriesInsightsReplaceInstance #region Snippet:TimeSeriesInsightsGetnstancesById // Get Time Series Insights instances by Id // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`. var timeSeriesIds = new List <TimeSeriesId> { tsId, }; Response <InstancesOperationResult[]> getByIdsResult = await client.Instances.GetAsync(timeSeriesIds); // 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. for (int i = 0; i < getByIdsResult.Value.Length; i++) { InstancesOperationResult currentOperationResult = getByIdsResult.Value[i]; if (currentOperationResult.Instance != null) { Console.WriteLine($"Retrieved Time Series Insights instance with Id '{currentOperationResult.Instance.TimeSeriesId}' and name '{currentOperationResult.Instance.Name}'."); } else if (currentOperationResult.Error != null) { Console.WriteLine($"Failed to retrieve a Time Series Insights instance with Id '{timeSeriesIds[i]}'. Error message: '{currentOperationResult.Error.Message}'."); } } #endregion Snippet:TimeSeriesInsightsGetnstancesById // Clean up try { #region Snippet:TimeSeriesInsightsSampleDeleteInstanceById // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`. var instancesToDelete = new List <TimeSeriesId> { tsId, }; Response <TimeSeriesOperationError[]> deleteInstanceErrors = await client .Instances .DeleteAsync(instancesToDelete); // 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. for (int i = 0; i < deleteInstanceErrors.Value.Length; i++) { TimeSeriesId tsiId = instancesToDelete[i]; if (deleteInstanceErrors.Value[i] == null) { Console.WriteLine($"Deleted Time Series Insights instance with Id '{tsiId}'."); } else { Console.WriteLine($"Failed to delete a Time Series Insights instance with Id '{tsiId}'. Error Message: '{deleteInstanceErrors.Value[i].Message}'"); } } #endregion Snippet:TimeSeriesInsightsSampleDeleteInstanceById } catch (Exception ex) { Console.WriteLine($"Failed to delete Time Series Insights instance: {ex.Message}"); } }
/// <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}"); } }