Ejemplo n.º 1
0
        public async Task <IEnumerable <Prediction> > GetLatestPrediction(string deviceId)
        {
            var storageConnectionString = _settings.StorageConnectionString;
            var table = await AzureTableStorageHelper.GetTableAsync(storageConnectionString, _settings.PredictionTableName);

            var startTime = DateTimeOffset.Now.AddSeconds(-TimeOffsetInSeconds).DateTime;

            var deviceFilter    = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, deviceId);
            var timestampFilter = TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, startTime);
            var filter          = TableQuery.CombineFilters(deviceFilter, TableOperators.And, timestampFilter);

            TableQuery <PredictionRecord> query = new TableQuery <PredictionRecord>()
                                                  .Where(filter)
                                                  .Take(MaxRecordsToReceive)
                                                  .Select(new[] { "Timestamp", "Rul" });

            var result   = new Collection <Prediction>();
            var entities = table.ExecuteQuery(query)
                           .OrderByDescending(x => x.RowKey)
                           .Take(MaxRecordsToSend);

            foreach (var entity in entities)
            {
                var prediction = new Prediction
                {
                    DeviceId            = entity.PartitionKey,
                    Timestamp           = entity.Timestamp.DateTime,
                    RemainingUsefulLife = (int)double.Parse(entity.Rul),
                    Cycles = int.Parse(entity.RowKey)
                };
                result.Add(prediction);
            }

            return(result.OrderBy(x => x.Cycles));
        }
