Exemplo n.º 1
0
        private static async Task RunGetInstancesAsync()
        {
            string continuationToken;

            // Limit the total instances received.
            int limit = 1000;
            int totalInstanceCount           = 0;
            TimeSeriesInstance firstInstance = null;

            do
            {
                GetInstancesPage instancesPage = await _client.GetInstancesPagedAsync();

                if (instancesPage.Instances != null)
                {
                    totalInstanceCount += instancesPage.Instances.Count;

                    Console.WriteLine("Received instances : {0}", totalInstanceCount);

                    if (firstInstance == null)
                    {
                        firstInstance = instancesPage.Instances.FirstOrDefault();
                    }
                }

                continuationToken = instancesPage.ContinuationToken;
            }while (continuationToken != null && totalInstanceCount < limit);

            Console.WriteLine("First Instance:");
            PrintResponse(firstInstance);
        }
Exemplo n.º 2
0
 private static void PrintResponse(TimeSeriesInstance timeSeriesInstance)
 {
     Console.WriteLine("Time Series Instance");
     Console.WriteLine("  Time Series ID: {0}", string.Join(", ", timeSeriesInstance.TimeSeriesId));
     Console.WriteLine("  Description: {0}", timeSeriesInstance.Description);
     Console.WriteLine("  Type ID: {0}", timeSeriesInstance.TypeId);
     Console.WriteLine("  Hierarchy IDs: \n    {0}\n", timeSeriesInstance.HierarchyIds != null ? string.Join("\n    ", timeSeriesInstance.HierarchyIds) : "null");
     Console.WriteLine("  Instance Fields: \n    {0}\n", timeSeriesInstance.InstanceFields != null ? string.Join("\n    ", timeSeriesInstance.InstanceFields.Select(i => $"{i.Key}: {i.Value}")) : "null");
 }
