public async Task <List <ServerModel> > GetServersListByStateOrAllAsync(StatesEnums?state = null)
        {
            IDbBase db = null;

            try
            {
                List <ServerModel> servers = null;

                var parameters = new List <TimescaleParameter> {
                    new TimescaleParameter
                    {
                        NpgsqlValue   = state != null ? (short)state : DBNull.Value,
                        ParameterName = STATE_ID_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Smallint
                    }
                };

                db = _dbFactory.GetDbBase();

                await db.ConnectAsync();

                using (var reader = await db.ExecuteReaderFunctionAsync(GET_SERVERS_LIST_FNC_NAME, parameters))
                {
                    if (reader.HasRows)
                    {
                        servers = new List <ServerModel>();

                        while (reader.Read())
                        {
                            servers.Add(new ServerModel
                            {
                                ServerId    = Convert.ToInt64(reader["o_server_id"]),
                                ServerName  = reader["o_server_name"].ToString(),
                                ServerState = (StatesEnums)Convert.ToInt16(reader["o_state_id"])
                            });
                        }
                    }
                }

                return(servers);
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new HandledException(ex);
            }
            finally
            {
                await db?.DisconnectAsync();
            }
        }
        public async Task CreateSchema(IDbBase dbBase, string schemaName)
        {
            try
            {
                await dbBase.ExecuteNonQueryAsync($"create schema if not exists {schemaName};");
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new OutputException(
                          new Exception($"Cannot create schema {schemaName}"),
                          StatusCodes.Status500InternalServerError,
                          MnemoxStatusCodes.CANNOT_CREATE_SCHEMA);
            }
        }
예제 #3
0
        public async Task <IActionResult> AddResource([FromBody] ResourceBaseModel resourcesBaseModel)
        {
            try
            {
                var resourceId = await _resourcesDataManager.AddResource(resourcesBaseModel);

                return(Ok(new ResourceIdModel {
                    ResourceId = resourceId
                }));
            }
            catch (OutputException ex)
            {
                return(CreateErrorResultFromOutputException(ex));
            }
            catch (HandledException)
            {
                return(InternalServerErrorResult());
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                return(InternalServerErrorResult());
            }
        }
예제 #4
0
        public async Task <long> AddResource(ResourceBaseModel resource)
        {
            IDbBase dbBase = null;

            try
            {
                if (string.IsNullOrWhiteSpace(resource.Name))
                {
                    throw new OutputException(
                              new Exception(RESOURCE_NAME_IS_MANDATORY),
                              StatusCodes.Status400BadRequest,
                              MnemoxStatusCodes.INVALID_MODEL);
                }

                dbBase = _dbFactory.GetDbBase();

                var parameters = new List <TimescaleParameter>
                {
                    new TimescaleParameter
                    {
                        NpgsqlValue   = resource.Name,
                        ParameterName = RESOURCE_NAME_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Varchar
                    },
                    new TimescaleParameter
                    {
                        NpgsqlValue   = resource.Description,
                        ParameterName = RESOURCE_DESCRIPTION_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Varchar
                    },
                    new TimescaleParameter
                    {
                        NpgsqlValue   = resource.Type,
                        ParameterName = RESOURCE_TYPE_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Smallint
                    }
                };

                await dbBase.ConnectAsync();

                var resourceId = (long)await dbBase.ExecuteScalarAsync(ADD_RESOURCE_FUNCTION_NAME, parameters);

                return(resourceId);
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new HandledException(ex);
            }
            finally
            {
                if (dbBase != null)
                {
                    await dbBase.DisconnectAsync();
                }
            }
        }