Ejemplo n.º 2
0
        public async Task <TableStorageResponse <UserSetting> > SetUserSettingValueAsync(UserSetting setting)
        {
            var incomingEntity =
                new UserSettingTableEntity()
            {
                PartitionKey = _settingsTablePartitionKey,
                RowKey       = setting.Key,
                SettingValue = setting.Value
            };

            if (!string.IsNullOrWhiteSpace(setting.Etag))
            {
                incomingEntity.ETag = setting.Etag;
            }

            TableStorageResponse <UserSetting> result = await AzureTableStorageHelper.DoTableInsertOrReplaceAsync <UserSetting, UserSettingTableEntity>(incomingEntity, (tableEntity) =>
            {
                if (tableEntity == null)
                {
                    return(null);
                }

                var updatedSetting = new UserSetting()
                {
                    Key   = tableEntity.RowKey,
                    Value = tableEntity.SettingValue,
                    Etag  = tableEntity.ETag
                };

                return(updatedSetting);
            }, _storageAccountConnectionString, _settingsTableName);

            return(result);
        }
        /// <summary>
        /// Assess the self-set quota policy and number of recent calls made, and ensure that we don't exceed that number. This thread
        /// blocks if the limit set has been reached, until it is back under the required threshold
        /// </summary>
        /// <param name="identifierForThrottlingRecords">Identifier to use to track API calls to monitor calls against threshold</param>
        /// <param name="apiName">Name of the API against which calls are being monitored</param>
        private void ExecuteSelfThrottlingPolicy(string identifierForThrottlingRecords, string apiName)
        {
            switch (_selfThrottlingMethod)
            {
            case SelfThrottlingMethod.InMemoryCallRecollection:
                // Check if we have hit our limit for number of calls to the API
                while (!this.VerifyInMemoryThrottledCallCanProceed())
                {
                    Logger.Information($"Delaying issueing call to {apiName} API to ensure API throttling isn't exceeded at {DateTime.UtcNow}", "ApiInteractionHelper: ExecuteThrottledApiCall()");
                    Thread.Sleep(500);
                }

                // Add this call to the call tracker
                this.recentApiCalls.Add(DateTime.UtcNow);
                break;

            case SelfThrottlingMethod.AzureTableStorageCallRecollection:
                // Check if we have hit our limit for number of calls to the API
                while (!this.VerifyAzureTableStorageThrottledCallCanProceed(identifierForThrottlingRecords, apiName))
                {
                    Logger.Information($"Delaying issueing call to {apiName} API to ensure API throttling isn't exceeded at {DateTime.UtcNow}", "ApiInteractionHelper: ExecuteThrottledApiCall()");
                    Thread.Sleep(500);
                }

                // Add this call to the call tracker
                AzureTableStorageHelper.LogApiCallToTableStorage(new ApiCallRecordTableEntity(identifierForThrottlingRecords, apiName));
                break;

            case SelfThrottlingMethod.None:
            default:
                // Apply no throttling - proceed with call
                break;
            }
        }
        /// <summary>
        /// Return true if the number of calls to the API has not exceeded the maximum number of calls per minute in the last minute
        /// </summary>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool VerifyAzureTableStorageThrottledCallCanProceed(string apiKey, string apiName)
        {
            // Now check if we have capacity in our allocation to make a call now
            bool canProceed = true;

            // Check per minute limit
            var dateFromLastMinute = DateTime.UtcNow.AddMinutes(-1);
            var dateToLastMinute   = DateTime.UtcNow.AddMinutes(1);
            var messages           = AzureTableStorageHelper.RetrieveLogMessagesFromTableStorage(apiKey, dateFromLastMinute, dateToLastMinute);

            if ((messages != null) && (messages.Count() >= this.maxNumberOfCallsPerMinute))
            {
                canProceed = false;
            }

            // Check Daily limit
            var dateFromLastDay = DateTime.UtcNow.AddDays(-1);
            var dateTimeNow     = DateTime.UtcNow.AddMinutes(1);
            var daySpanMessages = AzureTableStorageHelper.RetrieveLogMessagesFromTableStorage(apiKey, dateFromLastDay, dateTimeNow);

            if ((daySpanMessages != null) && (daySpanMessages.Count() >= this.maxNumberOfCallsPerDay))
            {
                canProceed = false;
            }

            return(canProceed);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Save a Device Rule to the server. This may be either a new rule or an update to an existing rule.
        /// </summary>
        /// <param name="updateContainer"></param>
        /// <returns></returns>
        public async Task <TableStorageResponse <DeviceRule> > SaveDeviceRuleAsync(DeviceRule updatedRule)
        {
            DeviceRuleTableEntity incomingEntity =
                new DeviceRuleTableEntity(updatedRule.DeviceID, updatedRule.RuleId)
            {
                DataField  = updatedRule.DataField,
                Threshold  = (double)updatedRule.Threshold,
                Enabled    = updatedRule.EnabledState,
                RuleOutput = updatedRule.RuleOutput
            };

            if (!string.IsNullOrWhiteSpace(updatedRule.Etag))
            {
                incomingEntity.ETag = updatedRule.Etag;
            }

            TableStorageResponse <DeviceRule> result =
                await AzureTableStorageHelper.DoTableInsertOrReplace <DeviceRule, DeviceRuleTableEntity>(incomingEntity, BuildRuleFromTableEntity,
                                                                                                         _storageAccountConnectionString, _deviceRulesNormalizedTableName);

            // Build up a new blob to push up
            List <DeviceRuleBlobEntity> blobList = await BuildBlobEntityListFromTableRows();

            await PersistRulesToBlobStorageAsync(blobList);

            return(result);
        }
        public override async Task ProcessItem(dynamic eventData)
        {
            // Ensure this is a correctly-formatted event for ML; ignore it otherwise
            if (eventData == null || eventData.deviceid == null || eventData.cycle == null ||
                eventData.sensor9 == null || eventData.sensor11 == null || eventData.sensor14 == null || eventData.sensor15 == null)
            {
                return;
            }

            // The experiment theoretically supports multiple inputs at once,
            // even though we only get one value at a time, so the request
            // requires an array of inputs
            MLRequest mlRequest = new MLRequest(ML_REQUEST_COLUMNS, new string[, ]
            {
                {
                    // The id is required to be numeric, so we hash the actual device id
                    eventData.deviceid.ToString().GetHashCode().ToString(),
                    // The remaining entries are string representations of the numeric values
                    eventData.cycle.ToString(),
                    eventData.sensor9.ToString(),
                    eventData.sensor11.ToString(),
                    eventData.sensor14.ToString(),
                    eventData.sensor15.ToString()
                }
            }
                                                );

            HttpClient http = new HttpClient();

            http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _configurationProvider.GetConfigurationSettingValue("MLApiKey"));
            http.BaseAddress = new Uri(_configurationProvider.GetConfigurationSettingValue("MLApiUrl") + ML_ENDPOINT);

            HttpResponseMessage response = await http.PostAsJsonAsync("", mlRequest);

            if (response.IsSuccessStatusCode)
            {
                MLResponse result = JsonConvert.DeserializeObject <MLResponse>(await response.Content.ReadAsStringAsync());

                RulTableEntity entry = new RulTableEntity
                {
                    PartitionKey = eventData.deviceid.ToString(),
                    RowKey       = eventData.cycle.ToString(),
                    // Extract the single relevant RUL value from the JSON output
                    Rul = result.Results["data"].value.Values[0, RUL_COLUMN],
                    // Since the simulator might replay data, ensure we can overwrite table values
                    ETag = "*"
                };

                // We don't need a data model to represent the result of this operation,
                // so we use a stub table/model convertor
                await AzureTableStorageHelper.DoTableInsertOrReplaceAsync <object, RulTableEntity>(entry, (RulTableEntity e) => null,
                                                                                                   _configurationProvider.GetConfigurationSettingValue("eventHub.StorageConnectionString"),
                                                                                                   _configurationProvider.GetConfigurationSettingValue("MLResultTableName"));
            }
            else
            {
                throw new Exception(string.Format("The ML request failed with status code: {0}", response.StatusCode));
            }
        }
        async void ClearTables()
        {
            var telemetryTable = await AzureTableStorageHelper.GetTableAsync(_storageConnectionString, _telemetryTableName);

            var mlTable = await AzureTableStorageHelper.GetTableAsync(_storageConnectionString, _mlResultTableName);

            ClearTable(telemetryTable);
            ClearTable(mlTable);
        }