Exemplo n.º 3
0
 internal InstancesOperationResult(TimeSeriesInstance instance, TimeSeriesOperationError error)
 {
     Instance = instance;
     Error    = error;
 }
        public async Task TimeSeriesInsightsInstances_Lifecycle()
        {
            // Arrange
            TimeSeriesInsightsClient        client = GetClient();
            TimeSeriesInsightsModelSettings modelSettingsClient = client.GetModelSettingsClient();
            TimeSeriesInsightsInstances     instancesClient     = client.GetInstancesClient();

            int numOfInstancesToSetup = 2;
            var timeSeriesInstances   = new List <TimeSeriesInstance>();
            Response <TimeSeriesModelSettings> currentSettings = await modelSettingsClient.GetAsync().ConfigureAwait(false);

            string defaultTypeId     = currentSettings.Value.DefaultTypeId;
            int    numOfIdProperties = currentSettings.Value.TimeSeriesIdProperties.Count;

            for (int i = 0; i < numOfInstancesToSetup; i++)
            {
                TimeSeriesId id = await GetUniqueTimeSeriesInstanceIdAsync(instancesClient, numOfIdProperties)
                                  .ConfigureAwait(false);

                var instance = new TimeSeriesInstance(id, defaultTypeId)
                {
                    Name = Recording.GenerateAlphaNumericId("instance"),
                };
                timeSeriesInstances.Add(instance);
            }

            IEnumerable <TimeSeriesId> timeSeriesInstancesIds = timeSeriesInstances.Select((instance) => instance.TimeSeriesId);

            // Act and assert
            try
            {
                await TestRetryHelper.RetryAsync <Response <InstancesOperationResult[]> >((Func <Task <Response <InstancesOperationResult[]> > >)(async() =>
                {
                    // Create TSI instances
                    Response <TimeSeriesOperationError[]> createInstancesResult = await instancesClient
                                                                                  .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);

                    // Get the created instances by Ids
                    Response <InstancesOperationResult[]> getInstancesByIdsResult = await instancesClient
                                                                                    .GetByIdAsync(timeSeriesInstancesIds)
                                                                                    .ConfigureAwait(false);

                    getInstancesByIdsResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                    foreach (InstancesOperationResult instanceResult in getInstancesByIdsResult.Value)
                    {
                        instanceResult.Instance.Should().NotBeNull();
                        instanceResult.Error.Should().BeNull();
                        instanceResult.Instance.TimeSeriesId.ToStringArray().Length.Should().Be(numOfIdProperties);
                        AssertionExtensions.Should(instanceResult.Instance.TimeSeriesTypeId).Be(defaultTypeId);
                        instanceResult.Instance.HierarchyIds.Count.Should().Be(0);
                        instanceResult.Instance.InstanceFields.Count.Should().Be(0);
                    }

                    // Update the instances by adding descriptions to them
                    timeSeriesInstances.ForEach((timeSeriesInstance) =>
                                                timeSeriesInstance.Description = "Description");

                    Response <InstancesOperationResult[]> replaceInstancesResult = await instancesClient
                                                                                   .ReplaceAsync(timeSeriesInstances)
                                                                                   .ConfigureAwait(false);

                    replaceInstancesResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                    replaceInstancesResult.Value.Should().OnlyContain((errorResult) => errorResult.Error == null);

                    // Get instances by name
                    Response <InstancesOperationResult[]> getInstancesByNameResult = await instancesClient
                                                                                     .GetByNameAsync(timeSeriesInstances.Select((instance) => instance.Name))
                                                                                     .ConfigureAwait(false);

                    getInstancesByNameResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                    foreach (InstancesOperationResult instanceResult in getInstancesByNameResult.Value)
                    {
                        instanceResult.Instance.Should().NotBeNull();
                        instanceResult.Error.Should().BeNull();
                        instanceResult.Instance.TimeSeriesId.ToStringArray().Length.Should().Be(numOfIdProperties);
                        AssertionExtensions.Should(instanceResult.Instance.TimeSeriesTypeId).Be(defaultTypeId);
                        instanceResult.Instance.HierarchyIds.Count.Should().Be(0);
                        instanceResult.Instance.InstanceFields.Count.Should().Be(0);
                    }

                    // Get all Time Series instances in the environment
                    AsyncPageable <TimeSeriesInstance> getAllInstancesResponse = instancesClient.GetAsync();

                    int numOfInstances = 0;
                    await foreach (TimeSeriesInstance tsiInstance in getAllInstancesResponse)
                    {
                        numOfInstances++;
                        tsiInstance.Should().NotBeNull();
                    }
                    numOfInstances.Should().BeGreaterOrEqualTo(numOfInstancesToSetup);
                    return(null);
                }), MaxNumberOfRetries, s_retryDelay);
            }
            finally
            {
                // clean up
                try
                {
                    Response <TimeSeriesOperationError[]> deleteInstancesResponse = await instancesClient
                                                                                    .DeleteByIdAsync(timeSeriesInstancesIds)
                                                                                    .ConfigureAwait(false);

                    // Assert that the response array does not have any error object set
                    deleteInstancesResponse.Value.Should().OnlyContain((errorResult) => errorResult == null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Test clean up failed: {ex.Message}");
                    throw;
                }
            }
        }
