/// <summary>
        /// This sample is a placeholder to demo the snippet generation.
        /// </summary>
        public async Task RunSamplesAsync()
        {
            try
            {
                #region Snippet:TimeSeriesInsightsGetModelSettings

                // Get the model settings for the time series insights environment
                Response <TimeSeriesModelSettings> currentSettings = await client.GetModelSettingsAsync();

                Console.WriteLine($"Retrieved model with default type id {currentSettings.Value.DefaultTypeId} " +
                                  $"model name {currentSettings.Value.Name}.");

                foreach (TimeSeriesIdProperty tsiId in currentSettings.Value.TimeSeriesIdProperties)
                {
                    Console.WriteLine($"Time series Id name: '{tsiId.Name}', Type: '{tsiId.Type}'.");
                }

                #endregion Snippet:TimeSeriesInsightsGetModelSettings

                #region Snippet:TimeSeriesInsightsUpdateModelSettingsModelName

                string name = "sampleModel";
                Response <TimeSeriesModelSettings> updatedSettings = await client.UpdateModelSettingsNameAsync(name);

                Console.WriteLine($"Updated model name to {updatedSettings.Value.Name} ");

                #endregion Snippet:TimeSeriesInsightsUpdateModelSettingsModelName
            }
            catch (Exception ex)
            {
                FatalError($"Failed to create models due to:\n{ex}");
            }
        }
コード例 #2
0
        public async Task TimeSeriesInsightsClient_Construct()
        {
            TimeSeriesInsightsClient           client   = GetClient();
            Response <TimeSeriesModelSettings> response = await client.GetModelSettingsAsync().ConfigureAwait(false);

            response.GetRawResponse().Status.Should().Be(200);
        }
コード例 #3
0
        public async Task TimeSeriesInsightsClient_ModelSettingsTest()
        {
            TimeSeriesInsightsClient client = GetClient();

            // GET model settings
            Response <TimeSeriesModelSettings> currentSettings = await client.GetModelSettingsAsync().ConfigureAwait(false);

            currentSettings.GetRawResponse().Status.Should().Be((int)HttpStatusCode.OK);
            string testName = "testModel";
            // UPDATE model settings
            string typeId = await createTimeSeriesTypeAsync(client).ConfigureAwait(false);

            string defaultTypeId = await getDefaultTypeIdAsync(client).ConfigureAwait(false);

            try
            {
                Response <TimeSeriesModelSettings> updatedSettingsName = await client.UpdateModelSettingsNameAsync(testName).ConfigureAwait(false);

                updatedSettingsName.GetRawResponse().Status.Should().Be((int)HttpStatusCode.OK);
                updatedSettingsName.Value.Name.Should().Be(testName);

                await TestRetryHelper.RetryAsync <Response <TimeSeriesModelSettings> >(async() =>
                {
                    Response <TimeSeriesModelSettings> updatedSettingsId = await client.UpdateModelSettingsDefaultTypeIdAsync(typeId).ConfigureAwait(false);
                    updatedSettingsId.Value.DefaultTypeId.Should().Be(typeId);

                    // update it back to the default Type Id
                    updatedSettingsId = await client.UpdateModelSettingsDefaultTypeIdAsync(defaultTypeId).ConfigureAwait(false);
                    updatedSettingsId.Value.DefaultTypeId.Should().Be(defaultTypeId);

                    return(null);
                }, MaxNumberOfRetries, s_retryDelay);
            }
            finally
            {
                // clean up
                try
                {
                    Response <TimeSeriesOperationError[]> deleteTypesResponse = await client
                                                                                .DeleteTimeSeriesTypesbyIdAsync(new string[] { typeId })
                                                                                .ConfigureAwait(false);

                    // Assert that the response array does not have any error object set
                    deleteTypesResponse.Value.Should().OnlyContain((errorResult) => errorResult == null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Test clean up failed: {ex.Message}");
                    throw;
                }
            }
        }
コード例 #4
0
        public async Task TimeSeriesInsightsClient_ModelSettingsTest()
        {
            TimeSeriesInsightsClient client = GetClient();

            // GET model settings
            Response <TimeSeriesModelSettings> currentSettings = await client.GetModelSettingsAsync().ConfigureAwait(false);

            currentSettings.GetRawResponse().Status.Should().Be((int)HttpStatusCode.OK);
            string testName = "testModel";

            // UPDATE model settings
            Response <TimeSeriesModelSettings> updatedSettingsName = await client.UpdateModelSettingsNameAsync(testName).ConfigureAwait(false);

            updatedSettingsName.GetRawResponse().Status.Should().Be((int)HttpStatusCode.OK);
            updatedSettingsName.Value.Name.Should().Be(testName);
            // TODO 9430977: Add a test for updating default Type Id. Need existing Model type to update with associated type Id.
        }
コード例 #5
0
        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();
            }
        }
コード例 #6
0
        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.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(),
                    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.QuerySeriesAsync(
                        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.QuerySeriesAsync(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.QuerySeriesAsync(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.QuerySeriesAsync(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.QuerySeriesAsync(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();
            }
        }
コード例 #7
0
        protected async Task <string> getDefaultTypeIdAsync(TimeSeriesInsightsClient client)
        {
            Response <TimeSeriesModelSettings> currentSettings = await client.GetModelSettingsAsync().ConfigureAwait(false);

            return(currentSettings.Value.DefaultTypeId);
        }