Ejemplo n.º 8
0
        private async Task <IEnumerable <DeviceRuleTableEntity> > GetAllRulesFromTable()
        {
            var deviceRulesTable = await AzureTableStorageHelper.GetTableAsync(_storageAccountConnectionString, _deviceRulesNormalizedTableName);

            TableQuery <DeviceRuleTableEntity> query = new TableQuery <DeviceRuleTableEntity>();

            return(await Task.Run(() =>
                                  deviceRulesTable.ExecuteQuery(query)
                                  ));
        }
        public async Task <string> GetSimulationState()
        {
            var table = await AzureTableStorageHelper.GetTableAsync(this.storageConnectionString, "simulatorstate");

            var query = new TableQuery <StateTableEntity>()
                        .Take(1)
                        .Select(new[] { "State" });

            var result      = table.ExecuteQuery(query);
            var stateEntity = result.FirstOrDefault();

            return(stateEntity != null ? stateEntity.State : StartStopConstants.STOPPED);
        }
Ejemplo n.º 10
0
        public async Task AddOrUpdateDeviceAsync(InitialDeviceConfig deviceConfig)
        {
            var devicesTable = await AzureTableStorageHelper.GetTableAsync(_storageConnectionString, _deviceTableName);

            var deviceEnity = new DeviceListEntity()
            {
                DeviceId = deviceConfig.DeviceId,
                HostName = deviceConfig.HostName,
                Key      = deviceConfig.Key
            };
            var operation = TableOperation.InsertOrReplace(deviceEnity);
            await devicesTable.ExecuteAsync(operation);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Retrieve a single rule from AzureTableStorage or default if none exists.
        /// A distinct rule is defined by the combination key deviceID/DataField
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="dataField"></param>
        /// <returns></returns>
        public async Task <DeviceRule> GetDeviceRuleAsync(string deviceId, string ruleId)
        {
            var deviceRulesTable = await AzureTableStorageHelper.GetTableAsync(_storageAccountConnectionString, _deviceRulesNormalizedTableName);

            TableOperation query = TableOperation.Retrieve <DeviceRuleTableEntity>(deviceId, ruleId);

            TableResult response = await Task.Run(() =>
                                                  deviceRulesTable.Execute(query)
                                                  );

            DeviceRule result = BuildRuleFromTableEntity((DeviceRuleTableEntity)response.Result);

            return(result);
        }
        public static async Task Write(string device, string state, string connectionString, string table)
        {
            StateTableEntity entry = new StateTableEntity
            {
                PartitionKey = device,
                RowKey       = "State", // Arbitrary constant; we're only storing one value per device
                State        = state,
                ETag         = "*"
            };

            // We don't need a data model to represent the result of this operation,
            // so we use a stub table/model convertor
            await AzureTableStorageHelper.DoTableInsertOrReplaceAsync <object, StateTableEntity>(entry, (StateTableEntity e) => { return(null); }, connectionString, table);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Retrieve all rules from the database that have been defined for a single device.
        /// If none exist an empty list will be returned. This method guarantees a non-null
        /// result.
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public async Task <List <DeviceRule> > GetAllRulesForDeviceAsync(string deviceId)
        {
            var deviceRulesTable = await AzureTableStorageHelper.GetTableAsync(_storageAccountConnectionString, _deviceRulesNormalizedTableName);

            TableQuery <DeviceRuleTableEntity> query = new TableQuery <DeviceRuleTableEntity>().
                                                       Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, deviceId));

            List <DeviceRule> result = new List <DeviceRule>();

            foreach (DeviceRuleTableEntity entity in deviceRulesTable.ExecuteQuery(query))
            {
                result.Add(BuildRuleFromTableEntity(entity));
            }
            return(result);
        }