Exemplo n.º 5
0
        private async Task RunQuerySeriesSampleWithPreDefinedVariables(TimeSeriesInsightsClient client, TimeSeriesId tsId)
        {
            // Setup
            TimeSeriesInsightsInstances instancesClient = client.GetInstancesClient();
            TimeSeriesInsightsTypes     typesClient     = client.GetTypesClient();
            TimeSeriesInsightsQueries   queriesClient   = client.GetQueriesClient();

            // First create the Time Series type along with the numeric variables
            var timeSeriesTypes = new List <TimeSeriesType>();

            var celsiusVariable = new NumericVariable(
                new TimeSeriesExpression("$event.Temperature"),
                new TimeSeriesExpression("avg($value)"));
            var fahrenheitVariable = new NumericVariable(
                new TimeSeriesExpression("$event.Temperature * 1.8 + 32"),
                new TimeSeriesExpression("avg($value)"));

            var celsiusVariableName    = "TemperatureInCelsius";
            var fahrenheitVariableName = "TemperatureInFahrenheit";
            var variables = new Dictionary <string, TimeSeriesVariable>
            {
                { celsiusVariableName, celsiusVariable },
                { fahrenheitVariableName, fahrenheitVariable }
            };

            timeSeriesTypes.Add(new TimeSeriesType("TemperatureSensor", variables)
            {
                Id = "TemperatureSensorTypeId"
            });

            Response <TimeSeriesTypeOperationResult[]> createTypesResult = await typesClient
                                                                           .CreateOrReplaceAsync(timeSeriesTypes)
                                                                           .ConfigureAwait(false);

            if (createTypesResult.Value.First().Error != null)
            {
                Console.WriteLine($"\n\nFailed to create a Time Series Insights type. " +
                                  $"Error Message: '{createTypesResult.Value.First().Error.Message}.' " +
                                  $"Code: '{createTypesResult.Value.First().Error.Code}'.");
            }

            // Get the Time Series instance and replace its type with the one we just created
            Response <InstancesOperationResult[]> getInstanceResult = await instancesClient
                                                                      .GetAsync(new List <TimeSeriesId> {
                tsId
            });

            if (getInstanceResult.Value.First().Error != null)
            {
                Console.WriteLine($"\n\nFailed to retrieve Time Series instance with Id '{tsId}'. " +
                                  $"Error Message: '{getInstanceResult.Value.First().Error.Message}.' " +
                                  $"Code: '{getInstanceResult.Value.First().Error.Code}'.");
            }

            TimeSeriesInstance instanceToReplace = getInstanceResult.Value.First().Instance;

            instanceToReplace.TypeId = createTypesResult.Value.First().TimeSeriesType.Id;
            Response <InstancesOperationResult[]> replaceInstanceResult = await instancesClient
                                                                          .ReplaceAsync(new List <TimeSeriesInstance> {
                instanceToReplace
            });

            if (replaceInstanceResult.Value.First().Error != null)
            {
                Console.WriteLine($"\n\nFailed to retrieve Time Series instance with Id '{tsId}'. " +
                                  $"Error Message: '{replaceInstanceResult.Value.First().Error.Message}.' " +
                                  $"Code: '{replaceInstanceResult.Value.First().Error.Code}'.");
            }

            // Now that we set up the instance with the property type, query for the data
            #region Snippet:TimeSeriesInsightsSampleQuerySeries
            Console.WriteLine($"\n\nQuery for temperature series in Celsius and Fahrenheit over the past 10 minutes. " +
                              $"The Time Series instance belongs to a type that has predefined numeric variable that represents the temperature " +
                              $"in Celsuis, and a predefined numeric variable that represents the temperature in Fahrenheit.\n");

            DateTimeOffset endTime     = DateTime.UtcNow;
            DateTimeOffset startTime   = endTime.AddMinutes(-10);
            QueryAnalyzer  seriesQuery = queriesClient.CreateSeriesQuery(
                tsId,
                startTime,
                endTime);

            await foreach (TimeSeriesPoint point in seriesQuery.GetResultsAsync())
            {
                double?tempInCelsius    = point.GetNullableDouble(celsiusVariableName);
                double?tempInFahrenheit = point.GetNullableDouble(fahrenheitVariableName);

                Console.WriteLine($"{point.Timestamp} - Average temperature in Celsius: {tempInCelsius}. " +
                                  $"Average temperature in Fahrenheit: {tempInFahrenheit}.");
            }
            #endregion Snippet:TimeSeriesInsightsSampleQuerySeries
        }
        public async Task TimeSeriesInsightsInstances_Lifecycle()
        {
            // Arrange
            TimeSeriesInsightsClient client = GetClient();
            int    numOfIdProperties        = 3;
            int    numOfInstancesToSetup    = 2;
            var    timeSeriesInstances      = new List <TimeSeriesInstance>();
            string defaultTypeId            = await getDefaultTypeIdAsync(client).ConfigureAwait(false);

            for (int i = 0; i < numOfInstancesToSetup; i++)
            {
                TimeSeriesId id = await GetUniqueTimeSeriesInstanceIdAsync(client, numOfIdProperties)
                                  .ConfigureAwait(false);

                var instance = new TimeSeriesInstance(id, defaultTypeId)
                {
                    Name = Recording.GenerateAlphaNumericId("instance"),
                };
                timeSeriesInstances.Add(instance);
            }

            IEnumerable <TimeSeriesId> timeSeriesInstancesIds = timeSeriesInstances.Select((instance) => instance.TimeSeriesId);

            // Act and assert
            try
            {
                await TestRetryHelper.RetryAsync <Response <InstancesOperationResult[]> >(async() =>
                {
                    // Create TSI instances
                    Response <TimeSeriesOperationError[]> createInstancesResult = await client
                                                                                  .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);

                    // Get the created instances by Ids
                    Response <InstancesOperationResult[]> getInstancesByIdsResult = await client
                                                                                    .Instances
                                                                                    .GetAsync(timeSeriesInstancesIds)
                                                                                    .ConfigureAwait(false);

                    getInstancesByIdsResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                    foreach (InstancesOperationResult instanceResult in getInstancesByIdsResult.Value)
                    {
                        instanceResult.Instance.Should().NotBeNull();
                        instanceResult.Error.Should().BeNull();
                        instanceResult.Instance.TimeSeriesId.ToArray().Length.Should().Be(numOfIdProperties);
                        instanceResult.Instance.TypeId.Should().Be(defaultTypeId);
                        instanceResult.Instance.HierarchyIds.Count.Should().Be(0);
                        instanceResult.Instance.InstanceFields.Count.Should().Be(0);
                    }

                    return(null);
                }, MaxNumberOfRetries, s_retryDelay);

                // Update the instances by adding descriptions to them
                timeSeriesInstances.ForEach((timeSeriesInstance) =>
                                            timeSeriesInstance.Description = "Description");

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

                replaceInstancesResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                replaceInstancesResult.Value.Should().OnlyContain((errorResult) => errorResult.Error == null);

                // This retry logic was added as the TSI instance are not immediately available after creation
                await TestRetryHelper.RetryAsync <Response <InstancesOperationResult[]> >(async() =>
                {
                    // Get instances by name
                    Response <InstancesOperationResult[]> getInstancesByNameResult = await client
                                                                                     .Instances
                                                                                     .GetAsync(timeSeriesInstances.Select((instance) => instance.Name))
                                                                                     .ConfigureAwait(false);

                    getInstancesByNameResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                    foreach (InstancesOperationResult instanceResult in getInstancesByNameResult.Value)
                    {
                        instanceResult.Instance.Should().NotBeNull();
                        instanceResult.Error.Should().BeNull();
                        instanceResult.Instance.TimeSeriesId.ToArray().Length.Should().Be(numOfIdProperties);
                        instanceResult.Instance.TypeId.Should().Be(defaultTypeId);
                        instanceResult.Instance.HierarchyIds.Count.Should().Be(0);
                        instanceResult.Instance.InstanceFields.Count.Should().Be(0);
                    }

                    return(null);
                }, MaxNumberOfRetries, s_retryDelay);

                // Get all Time Series instances in the environment
                AsyncPageable <TimeSeriesInstance> getAllInstancesResponse = client.Instances.GetAsync();

                int numOfInstances = 0;
                await foreach (TimeSeriesInstance tsiInstance in getAllInstancesResponse)
                {
                    numOfInstances++;
                    tsiInstance.Should().NotBeNull();
                }
                numOfInstances.Should().BeGreaterOrEqualTo(numOfInstancesToSetup);

                // Get search suggestions for the first instance
                TimeSeriesId timeSeriesIdToSuggest = timeSeriesInstances.First().TimeSeriesId;
                string       suggestionString      = timeSeriesIdToSuggest.ToArray().First();
                Response <SearchSuggestion[]> searchSuggestionResponse = await TestRetryHelper.RetryAsync(async() =>
                {
                    Response <SearchSuggestion[]> searchSuggestions = await client
                                                                      .Instances
                                                                      .GetSearchSuggestionsAsync(suggestionString)
                                                                      .ConfigureAwait(false);

                    if (searchSuggestions.Value.Length == 0)
                    {
                        throw new Exception($"Unable to find a search suggestion for string {suggestionString}.");
                    }

                    return(searchSuggestions);
                }, MaxNumberOfRetries, s_retryDelay);

                searchSuggestionResponse.Value.Length.Should().Be(1);
            }
            finally
            {
                // clean up
                try
                {
                    Response <TimeSeriesOperationError[]> deleteInstancesResponse = await client
                                                                                    .Instances
                                                                                    .DeleteAsync(timeSeriesInstancesIds)
                                                                                    .ConfigureAwait(false);

                    // Assert that the response array does not have any error object set
                    deleteInstancesResponse.Value.Should().OnlyContain((errorResult) => errorResult == null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Test clean up failed: {ex.Message}");
                    throw;
                }
            }
        }
        /// <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}");
            }
        }
Exemplo n.º 8
0
 internal InstanceOrError(TimeSeriesInstance instance, TsiErrorBody error)
 {
     Instance = instance;
     Error    = error;
 }
Exemplo n.º 9
0
        /// <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}");
            }
        }