Esempio n. 1
0
        private async Task <InvokeResult> RenewRefreshToken()
        {
            var authRequest = new AuthRequest();

            authRequest.AppId         = _appConfig.AppId;
            authRequest.ClientType    = "mobileapp";
            authRequest.DeviceId      = _deviceInfo.DeviceUniqueId;
            authRequest.AppInstanceId = _authManager.AppInstanceId;
            authRequest.GrantType     = "refreshtoken";
            authRequest.UserName      = _authManager.User.Email;
            authRequest.Email         = _authManager.User.Email;
            authRequest.RefreshToken  = _authManager.RefreshToken;

            var response = await _authClient.LoginAsync(authRequest);

            if (response.Successful)
            {
                _authManager.AccessToken = response.Result.AccessToken;
                _authManager.AccessTokenExpirationUTC  = response.Result.AccessTokenExpiresUTC;
                _authManager.RefreshToken              = response.Result.RefreshToken;
                _authManager.AppInstanceId             = response.Result.AppInstanceId;
                _authManager.RefreshTokenExpirationUTC = response.Result.RefreshTokenExpiresUTC;
                _logger.AddCustomEvent(LogLevel.Message, "RawRestClient_RenewRefreshTokenAsync", "Access Token Renewed with Refresh Token");
                await _authManager.PersistAsync();

                return(InvokeResult.Success);
            }
            else
            {
                _logger.AddCustomEvent(LogLevel.Error, "RawRestClient_RenewRefreshTokenAsync", "Could Not Renew Access Token", response.ErrorsToKVPArray());
                var result = new InvokeResult();
                result.Concat(response);
                throw new Exceptions.CouldNotRenewTokenException();
            }
        }
Esempio n. 2
0
        public void ShowColor(string color)
        {
            _logger.AddCustomEvent(LogLevel.Message, "LedController_ShowColor", color);

            try
            {
                var buffer = new byte[]
                {
                    (byte)'c',
                    (byte)'o',
                    (byte)'l',
                    (byte)'o',
                    (byte)'r',
                    (byte)' ',
                    (byte)byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                    (byte)' ',
                    (byte)byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                    (byte)' ',
                    (byte)byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber),
                    (byte)';',
                };

                _ledController.Write(buffer);
            }
            catch (Exception ex)
            {
                _logger.AddException("LedController", ex);
            }
        }
Esempio n. 3
0
        protected async Task <InvokeResult> ExecWithRetry(TableOperation operation, int numberRetries = 5)
        {
            var retryCount = 0;
            var completed  = false;

            while (retryCount++ < numberRetries && !completed)
            {
                try
                {
                    var execResult = await _cloudTable.ExecuteAsync(operation);

                    completed = (execResult.HttpStatusCode == 200 || execResult.HttpStatusCode == 204);
                    if (!completed)
                    {
                        _logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Warning, "AzureTableStorageConnector_ExecWithRetry", "HTTP Error Adding PEM", execResult.HttpStatusCode.ToString().ToKVP("httpStatusCode"), retryCount.ToString().ToKVP("retryCount"));
                    }
                }
                catch (Exception ex)
                {
                    if (retryCount == numberRetries)
                    {
                        _logger.AddException("AzureTableStorageConnector_ExecWithRetry", ex);
                        return(InvokeResult.FromException("AzureTableStorageConnector_ExecWithRetyr", ex));
                    }
                    else
                    {
                        _logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Warning, "AzureTableStorageConnector_ExecWithRetry", "Exception writing PEM, will retry", ex.Message.ToKVP("exceptionMessage"), ex.GetType().Name.ToKVP("exceptionType"), retryCount.ToString().ToKVP("retryCount"));
                    }
                    await Task.Delay(retryCount * 250);
                }
            }

            return(InvokeResult.Success);
        }
        public async Task <InvokeResult> InitAsync(DataStream stream)
        {
            _stream = stream;

            var builder = new System.Data.SqlClient.SqlConnectionStringBuilder();

            builder.Add("Data Source", stream.DbURL);
            builder.Add("Initial Catalog", stream.DbName);
            builder.Add("User Id", stream.DbUserName);
            builder.Add("Password", stream.DbPassword);
            _connectionString = builder.ConnectionString;

            if (stream.DbValidateSchema)
            {
                var result = await ValidateConnectionAsync(stream);

                if (!result.Successful)
                {
                    _logger.AddCustomEvent(LogLevel.Error, "SQLServerConnecction", "Could not validate SQL Connection", result.Errors.First().Message.ToKVP("firstError"));
                    return(result.ToInvokeResult());
                }
            }

            return(InvokeResult.Success);
        }
        public async Task <InvokeResult> AddMediaAsync(byte[] data, string orgId, string fileName, string contentType)
        {
            var result = await GetStorageContainerAsync(orgId);

            if (!result.Successful)
            {
                return(result.ToInvokeResult());
            }

            var container = result.Result;

            var blob = container.GetBlockBlobReference(fileName);

            blob.Properties.ContentType = contentType;

            //TODO: Should really encapsulate the idea of retry of an action w/ error reporting
            var numberRetries = 5;
            var retryCount    = 0;
            var completed     = false;
            var stream        = new MemoryStream(data);

            while (retryCount++ < numberRetries && !completed)
            {
                try
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    await blob.UploadFromStreamAsync(stream);

                    return(InvokeResult.Success);
                }
                catch (Exception ex)
                {
                    if (retryCount == numberRetries)
                    {
                        _logger.AddException("MediaServicesRepo_AddItemAsync", ex);
                        return(InvokeResult.FromException("MediaServicesRepo_AddItemAsync", ex));
                    }
                    else
                    {
                        _logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Warning, "MediaServicesRepo_AddItemAsync", "", ex.Message.ToKVP("exceptionMessage"), ex.GetType().Name.ToKVP("exceptionType"), retryCount.ToString().ToKVP("retryCount"));
                    }
                    await Task.Delay(retryCount * 250);
                }
            }

            return(InvokeResult.Success);
        }