Ejemplo n.º 14
0
        public async Task Initialize()
        {
            Mock <ILoggerFactory> factory = new Mock <ILoggerFactory>();
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");
            var config    = builder.Build();
            var _dbconfig = config.GetSection("CosmoDBSettings").Get <CosmoDBSettings>();

            _repository = new RawEventStorageRepository(new CosmoDBStorageInitializer(_dbconfig), factory.Object);

            await AzureTableStorageHelper.EnsurePersonIsInLocalStorage(_context, _userId, _userPersonalInfo.Initials, _userPersonalInfo.LastNameAtBirth, _userPersonalInfo.LastNameAtBirthPrefix, _userPersonalInfo.BirthDate);

            await AzureTableStorageHelper.EnsurePersonIsInLocalStorage(_context, _targetId, _targetPersonalInfo.Initials, _targetPersonalInfo.LastNameAtBirth, _targetPersonalInfo.LastNameAtBirthPrefix, _targetPersonalInfo.BirthDate);
        }
Ejemplo n.º 15
0
        public async Task CleanUp()
        {
            foreach (string eventId in _eventIdList)
            {
                await _repository.DeleteRawEventAsync(eventId, new RequestOptions()
                {
                    PartitionKey = new Microsoft.Azure.Documents.PartitionKey(Microsoft.Azure.Documents.Undefined.Value)
                });
            }

            _eventIdList.Clear();

            await AzureTableStorageHelper.CleanUpPersonFromLocalStorage(_context, _userId);

            await AzureTableStorageHelper.CleanUpPersonFromLocalStorage(_context, _targetId);
        }
Ejemplo n.º 16
0
        private async Task <InitialDeviceConfig> GetDeviceAsync(TableQuery <DeviceListEntity> query)
        {
            var devicesTable = await AzureTableStorageHelper.GetTableAsync(_storageConnectionString, _deviceTableName);

            foreach (var device in devicesTable.ExecuteQuery <DeviceListEntity>(query))
            {
                // Always return first device found
                return(new InitialDeviceConfig
                {
                    DeviceId = device.DeviceId,
                    HostName = device.HostName,
                    Key = device.Key
                });
            }
            return(null);
        }
Ejemplo n.º 17
0
        public async Task <TableStorageResponse <DeviceRule> > DeleteDeviceRuleAsync(DeviceRule ruleToDelete)
        {
            DeviceRuleTableEntity incomingEntity = BuildTableEntityFromRule(ruleToDelete);

            TableStorageResponse <DeviceRule> result =
                await AzureTableStorageHelper.DoDeleteAsync <DeviceRule, DeviceRuleTableEntity>(incomingEntity, BuildRuleFromTableEntity,
                                                                                                _storageAccountConnectionString, _deviceRulesNormalizedTableName);

            if (result.Status == TableStorageResponseStatus.Successful)
            {
                // Build up a new blob to push up for ASA job ref data
                List <DeviceRuleBlobEntity> blobList = await BuildBlobEntityListFromTableRows();
                await PersistRulesToBlobStorageAsync(blobList);
            }

            return(result);
        }