예제 #5
0
        public async Task <Tokens> GetTokenDetailsFromDataStorgeAsync(string token)
        {
            IDbBase dbBase = null;

            Tokens tokenResponse = null;

            try
            {
                dbBase = _dbFactory.GetDbBase();

                var parameters = new List <TimescaleParameter>
                {
                    new TimescaleParameter
                    {
                        NpgsqlValue   = token,
                        ParameterName = TOKEN_PARAMTER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Varchar
                    }
                };

                await dbBase.ConnectAsync();

                using (var reader = await dbBase.ExecuteReaderFunctionAsync(GET_TOKEN_DETAILS_FUNCTION_NAME, parameters))
                {
                    if (reader.HasRows && reader.Read())
                    {
                        tokenResponse = new Tokens
                        {
                            TokenId = _dataManagersHelpers.GetLong(reader, OUTPUT_TOKEN_ID_PARAMTER_NAME).Value,

                            Token = _dataManagersHelpers.GetString(reader, OUTPUT_TOKEN_PARAMTER_NAME),

                            OwnerId = _dataManagersHelpers.GetLong(reader, OUTPUT_TOKEN_OWNER_ID_PARAMTER_NAME).Value,

                            MnemoxAccessObjectsType = (MnemoxAccessObjectsTypesEnum)_dataManagersHelpers.GetInt(reader, OUTPUT_TOKEN_OWNER_TYPE_ID_PARAMTER_NAME).Value,

                            ValidUntilDateTimeUtc = _dataManagersHelpers.GetDateTime(reader, OUTPUT_TOKEN_VALID_UNTIL_PARAMTER_NAME).Value
                        };
                    }
                }

                return(tokenResponse);
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new HandledException(ex);
            }
            finally
            {
                if (dbBase != null)
                {
                    await dbBase.DisconnectAsync();
                }
            }
        }
        public async Task <AuthResponse> SignIn(AuthRequest authRequest)
        {
            try
            {
                var user = await _usersDataManagerTsHelpers.GetUserByUsernameAndPassword(authRequest.Username, authRequest.Password);

                if (user == null)
                {
                    throw new OutputException(
                              new Exception(INVALID_USERNAME_OR_PASSWORD),
                              StatusCodes.Status401Unauthorized,
                              MnemoxStatusCodes.INVALID_USERNAME_OR_PASSWORD);
                }

                var token = _secretsManager.GenerateToken();

                var tokenValidUntilUtc = DateTime.UtcNow.AddMinutes(TOKEN_VALID_MINUTES);

                var tokenId = await _usersDataManagerTsHelpers.SetSignedInUserIntoStorage(user, token, tokenValidUntilUtc);

                return(new AuthResponse
                {
                    Token = token
                });
            }
            catch (OutputException)
            {
                throw;
            }
            catch (HandledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new HandledException(ex);
            }
        }
        public async Task <IActionResult> StoreHeartBeat([FromBody] HeartBeatRequest heartBeatRequest)
        {
            try
            {
                await _heartBeatDataManager.StoreHeartBeat(heartBeatRequest);
            }
            catch (HandledException)
            {
                return(InternalServerErrorResult());
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                return(InternalServerErrorResult());
            }

            return(Ok());
        }
예제 #8
0
        public WebFile GetFile(string relativePath)
        {
            try
            {
                var webFile = new WebFile();

                if (relativePath.StartsWith("/"))
                {
                    relativePath = relativePath.Substring(1);
                }

                var extension = Path.GetExtension(relativePath);

                if (string.IsNullOrWhiteSpace(extension))
                {
                    var pathToFile = Path.Combine(_serverSettings.BasePath, BASE_URL);

                    webFile.File = _webFilesManagerHelpers.GetHtmlFile(pathToFile);

                    webFile.ContentType = HTML_CONTENT_TYPE;
                }
                else
                {
                    var pathToFile = Path.Combine(_serverSettings.BasePath, relativePath);

                    webFile.File = _webFilesManagerHelpers.ReadAllBytes(pathToFile);

                    webFile.ContentType = _webFilesManagerHelpers.GetContentType(extension);
                }

                return(webFile);
            }
            catch (Exception ex)
            {
                _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw;
            }
        }
예제 #9
0
        public async Task <ActionResult <AuthResponse> > SignIn([FromBody] AuthRequest authRequest)
        {
            try
            {
                var response = await _usersDataManager.SignIn(authRequest);

                return(Ok(response));
            }
            catch (OutputException ex)
            {
                return(CreateErrorResultFromOutputException(ex));
            }
            catch (HandledException)
            {
                return(InternalServerErrorResult());
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                return(InternalServerErrorResult());
            }
        }
