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));
            }
        }
        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));
            }
        }
        public async Task <string> GetRULAsync(string deviceId, string cycle, string sensor9, string sensor11, string sensor14, string sensor15)
        {
            // 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
                    deviceId,
                    // The remaining entries are string representations of the numeric values
                    cycle,
                    sensor9,
                    sensor11,
                    sensor14,
                    sensor15
                }
            }
                                                );

            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());
                return(result.Results["data"].value.Values[0, RUL_COLUMN]);
            }
            else
            {
                throw new Exception(string.Format("The AML request failed with status code: {0}", response.StatusCode));
            }
        }
Пример #4
0
                                                                                     

        [HttpGet] 
 public async Task <MLResponse> GetData() 

                                                                                     {
                                                                                         
 var balanceController = new BalanceController(); 
 balanceController.SetToken(base.GetToken()); 
 var balanceHistory = await balanceController.GetHistory(DateTime.Today.AddYears(-6).ToString("yyyyMMdd"), DateTime.Today.ToString("yyyyMMdd")); 

            if (balanceHistory == null)

                                                                                         {
                                                                                             
                return(null);
                                                                                         }
                                                                                         

            foreach (var item in balanceHistory)
                                                                                         {
                                                                                             
            {
                                                                                                 
 item.TransacionAmountDecimal = decimal.Parse(item.transaction_amount); 
 item.DateDateTime = DateTime.ParseExact(item.date, "yyyyMMdd", CultureInfo.CurrentCulture); 

                                                                                             }
                                                                                         }
                                                                                         

 var firstDate = balanceHistory.OrderBy(x => x.DateDateTime).First().DateDateTime; 
 var lastMonthTransactions = balanceHistory.Where(x => x.DateDateTime > DateTime.Now.AddMonths(-3)).Count() / 3; 

 var lastMonthBalance = balanceHistory.Where(x => x.DateDateTime > DateTime.Now.AddDays(-30)).Sum(x => x.TransacionAmountDecimal); 
 var lastLastMonthBalance = balanceHistory.Where(x => x.DateDateTime > DateTime.Now.AddDays(-60) && x.DateDateTime <= DateTime.Now.AddDays(-30)).Sum(x => x.TransacionAmountDecimal); 

 var balanceTrend = 0; 
            if (lastMonthBalance > lastLastMonthBalance)

                                                                                         {
                                                                                             
 balanceTrend = 1;
                                                                                         }
                                                                                         
            else if (lastMonthBalance < lastLastMonthBalance)
                                                                                         {
                                                                                             
 balanceTrend = -1;
                                                                                         }
                                                                                         

 var investmentController = new InvestimentoController(); 
 investmentController.SetToken(base.GetToken()); 
 var investment_trend = await investmentController.EvolucaoInvestimento(DateTime.Now.AddYears(-6).ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMdd")); 
 var has_investment = await investmentController.TemInvestimento(); 

 var random = new Random(); 

 var r = new MLRequest(); 
 r.Inputs.input1.ColumnNames.Add("qtd_trans_mes"); 
 r.Inputs.input1.ColumnNames.Add("tempo_casa"); 
 r.Inputs.input1.ColumnNames.Add("tendencia_saldo"); 
 r.Inputs.input1.ColumnNames.Add("investidor"); 
 r.Inputs.input1.ColumnNames.Add("tendencia_investimento"); 
 r.Inputs.input1.ColumnNames.Add("idade"); 
 r.Inputs.input1.ColumnNames.Add("encerrou_conta"); 

 var goHorseList = new List <string>(); 
 goHorseList.Add(lastMonthTransactions.ToString()); 
 goHorseList.Add(((int)DateTime.Now.Subtract(firstDate.Date).Days / 30).ToString()); 
 goHorseList.Add(balanceTrend.ToString()); 
 goHorseList.Add(has_investment? "1" : "0"); 
 goHorseList.Add(investment_trend.ToString()); 
 goHorseList.Add(random.Next(18, 41).ToString()); 
 goHorseList.Add("0"); 

 r.Inputs.input1.Values.Add(goHorseList); 

 var client = new HttpClient(); 
 var requestBody = JsonConvert.SerializeObject(r); 
 client.DefaultRequestHeaders.Add("Authorization", "Bearer Rt/+xjyxpGNaIC70ICZblBsmp1afPTnWLO+yxH4Kv1DVfmSVm6PXGMOP0NEARk1jKBMskFchoGk5fQvn5wPimw=="); 
 var mlResponse = await client.PostAsync("https://ussouthcentral.services.azureml.net/workspaces/271e2f65c2a4436989e58d57c424a6ba/services/cf18fd70e61e4bfbb8771adb6924d6d4/execute?api-version=2.0&details=true", new StringContent(requestBody, Encoding.UTF8, "application/json")); 

            return(JsonConvert.DeserializeObject <MLResponse>(await mlResponse.Content.ReadAsStringAsync())); 

                                                                                     }