Ejemplo n.º 18
0
        public async Task <List <InitialDeviceConfig> > GetDeviceListAsync()
        {
            List <InitialDeviceConfig> devices = new List <InitialDeviceConfig>();
            var devicesTable = await AzureTableStorageHelper.GetTableAsync(_storageConnectionString, _deviceTableName);

            TableQuery <DeviceListEntity> query = new TableQuery <DeviceListEntity>();

            foreach (var device in devicesTable.ExecuteQuery(query))
            {
                var deviceConfig = new InitialDeviceConfig()
                {
                    HostName = device.HostName,
                    DeviceId = device.DeviceId,
                    Key      = device.Key
                };
                devices.Add(deviceConfig);
            }
            return(devices);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Return true if the number of calls to the API has not exceeded the maximum number of calls per minute in the last minute
        /// </summary>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool VerifyAzureTableStorageThrottledCallCanProceed(string apiKey, string apiName)
        {
            // Now check if we have capacity in our allocation to make a call now
            var dateFromLastMinute = DateTime.UtcNow.AddMinutes(-1);
            var dateToLastMinute   = DateTime.UtcNow.AddMinutes(1);
            var messages           = AzureTableStorageHelper.RetrieveLogMessagesFromTableStorage(apiKey, dateFromLastMinute, dateToLastMinute);

            if (messages == null)
            {
                return(true);
            }
            if (messages.Count() >= this.maxNumberOfCallsPerMinute)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Make a call to an API with the given details, and apply the specified self-throttling method
        /// </summary>
        /// <typeparam name="T">Type to desearalize the data returned into</typeparam>
        /// <param name="timeout">Optional time to give up after</param>
        /// <param name="webApiHelper">WebApiSerializerHelper of a given type</param>
        /// <param name="apiQueryUrl">URL of the API</param>
        /// <param name="urlParameters">Optional paramaters for the API call</param>
        /// <param name="apiKey">Optional APIKey for the API</param>
        /// <param name="apiName">Optional Name of the API for logging</param>
        /// <returns>Results of the API call, desearilized into the given object type</returns>
        public T ExecuteThrottledApiCall <T>(
            TimeSpan?timeout,
            WebApiSerializerHelper <T> webApiHelper,
            string apiQueryUrl, string urlParameters, string apiKey = null, string apiName = null)
        {
            switch (_selfThrottlingMethod)
            {
            case SelfThrottlingMethod.InMemoryCallRecollection:
                // Check if we have hit our limit for number of calls to the API
                while (!this.VerifyInMemoryThrottledCallCanProceed())
                {
                    Logger.Information($"Delaying issueing call to {apiName} API to ensure API throttling isn't exceeded at {DateTime.UtcNow}", "ApiInteractionHelper: ExecuteThrottledApiCall()");
                    Thread.Sleep(500);
                }

                // Add this call to the call tracker
                this.recentApiCalls.Add(DateTime.UtcNow);
                break;

            case SelfThrottlingMethod.AzureTableStorageCallRecollection:
                // Check if we have hit our limit for number of calls to the API
                while (!this.VerifyAzureTableStorageThrottledCallCanProceed(apiKey, apiName))
                {
                    Logger.Information($"Delaying issueing call to {apiName} API to ensure API throttling isn't exceeded at {DateTime.UtcNow}", "ApiInteractionHelper: ExecuteThrottledApiCall()");
                    Thread.Sleep(500);
                }

                // Add this call to the call tracker
                AzureTableStorageHelper.LogApiCallToTableStorage(new ApiCallRecordTableEntity(apiKey, apiName));
                break;

            case SelfThrottlingMethod.None:
            default:
                // Apply no throttling - proceed with call
                break;
            }

            var response = webApiHelper.GetHttpResponseContentAsType <T>(apiQueryUrl, urlParameters, timeout, apiKey).Result;

            return(response);
        }
Ejemplo n.º 21
0
        public async Task <bool> RemoveDeviceAsync(string deviceId)
        {
            var devicesTable = await AzureTableStorageHelper.GetTableAsync(_storageConnectionString, _deviceTableName);

            var device = await this.GetDeviceAsync(deviceId);

            if (device != null)
            {
                var operation = TableOperation.Retrieve <DeviceListEntity>(device.DeviceId, device.HostName);
                var result    = await devicesTable.ExecuteAsync(operation);

                var deleteDevice = (DeviceListEntity)result.Result;
                if (deleteDevice != null)
                {
                    var deleteOperation = TableOperation.Delete(deleteDevice);
                    await devicesTable.ExecuteAsync(deleteOperation);

                    return(true);
                }
            }
            return(false);
        }
        public async Task RepositoryIsAbleToConnectAndManagePersonalInfo()
        {
            var initializer = AzureTableStorageHelper.InitializeTableStorage();
            var repo        = new AzureTableStorageRepository <StoredPersonalInfo>(initializer, new Mock <ILogger>().Object);

            var partitionKey = "AzureTableStorageClientIntegrationTests";
            var rowKey       = "R234568";

            //  Clean up
            var sut = await repo.RetrieveRecord(partitionKey, rowKey);

            if (sut != null)
            {
                await repo.DeleteRecord(sut);
            }

            //  Insert
            await repo.InsertRecordToTable(new StoredPersonalInfo()
            {
                PartitionKey          = partitionKey,
                RowKey                = rowKey,
                initials              = "AP",
                lastNameAtBirthPrefix = "Aylen Perez",
                lastNameAtBirth       = "",
                birthdate             = "28/09/1976"
            });

            sut = await repo.RetrieveRecord(partitionKey, rowKey);

            Assert.IsNotNull(sut);
            Assert.IsInstanceOfType(sut, typeof(StoredPersonalInfo));

            //  Delete
            await repo.DeleteRecord(sut);

            sut = await repo.RetrieveRecord(partitionKey, rowKey);

            Assert.IsNull(sut);
        }
Ejemplo n.º 23
0
        public override async Task ProcessItem(dynamic eventData)
        {
            // Ensure this is a correctly-formatted event for ML; ignore it otherwise
            if (eventData == null || eventData.deviceid == null || eventData.cycle == null ||
                eventData.sensor9 == null || eventData.sensor11 == null || eventData.sensor14 == null || eventData.sensor15 == null)
            {
                return;
            }

            string result = await _mlServiceInvoker.GetRULAsync(
                // The id is required to be numeric, so we hash the actual device id
                eventData.deviceid.ToString().GetHashCode().ToString(),
                // The remaining entries are string representations of the numeric values
                eventData.cycle.ToString(),
                eventData.sensor9.ToString(),
                eventData.sensor11.ToString(),
                eventData.sensor14.ToString(),
                eventData.sensor15.ToString()
                );

            Trace.TraceInformation($"RUL Result: {result}");

            RulTableEntity entry = new RulTableEntity
            {
                PartitionKey = eventData.deviceid.ToString(),
                RowKey       = eventData.cycle.ToString(),
                // Extract the single relevant RUL value from the JSON output
                Rul = result,
                // Since the simulator might replay data, ensure we can overwrite table values
                ETag = "*"
            };

            // We don't need a data model to represent the result of this operation,
            // so we use a stub table/model convertor
            await AzureTableStorageHelper.DoTableInsertOrReplaceAsync <object, RulTableEntity>(entry, (RulTableEntity e) => null,
                                                                                               _configurationProvider.GetConfigurationSettingValue("eventHub.StorageConnectionString"),
                                                                                               _configurationProvider.GetConfigurationSettingValue("MLResultTableName"));
        }
Ejemplo n.º 24
0
        public async Task <IEnumerable <Telemetry> > GetLatestTelemetry(string deviceId)
        {
            var storageConnectionString = _settings.StorageConnectionString;
            var table = await AzureTableStorageHelper.GetTableAsync(storageConnectionString, _settings.TelemetryTableName);

            var startTime = DateTimeOffset.Now.AddSeconds(-TimeOffsetInSeconds).DateTime;

            var deviceFilter    = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, deviceId);
            var timestampFilter = TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, startTime);
            var filter          = TableQuery.CombineFilters(deviceFilter, TableOperators.And, timestampFilter);

            TableQuery <TelemetryEntity> query = new TableQuery <TelemetryEntity>()
                                                 .Where(filter)
                                                 .Take(MaxRecordsToReceive)
                                                 .Select(new[] { "sensor11", "sensor14", "sensor15", "sensor9" });

            var result   = new Collection <Telemetry>();
            var entities = table.ExecuteQuery(query)
                           .OrderByDescending(x => x.Timestamp)
                           .Take(MaxRecordsToSend);

            foreach (var entity in entities)
            {
                var telemetry = new Telemetry
                {
                    DeviceId  = entity.PartitionKey,
                    RecordId  = entity.RowKey,
                    Timestamp = entity.Timestamp.DateTime,
                    Sensor1   = Math.Round(double.Parse(entity.sensor11)),
                    Sensor2   = Math.Round(double.Parse(entity.sensor14)),
                    Sensor3   = Math.Round(double.Parse(entity.sensor15)),
                    Sensor4   = Math.Round(double.Parse(entity.sensor9))
                };
                result.Add(telemetry);
            }

            return(result.OrderBy(x => x.Timestamp));
        }
        public async Task RepositoryIsAbleToConnectAndManageContextMappings()
        {
            var initializer = AzureTableStorageHelper.InitializeTableStorage();
            var repo        = new AzureTableStorageRepository <ContextMapping>(initializer, new Mock <ILogger>().Object);

            var partitionKey = "PersonInfo";
            var rowKey       = "AzureTableStorageClientIntegrationTests";

            //  Clean up
            var sut = await repo.RetrieveRecord(partitionKey, rowKey);

            if (sut != null)
            {
                await repo.DeleteRecord(sut);
            }

            //  Insert
            await repo.InsertRecordToTable(new ContextMapping()
            {
                PartitionKey = partitionKey,
                RowKey       = rowKey,
                URL          = "http://localhost:9002/youforcereseolver"
            });

            sut = await repo.RetrieveRecord(partitionKey, rowKey);

            Assert.IsNotNull(sut);
            Assert.IsInstanceOfType(sut, typeof(ContextMapping));
            Assert.IsFalse(string.IsNullOrEmpty(sut.URL));

            //  Delete
            await repo.DeleteRecord(sut);

            sut = await repo.RetrieveRecord(partitionKey, rowKey);

            Assert.IsNull(sut);
        }