예제 #10
0
        public async Task StoreHeartBeat(HeartBeatRequest heartBeatRequest)
        {
            IDbBase dbBase = null;

            try
            {
                dbBase = _dbFactory.GetDbBase();

                var parameters = new List <TimescaleParameter>
                {
                    new TimescaleParameter
                    {
                        NpgsqlValue   = heartBeatRequest.InstanceId,
                        ParameterName = INSTANCE_ID_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Bigint
                    }
                };

                await dbBase.ConnectAsync();

                await dbBase.ExecuteNonQueryFunctionAsync(ADD_HEART_BEAT_FUNCTION_NAME, parameters);
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new HandledException(ex);
            }
            finally
            {
                if (dbBase != null)
                {
                    await dbBase.DisconnectAsync();
                }
            }
        }
        public async Task <List <Tenant> > GetObjectTenantsAsync(long objectId, MnemoxAccessObjectsTypesEnum objectType)
        {
            IDbBase dbBase;

            List <Tenant> objectTenants = null;

            try
            {
                var parameters = new List <TimescaleParameter>
                {
                    new TimescaleParameter
                    {
                        NpgsqlValue   = objectId,
                        ParameterName = OBJECT_ID_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Bigint
                    },
                    new TimescaleParameter
                    {
                        NpgsqlValue   = (short)objectType,
                        ParameterName = OBJECT_TYPE_ID_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Smallint
                    }
                };

                dbBase = _dbFactory.GetDbBase();

                await dbBase.ConnectAsync();

                using (var reader = await dbBase.ExecuteReaderFunctionAsync(GET_OBJECT_TENANTS_FUNCTION_NAME, parameters))
                {
                    if (!reader.HasRows)
                    {
                        return(null);
                    }

                    objectTenants = new List <Tenant>();

                    while (reader.Read())
                    {
                        var tenant = new Tenant
                        {
                            TenantId = Convert.ToInt64(reader[TENANT_ID_FIELD_NAME]),

                            Name = _dataManagersHelpers.GetString(reader, TENANT_NAME_FIELD_NAME),

                            Description = _dataManagersHelpers.GetString(reader, TENANT_DESCRIPTION_FIELD_NAME)
                        };

                        objectTenants.Add(tenant);
                    }
                }

                return(objectTenants);
            }
            catch (OutputException)
            {
                throw;
            }
            catch (HandledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new HandledException(ex);
            }
        }
        public async Task <InitializationStatesEnums> InitializeDataStorage(dynamic settings)
        {
            IDbBase db = null;

            try
            {
                InfrastructureSettings infrastructureSettings = settings;

                db = _dbFactory.GetDbBase(infrastructureSettings.ConnectonString);

                await db.ConnectAsync();

                var databaseInitializationState = await _timescaleInfrastructureHelpers.InitializationState(db);

                if (databaseInitializationState == InitializationStatesEnums.DATABASE_INITIALIZED)
                {
                    _timescaleInfrastructureHelpers.ReInitConnectionString(infrastructureSettings);

                    return(databaseInitializationState);
                }

                await _timescaleInfrastructureHelpers.CreateSchema(db, "server");

                await _timescaleInfrastructureHelpers.CreateSchema(db, "monitoring");

                await _timescaleInfrastructureHelpers.CreateExtension(db, "timescaledb", "monitoring");

                await _timescaleInfrastructureHelpers.CreateSchema(db, "resources");

                await _timescaleInfrastructureHelpers.CreateSchema(db, "tenants");

                await _timescaleInfrastructureHelpers.DropSchema(db, "public");

                await _timescaleInfrastructureHelpers.CreateExtension(db, "pgcrypto", "tenants");

                var pathToInitializationFile = Path.Combine(
                    _settingsManager.FullSettings.ServerSettings.BasePath,
                    PATH_TO_DATABASE_INITIALIZATION_FILES_FOLDER,
                    TABLES_AND_FUNCTIONS_FILE);

                var tablesAndFunctionsInitialization = _timescaleInfrastructureHelpers.LoadFile(
                    pathToInitializationFile
                    );

                await _timescaleInfrastructureHelpers.RunNonQuery(db, tablesAndFunctionsInitialization);

                await _settingsManager.ReloadSettingsAsync();

                _timescaleInfrastructureHelpers.ReInitConnectionString(infrastructureSettings);

                await _serversManager.ServerInitizalizationStateSet(InitializationStatesEnums.DATABASE_INITIALIZED);

                return(InitializationStatesEnums.DATABASE_INITIALIZED);
            }
            catch (OutputException)
            {
                throw;
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new OutputException(ex, StatusCodes.Status500InternalServerError, MnemoxStatusCodes.INTERNAL_SERVER_ERROR);
            }
            finally
            {
                await db?.DisconnectAsync();
            }
        }
예제 #13
0
        public async Task <User> GetUserByUsernameAndPassword(string username, string password)
        {
            IDbBase dbBase = null;

            User user = null;

            try
            {
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new OutputException(
                              new Exception(ALL_FIELDS_ARE_MANDATORY),
                              StatusCodes.Status400BadRequest,
                              MnemoxStatusCodes.INVALID_MODEL
                              );
                }

                var parameters = new List <TimescaleParameter>
                {
                    new TimescaleParameter
                    {
                        NpgsqlValue   = username,
                        ParameterName = USERNAME_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Varchar
                    },
                    new TimescaleParameter
                    {
                        NpgsqlValue   = password,
                        ParameterName = PASSWORD_PARAMETER_NAME,
                        NpgsqlDbType  = NpgsqlDbType.Varchar
                    }
                };

                dbBase = _dbFactory.GetDbBase();

                await dbBase.ConnectAsync();

                using (var userReader = await dbBase.ExecuteReaderFunctionAsync(SIGN_IN_USER_FUNCTION_NAME, parameters))
                {
                    if (!userReader.HasRows)
                    {
                        return(null);
                    }

                    userReader.Read();

                    user = new User
                    {
                        UserId = Convert.ToInt64(userReader[USER_ID_READER_FIELD_NAME]),

                        FirstName = _dataManagersHelpers.GetString(userReader, FIRST_NAME_READER_FIELD_NAME),

                        LastName = _dataManagersHelpers.GetString(userReader, LAST_NAME_READER_FIELD_NAME)
                    };
                }

                return(user);
            }
            catch (OutputException)
            {
                throw;
            }
            catch (Exception ex)
            {
                await _logsManager.ErrorAsync(new ErrorLogStructure(ex).WithErrorSource());

                throw new HandledException(ex);
            }
            finally
            {
                if (dbBase != null)
                {
                    await dbBase.DisconnectAsync();
                }
            }
        }