Esempio n. 1
0
        /// <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);
        }
Esempio n. 2
0
        /// <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);
        }
        /// <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}");
            }
        }