Ejemplo n.º 26
0
        public async Task <UserSetting> GetUserSettingValueAsync(string settingKey)
        {
            var settingsTable = await AzureTableStorageHelper.GetTableAsync(_storageAccountConnectionString, _settingsTableName);

            TableOperation query = TableOperation.Retrieve <UserSettingTableEntity>(_settingsTablePartitionKey, settingKey);

            TableResult response = await Task.Run(() =>
                                                  settingsTable.Execute(query)
                                                  );

            UserSetting result = null;

            if (response.Result != null && response.Result.GetType() == typeof(UserSettingTableEntity))
            {
                result = new UserSetting
                {
                    Etag  = ((UserSettingTableEntity)response.Result).ETag,
                    Key   = ((UserSettingTableEntity)response.Result).RowKey,
                    Value = ((UserSettingTableEntity)response.Result).SettingValue
                };
            }

            return(result);
        }
Ejemplo n.º 27
0
 public ApiRegistrationRepository(IConfigurationProvider configProvider)
 {
     _table = AzureTableStorageHelper.GetTable(
         configProvider.GetConfigurationSettingValue("device.StorageConnectionString"), API_TABLE_NAME);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommentsActivity" /> class.
 /// </summary>
 public CommentsActivity()
 {
     this.azureTableStorageHelper = new AzureTableStorageHelper();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TimeOffActivity" /> class.
 /// </summary>
 public TimeOffActivity()
 {
     this.azureTableStorageHelper = new AzureTableStorageHelper();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SupervisorViewTimeOffActivity" /> class.
 /// </summary>
 public SupervisorViewTimeOffActivity()
 {
     this.azureTableStorageHelper = new AzureTableStorageHelper();
 }