Esempio n. 6
0
        public async Task <InvokeResult> AddItemAsync(DataStreamRecord item)
        {
            var recordId = DateTime.UtcNow.ToInverseTicksRowKey();

            item.Data.Add(_stream.TimestampFieldName, item.GetTimeStampValue(_stream));
            item.Data.Add("sortOrder", item.GetTicks());
            item.Data.Add("deviceId", item.DeviceId);
            item.Data.Add("id", recordId);
            item.Data.Add("dataStreamId", _stream.Id);

            var fileName = $"{recordId}.json";
            var blob     = _container.GetBlockBlobReference(fileName);

            blob.Properties.ContentType = "application/json";
            var json = JsonConvert.SerializeObject(item.Data);

            var numberRetries = 5;
            var retryCount    = 0;
            var completed     = false;

            while (retryCount++ < numberRetries && !completed)
            {
                try
                {
                    await blob.UploadTextAsync(json);
                }
                catch (Exception ex)
                {
                    if (retryCount == numberRetries)
                    {
                        _logger.AddException("AzureBlobConnector_AddItemAsync", ex);
                        return(InvokeResult.FromException("AzureBlobConnector_AddItemAsync", ex));
                    }
                    else
                    {
                        _logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Warning, "AzureBlobConnector_AddItemAsync", "", ex.Message.ToKVP("exceptionMessage"), ex.GetType().Name.ToKVP("exceptionType"), retryCount.ToString().ToKVP("retryCount"));
                    }
                    await Task.Delay(retryCount * 250);
                }
            }

            return(InvokeResult.Success);
        }
        public async Task <InvokeResult> AddItemAsync(DataStreamRecord item)
        {
            var recordId = DateTime.UtcNow.ToInverseTicksRowKey();

            item.Data.Add(_stream.TimestampFieldName, item.GetTimeStampValue(_stream));
            item.Data.Add("sortOrder", item.GetTicks());
            item.Data.Add("deviceId", item.DeviceId);
            item.Data.Add("id", recordId);
            item.Data.Add("dataStreamId", _stream.Id);

            var json      = JsonConvert.SerializeObject(item.Data);
            var buffer    = Encoding.UTF8.GetBytes(json);
            var eventData = new EventData(buffer);

            var numberRetries = 5;
            var retryCount    = 0;
            var completed     = false;

            while (retryCount++ < numberRetries && !completed)
            {
                try
                {
                    await _eventHubClient.SendAsync(eventData);
                }
                catch (Exception ex)
                {
                    if (retryCount == numberRetries)
                    {
                        _logger.AddException("AzureTableStorageConnector_GetItemsAsync", ex);
                        return(InvokeResult.FromException("AzureBlobConnector_AddItemAsync", ex));
                    }
                    else
                    {
                        _logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Warning, "AzureTableStorageConnector_GetItemsAsync", "", ex.Message.ToKVP("exceptionMessage"), ex.GetType().Name.ToKVP("exceptionType"), retryCount.ToString().ToKVP("retryCount"));
                    }
                    await Task.Delay(retryCount * 250);
                }
            }

            return(InvokeResult.Success);
        }
Esempio n. 8
0
        public static void ConfigureServices(IConfigurationRoot configurationRoot, Microsoft.Extensions.DependencyInjection.IServiceCollection services, ILogger logger)
        {
            var billingDbSection = configurationRoot.GetSection("BillingDb");

            if (billingDbSection == null)
            {
                logger.AddCustomEvent(LogLevel.ConfigurationError, "BillingManager_Startup", "Missing Section BillingDb");
                throw new InvalidConfigurationException(new IoT.Logging.Error()
                {
                    ErrorCode = "CFG9991", Message = "Missing Section BillingDb"
                });
            }

            var connectionSettings = new ConnectionSettings()
            {
                Uri          = billingDbSection["ServerURL"],
                ResourceName = billingDbSection["InitialCatalog"],
                UserName     = billingDbSection["UserName"],
                Password     = billingDbSection["Password"],
            };

            if (string.IsNullOrEmpty(connectionSettings.Uri))
            {
                logger.AddCustomEvent(LogLevel.ConfigurationError, "BillingManager_Startup", "Missing BillingDb__ServerURL");
                throw new InvalidConfigurationException(new IoT.Logging.Error()
                {
                    ErrorCode = "CFG9999", Message = "Missing BillingDb__ServerURL"
                });
            }

            if (string.IsNullOrEmpty(connectionSettings.ResourceName))
            {
                logger.AddCustomEvent(LogLevel.ConfigurationError, "BillingManager_Startup", "Missing BillingDb__InitialCatalog");
                throw new InvalidConfigurationException(new IoT.Logging.Error()
                {
                    ErrorCode = "CFG9999", Message = "Missing BillingDb__InitialCatalog"
                });
            }

            if (string.IsNullOrEmpty(connectionSettings.UserName))
            {
                logger.AddCustomEvent(LogLevel.ConfigurationError, "BillingManager_Startup", "Missing BillingDb__UserName");
                throw new InvalidConfigurationException(new IoT.Logging.Error()
                {
                    ErrorCode = "CFG9999", Message = "Missing BillingDb__UserName"
                });
            }

            if (string.IsNullOrEmpty(connectionSettings.Password))
            {
                logger.AddCustomEvent(LogLevel.ConfigurationError, "BillingManager_Startup", "Missing BillingDb__Password");
                throw new InvalidConfigurationException(new IoT.Logging.Error()
                {
                    ErrorCode = "CFG9999", Message = "Missing BillingDb__Password"
                });
            }

            var connectionString = $"Server=tcp:{connectionSettings.Uri},1433;Initial Catalog={connectionSettings.ResourceName};Persist Security Info=False;User ID={connectionSettings.UserName};Password={connectionSettings.Password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

            services.AddTransient <ISubscriptionRepo, SubscriptionRepo>();
            services.AddTransient <IRDBMSManager, RDBMSManager>();
            services.AddDbContext <UserAdminDataContext>(options =>
                                                         options.UseSqlServer(connectionString, moreOptions => moreOptions.EnableRetryOnFailure()));
        }
        public async Task <ListResponse <DataStreamResult> > GetItemsAsync(Dictionary <string, object> filter, ListRequest request)
        {
            var sql = new StringBuilder("select ");

            if (request.PageSize == 0)
            {
                request.PageSize = 50;
            }

            sql.Append($"{_stream.TimestampFieldName}");
            sql.Append($", {_stream.DeviceIdFieldName}");

            foreach (var fld in _stream.Fields)
            {
                switch (fld.FieldType.Value)
                {
                case DeviceAdmin.Models.ParameterTypes.GeoLocation:
                    sql.Append($", ST_AsText({fld.FieldName}) out_{fld.FieldName}");
                    break;

                default:
                    sql.Append($", {fld.FieldName}");
                    break;
                }
            }

            sql.AppendLine();
            sql.AppendLine($"  from  {_stream.DbSchema}.{_stream.DbTableName}");
            sql.AppendLine($"  where 1 = 1"); /* just used to establish a where clause we can use by appending "and x = y" */

            _logger.AddCustomEvent(LogLevel.Message, "GetItemsAsync", sql.ToString());

            var responseItems = new List <DataStreamResult>();

            using (var cn = OpenConnection(_stream.DbName))
                using (var cmd = new NpgsqlCommand())
                {
                    Console.WriteLine(cmd.CommandText);

                    if (!String.IsNullOrEmpty(request.NextRowKey))
                    {
                        sql.AppendLine($"  and {_stream.TimestampFieldName} < @lastDateStamp");
                        cmd.Parameters.AddWithValue($"@lastDateStamp", request.NextRowKey.ToDateTime());
                    }

                    if (!String.IsNullOrEmpty(request.StartDate))
                    {
                        sql.AppendLine($"  and {_stream.TimestampFieldName} >= @startDateStamp");
                        cmd.Parameters.AddWithValue($"@startDateStamp", request.StartDate.ToDateTime());
                    }

                    if (!String.IsNullOrEmpty(request.EndDate))
                    {
                        sql.AppendLine($"  and {_stream.TimestampFieldName} <= @endDateStamp");
                        cmd.Parameters.AddWithValue($"@endDateStamp", request.EndDate.ToDateTime());
                    }

                    if (!String.IsNullOrEmpty(request.GroupBy))
                    {
                        sql.AppendLine($"  and period = @groupBy");
                        cmd.Parameters.AddWithValue($"@groupBy", request.GroupBy);
                    }

                    foreach (var filterItem in filter)
                    {
                        sql.AppendLine($"  and {filterItem.Key} = @parm{filterItem.Key}");
                        cmd.Parameters.AddWithValue($"@parm{filterItem.Key}", filterItem.Value);
                        _logger.AddCustomEvent(LogLevel.Message, "GetItemsAsync", $"{filterItem.Key} - {filterItem.Value}");
                    }

                    sql.AppendLine($"  order by {_stream.TimestampFieldName} desc");
                    sql.AppendLine($"   LIMIT {request.PageSize} OFFSET {request.PageSize * Math.Max(request.PageIndex - 1, 0)} ");

                    cmd.Connection  = cn;
                    cmd.CommandText = sql.ToString();
                    cmd.CommandType = System.Data.CommandType.Text;

                    using (var rdr = await cmd.ExecuteReaderAsync())
                    {
                        while (rdr.Read())
                        {
                            var resultItem = new DataStreamResult();
                            var timeStamp  = Convert.ToDateTime(rdr[_stream.TimestampFieldName]);
                            timeStamp            = DateTime.SpecifyKind(timeStamp, DateTimeKind.Utc);
                            resultItem.Timestamp = timeStamp.ToJSONString();

                            resultItem.Add(_stream.TimestampFieldName, resultItem.Timestamp);
                            resultItem.Add(_stream.DeviceIdFieldName, rdr[_stream.DeviceIdFieldName]);

                            foreach (var fld in _stream.Fields)
                            {
                                switch (fld.FieldType.Value)
                                {
                                case DeviceAdmin.Models.ParameterTypes.GeoLocation:
                                    var result = rdr[$"out_{fld.FieldName}"] as String;
                                    if (!String.IsNullOrEmpty(result))
                                    {
                                        var reg      = new Regex(@"^POINT\((?'lat'[\d\.\-]{2,14}) (?'lon'[\d\.\-]{2,14})\)$");
                                        var regMatch = reg.Match(result);
                                        if (regMatch.Success && regMatch.Groups.Count == 3)
                                        {
                                            var strLat = regMatch.Groups[1];
                                            var strLon = regMatch.Groups[2];
                                            if (double.TryParse(strLat.Value, out double lat) &&
                                                double.TryParse(strLat.Value, out double lon))
                                            {
                                                resultItem.Add(fld.FieldName, $"{lat:0.0000000},{lon:0.0000000}");
                                            }
                                        }
                                    }


                                    if (!resultItem.Keys.Contains(fld.FieldName))
                                    {
                                        resultItem.Add(fld.FieldName, null);
                                    }

                                    break;

                                case DeviceAdmin.Models.ParameterTypes.DateTime:
                                {
                                    var dtValue = rdr[fld.FieldName] as DateTime?;
                                    if (dtValue.HasValue)
                                    {
                                        resultItem.Add(fld.FieldName, dtValue.Value.ToJSONString());
                                    }
                                }

                                break;

                                default:
                                    resultItem.Add(fld.FieldName, rdr[fld.FieldName]);
                                    break;
                                }
                            }

                            responseItems.Add(resultItem);
                        }
                    }
                }

            var response = new Core.Models.UIMetaData.ListResponse <DataStreamResult>();

            response.Model          = responseItems;
            response.PageSize       = responseItems.Count;
            response.PageIndex      = request.PageIndex;
            response.HasMoreRecords = responseItems.Count == request.PageSize;
            if (response.HasMoreRecords)
            {
                response.NextRowKey = responseItems.Last().Timestamp;
            }

            return(response);
        }