public async Task create_server_async_without_using_block() { var server = new MysticMind.PostgresEmbed.PgServer( "9.5.5.1", PG_USER, addLocalUserAccessPermission: ADD_LOCAL_USER_ACCESS_PERMISSION, clearInstanceDirOnStop: true); try { await server.StartAsync(); string connStr = string.Format(CONN_STR, server.PgPort, PG_USER); var conn = new Npgsql.NpgsqlConnection(connStr); var cmd = new Npgsql.NpgsqlCommand( "CREATE TABLE table1(ID CHAR(256) CONSTRAINT id PRIMARY KEY, Title CHAR)", conn); await conn.OpenAsync(); await cmd.ExecuteNonQueryAsync(); conn.Close(); } finally { await server.StopAsync(); } }
public async Task <ActionResult <List <Salesperson> > > Test() { var models = new List <Salesperson>(); var connectionString = _config[SystemConstants.ConnectionStringKey]; using (var connection = new Npgsql.NpgsqlConnection(connectionString)) { await connection.OpenAsync(); var command = new Npgsql.NpgsqlCommand(@"SELECT v.businessentityid, v.emailaddress, v.firstname, v.lastname, v.phonenumber, v.territoryid FROM sales.vsalesperson AS v", connection); using (var reader = await command.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { var model = new Salesperson(); model.BusinessEntityId = await reader.GetFieldValueAsync <int>(reader.GetOrdinal("businessentityid")); model.FirstName = await reader.GetFieldValueAsync <string>(reader.GetOrdinal("firstname")); model.TerritoryId = await reader.GetFieldValueAsync <int?>(reader.GetOrdinal("territoryid")); models.Add(model); } } } return(models); }
/// <summary> /// Inserts many Venue Tags /// </summary> /// <returns>Returns a result containing the created resource id</returns> public async Task <Result> ReplaceVenueDocuments(int venueId, List <VenueDocument> documents) { try { using var con = new Npgsql.NpgsqlConnection(settings.Connection.DatabaseConnectionString); await con.OpenAsync().ConfigureAwait(false); var transaction = con.BeginTransaction(); await con.ExecuteAsync(@"DELETE FROM ""VenueDocuments"" WHERE venueId = @VenueId", new { @VenueId = venueId }).ConfigureAwait(false); if (documents.Count > 0) { await con.ExecuteAsync(@"INSERT INTO ""VenueDocuments"" (venueId, documentId) VALUES (@VenueId, @DocumentId)", documents).ConfigureAwait(false); } await transaction.CommitAsync().ConfigureAwait(false); return(Result.Ok()); } catch (Exception ex) { return(Result.Fail(ex.ToString())); } }
public async Task create_server_async_and_table_test() { using (var server = new MysticMind.PostgresEmbed.PgServer( "9.5.5.1", PG_USER, addLocalUserAccessPermission: ADD_LOCAL_USER_ACCESS_PERMISSION, clearInstanceDirOnStop: true)) { await server.StartAsync(); // Note: set pooling to false to prevent connecting issues // https://github.com/npgsql/npgsql/issues/939 string connStr = string.Format(CONN_STR, server.PgPort, PG_USER); var conn = new Npgsql.NpgsqlConnection(connStr); var cmd = new Npgsql.NpgsqlCommand( "CREATE TABLE table1(ID CHAR(256) CONSTRAINT id PRIMARY KEY, Title CHAR)", conn); await conn.OpenAsync(); await cmd.ExecuteNonQueryAsync(); conn.Close(); } }
public async Task <bool> AnnotateImage(ImageAnnotationBoundingBoxResult aBbox) { try { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); Guid id = Guid.NewGuid(); var insertQuery = "INSERT INTO label.\"bounding_boxes\" (id, id_creator_fk, createdon, id_ref_trash_type_fk, id_ref_images_for_labelling, location_x, location_y, width, height) VALUES ( @Id, @CreatorId, current_timestamp, @TrashId, @ImageId, @Location_x, @Location_y, @Width, @Height)"; var result = await conn.ExecuteAsync(insertQuery, new { Id = id, CreatorId = aBbox.CreatorId, TrashId = aBbox.TrashId, ImageId = aBbox.ImageId, Location_x = aBbox.Location_x, Location_y = aBbox.Location_y, Width = aBbox.Width, Height = aBbox.Height } ); return(result > 0); } } catch (Exception e) { throw e; } }
public async Task <bool> InsertImageData(ImageLabel img) { try { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); var query = $"INSERT INTO label.\"images_for_labelling\" (id, id_creator_fk, createdon, filename, view, image_quality, context, container_url) VALUES (@Id, (SELECT id from campaign.\"user\" WHERE id=@UserId), @CreatedOn, @Filename, @View, @ImgQuality, @Context, @Url)"; var result = await conn.ExecuteAsync(query, new { Id = img.Id, UserId = img.Id_creator_fk, View = img.View, Filename = img.FileName, ImgQuality = img.Image_Quality, Context = img.Context, Url = img.Container_url, @CreatedOn = img.Createdon } ); return(result > 0); } } catch (Exception e) { throw e; } }
public async Task <ImageLabel> GetARandomImage() { try { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { string query = "SELECT * FROM label.\"images_for_labelling\" WHERE view = '' ORDER BY random() LIMIT 1"; string query2 = "SELECT * FROM label.\"images_for_labelling\" ORDER BY random() LIMIT 1"; await conn.OpenAsync(); var result = await conn.QueryAsync <ImageLabel>(query); if (!result.Any()) { result = await conn.QueryAsync <ImageLabel>(query2); } return(result.FirstOrDefault()); } } catch (Exception e) { throw e; } }
public async Task <bool> UpdateImageData(ImageLabelViewModel img) { try { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); var query = "UPDATE label.\"images_for_labelling\" SET view = @View, image_quality = @ImgQuality, context = @Context WHERE id = @ImageId"; var result = await conn.ExecuteAsync(query, new { View = img.View, ImgQuality = img.ImgQuality, Context = img.Context, ImageId = img.ImageId, } ); return(result > 0); } } catch (Exception e) { throw e; } }
public async Task <string> Create(User userData) { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); Guid id = Guid.NewGuid(); string insertQuery = "INSERT INTO campaign.\"user\" (id,firstname,lastname,email,emailconfirmed,passwordhash,yearofbirth,isdeleted,createdon) VALUES (@Id, @FirstName, @LastName, @Email, FALSE, @PassHash, @BirthYear, FALSE, @CreationTime)"; DateTime?birthDate = null; int yearOfBirth; if (Int32.TryParse(userData.BirthYear, out yearOfBirth)) { birthDate = new DateTime(yearOfBirth, 01, 01); } var result = await conn.ExecuteAsync(insertQuery, new { Id = id, userData.FirstName, userData.LastName, userData.Email, PassHash = userData.PasswordHash, BirthYear = birthDate, CreationTime = DateTime.UtcNow } ); return(id.ToString("D")); } }
/// <summary> /// Inserts many Venue Tags /// </summary> /// <returns>Returns a result containing the created resource id</returns> public async Task <Result> CreateVenueTags(int venueId, List <int> tagIds) { try { using var con = new Npgsql.NpgsqlConnection(settings.Connection.DatabaseConnectionString); await con.OpenAsync().ConfigureAwait(false); var transaction = con.BeginTransaction(); await Task.WhenAll(tagIds.Select(async _ => { return(await con.ExecuteAsync( @"INSERT INTO ""VenueTag""( venueId, tagId ) VALUES ( @VenueId, @TagId )", tagIds.Select(t => new { VenueId = venueId, TagId = t }).ToList() ).ConfigureAwait(false)); }).ToArray()).ConfigureAwait(false); await transaction.CommitAsync().ConfigureAwait(false); return(Result.Ok()); } catch (Exception ex) { return(Result.Fail(ex.ToString())); } }
/// <summary> /// Runs a stored function and returns value by using a converter /// </summary> /// <param name="name">Stored function name</param> /// <param name="param">List of parameter to use. Set null for no parameters.</param> /// <param name="connectionString">Connection sting to use</param> /// <param name="transformer">Transformer function</param> /// <param name="cancellationToken">Cancellation Token</param> /// <returns>Object</returns> public static async Task <object> HelperAsync( string name, IEnumerable <Npgsql.NpgsqlParameter> param, string connectionString, Func <Npgsql.NpgsqlCommand, CancellationToken, Task <object> > transformer, CancellationToken cancellationToken) { object result = null; if (Generics.StringExtensions.IsEmpty(name) || Generics.StringExtensions.IsEmpty(connectionString) || cancellationToken.IsCancellationRequested) { return(result); } using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(connectionString)) { using (Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand(name, connection)) { command.CommandType = System.Data.CommandType.StoredProcedure; if (param != null) { foreach (var item in param) { command.Parameters.Add(item); } } else { command.Parameters.Clear(); } try { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(cancellationToken); } await connection.OpenAsync(cancellationToken); result = await transformer(command, cancellationToken); } catch (AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); } finally { connection.Close(); } } } return(result); }
public async Task CreateTrajectoryPoints(IEnumerable <Position> positions) { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); string insertQuery = "INSERT INTO campaign.\"trajectory_point\" (id, id_ref_campaign_fk, \"time\", lat, lon, createdon) VALUES (@Id, @RefCampaign, @Time, @Lat, @Lon, @Createdon)"; var result = await conn.ExecuteAsync(insertQuery, positions); } }
public async Task CreateCampaign(Trace trace) { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); string insertQuery = "INSERT INTO campaign.\"campaign\" (id, locomotion, isaidriven, remark, id_ref_user_fk, riverside, createdon) VALUES (@Id, @Locomotion, @IsAiDriven, @Remark, @UserId, @Riverside, @CapturedOn)"; var result = await conn.ExecuteAsync(insertQuery, trace); } }
/// <summary> /// Runs a query and returns void /// </summary> /// <param name="name">Stored function name</param> /// <param name="param">List of parameter to use. Set null for no parameters.</param> /// <param name="connectionString">Connection sting to use</param> /// <param name="cancellationToken">Cancellation Token</param> /// <returns>boolean</returns> public static async Task <bool> VoidAsync(string name, IEnumerable <Npgsql.NpgsqlParameter> param, string connectionString, CancellationToken cancellationToken = default(CancellationToken)) { if (Generics.StringExtensions.IsEmpty(name) || Generics.StringExtensions.IsEmpty(connectionString) || cancellationToken.IsCancellationRequested) { return(false); } using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(connectionString)) { using (Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand(name, connection)) { command.CommandType = System.Data.CommandType.StoredProcedure; if (param != null) { foreach (var item in param) { command.Parameters.Add(item); } } else { command.Parameters.Clear(); } try { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(cancellationToken); } await connection.OpenAsync(cancellationToken); var transaction = connection.BeginTransaction(); command.Transaction = transaction; var t = await command.ExecuteNonQueryAsync(cancellationToken); transaction.Commit(); } catch (AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); } finally { connection.Close(); } } } return(true); }
public async Task DropTable(string tableName) { using (var connection = new Npgsql.NpgsqlConnection(_connectionString)) { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { command.CommandText = $"DROP TABLE {tableName};"; await command.ExecuteNonQueryAsync(); } } }
public async Task CreateTestTable(string tableName) { using (var connection = new Npgsql.NpgsqlConnection(_connectionString)) { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { command.CommandText = $"CREATE TABLE {tableName} (id serial, message text NOT NULL, created_at timestamp with time zone NOT NULL);"; await command.ExecuteNonQueryAsync(); } } }
public async Task <User> GetFromId(string userId) { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); var result = await conn.QueryAsync <User>( "select id,lastname,firstname,yearofbirth BirthYear,email,passwordhash from campaign.\"user\" WHERE isdeleted = FALSE AND id = @Id", new { Id = Guid.Parse(userId) } ); return(result.FirstOrDefault()); } }
/// <summary> /// Runs a query and returns value by using a converter /// </summary> /// <param name="query">Query to run</param> /// <param name="connectionString">Connection to use</param> /// <param name="transformer">Cancellation Token</param> /// <param name="cancellationToken"></param> /// <returns>Object</returns> public static async Task <object> HelperAsync( string query, string connectionString, Func <Npgsql.NpgsqlCommand, CancellationToken, Task <object> > transformer, CancellationToken cancellationToken) { object result = null; if (Generics.StringExtensions.IsEmpty(query) || Generics.StringExtensions.IsEmpty(connectionString) || cancellationToken.IsCancellationRequested) { return(result); } using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(connectionString)) { using (Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand(query, connection)) { command.CommandType = System.Data.CommandType.Text; try { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(cancellationToken); } await connection.OpenAsync(cancellationToken); var transaction = connection.BeginTransaction(); command.Transaction = transaction; result = await transformer(command, cancellationToken); transaction.Commit(); } catch (AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); } finally { connection.Close(); } } } return(result); }
public async Task Save(string message, string tableName) { using (var connection = new Npgsql.NpgsqlConnection(_connectionString)) { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { command.CommandText = $"insert into {tableName} (message, created_at) values (@message, clock_timestamp());"; command.Parameters.Add("message", NpgsqlDbType.Text).Value = message; await command.ExecuteNonQueryAsync(); } } }
public async Task <User> GetFromEmail(string email) { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); var result = await conn.QueryAsync <dynamic>( "select id Id, lastname LastName,firstname FirstName,yearofbirth BirthYear,email Email,passwordhash PasswordHash from campaign.user WHERE isdeleted = FALSE AND email = @Id", new { Id = email } ); dynamic r = result.First(); return(new User(r.id.ToString(), r.lastname, r.firstname, r.birthyear.ToString(), r.passwordhash, r.email)); } }
public async Task SetAccountValidated(string userId) { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); var result = await conn.ExecuteAsync( "UPDATE campaign.\"user\"" + "SET " + "emailconfirmed = True " + "WHERE id = @id", new { id = Guid.Parse(userId) } ); return; } }
public async Task <bool> UpdatePassword(string userId, string passwordHash) { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); var result = await conn.ExecuteAsync( "UPDATE campaign.\"user\" " + "SET " + "passwordhash = @hash " + "WHERE id = @id", new { id = Guid.Parse(userId), hash = passwordHash } ); return(true); } }
public async Task <bool> CheckAvailability() { try { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); await conn.QueryAsync("SELECT version();"); return(true); } } catch (Exception e) { return(false); } }
public static async Task ExecuteDatabaseAwareTest(Func <DocumentStore, MartenBasedClientRepository, Task> executor) { Random random1 = new(); String dbName = $"MartenBased-{random1.GetAlphanumericString()}"; String connectionString = $"{ConfigurationUtility.GetConnectionString("PostgresTest")};Database={dbName};"; var store = DocumentStore.For((storeOptions) => { storeOptions.CreateDatabasesForTenants(c => { c.ForTenant() .WithEncoding("UTF-8") .ConnectionLimit(-1) .OnDatabaseCreated(_ => { }); }); storeOptions.Connection(connectionString); storeOptions.AutoCreateSchemaObjects = AutoCreate.All; }); MartenBasedClientRepository repo = new(store); try { await executor(store, repo); } finally { store.Advanced.Clean.CompletelyRemoveAll(); store.Dispose(); using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection($"{ConfigurationUtility.GetConnectionString("PostgresTest")};Database=postgres;")) { await connection.OpenAsync(); Npgsql.NpgsqlCommand dropCmd = new Npgsql.NpgsqlCommand($"DROP DATABASE \"{dbName}\" WITH (FORCE);", connection); await dropCmd.ExecuteNonQueryAsync(); } } }
/// <summary> /// Returns usable and unusable IP addresses for call.route messages /// </summary> /// <returns></returns> private async Task <List <Customer> > GetIPs() { var list = new List <Customer>(); using (Npgsql.NpgsqlConnection con = new Npgsql.NpgsqlConnection(this._connectionString)) { using (Npgsql.NpgsqlCommand com = new Npgsql.NpgsqlCommand(@"SELECT HOST(address) AS ip, prefix FROM domain.customer_ip INNER JOIN customer ON customer.id = customer_ip.customer_id WHERE customer.enabled = TRUE AND customer_ip.enabled = TRUE AND customer_id IN (SELECT DISTINCT customer_id FROM customer_price WHERE NOW() BETWEEN valid_from AND valid_to);", con)) { try { com.CommandType = System.Data.CommandType.Text; await con.OpenAsync(); using (var reader = await com.ExecuteReaderAsync(System.Data.CommandBehavior.SingleResult)) { while (await reader.ReadAsync()) { list.Add(new Customer() { IP = reader.GetString(0), Prefix = reader.IsDBNull(1) ? string.Empty : reader.GetString(1) }); } } } catch (Exception ex) { Debug.WriteLine(ex); } finally { con.Close(); } } } return(list); }
/// <summary> /// Replaces a venue's set of tags with a new set /// </summary> /// <returns>Returns a result indicating if the delete succeeded</returns> public async Task <Result> ReplaceVenueTags(int venueId, List <string> tagNames) { if (tagNames.Count == 0) { return(Result.Ok()); } try { using var con = new Npgsql.NpgsqlConnection(settings.Connection.DatabaseConnectionString); await con.OpenAsync().ConfigureAwait(false); var tran = await con.BeginTransactionAsync().ConfigureAwait(false); var tags = await con.QueryAsync <Tag>("SELECT * FROM \"Tag\" WHERE tagname = ANY(@TagNames)", new { TagNames = tagNames }).ConfigureAwait(false); await con.ExecuteAsync("DELETE FROM \"VenueTag\" WHERE venueId = @VenueId", new { VenueId = venueId }).ConfigureAwait(false); var venueTags = tags.Select(t => new VenueTag { VenueId = venueId, TagId = t.TagId }).ToList(); await con.ExecuteAsync("INSERT INTO \"VenueTag\" (venueid, tagid) VALUES (@VenueId, @TagId)", venueTags).ConfigureAwait(false); try { await tran.CommitAsync().ConfigureAwait(false); } catch (Exception ex) { await tran.RollbackAsync().ConfigureAwait(false); return(Result.Fail(ex.ToString())); } return(Result.Ok()); } catch (Exception ex) { return(Result.Fail(ex.ToString())); } }
public async Task <Tuple <string, string> > GetUserPasswordHash(string userEmail) { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); var result = await conn.QueryFirstAsync( "select id, passwordHash from campaign.\"user\" WHERE isdeleted = FALSE AND email = @Email", new { Email = userEmail } ); var row = result as IDictionary <string, object>; if (row == null) { return(null); } return(new Tuple <string, string>(row["id"].ToString(), row["passwordhash"].ToString())); } }
public async Task <IEnumerable <ImageAnnotationBoundingBox> > GetBBoxForOneImage(Guid id) { try { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); string query = $"SELECT * FROM label.\"bounding_boxes\" WHERE label.\"bounding_boxes\".id_ref_images_for_labelling = \'{id}\'"; var result = await conn.QueryAsync <ImageAnnotationBoundingBox>(query); return(result); } } catch (Exception e) { throw e; } }
public async Task <IEnumerable <TrashType> > GetTrashTypes() { try { using (var conn = new Npgsql.NpgsqlConnection(_configService.GetValue(ConfigurationServiceWellKnownKeys.PostgresqlDbConnectionString))) { await conn.OpenAsync(); string query = "SELECT * FROM campaign.\"trash_type\""; var result = await conn.QueryAsync <TrashType>(query); return(result); } } catch (Exception e) { throw e; } }
/// <summary> /// Query with no return /// </summary> /// <param name="query">Query string</param> /// <param name="connectionString">Database connection string</param> /// <param name="cancellationToken">Cancellation Token</param> /// <returns>Boolean</returns> public static async Task <bool> VoidAsync(string query, string connectionString, CancellationToken cancellationToken = default(CancellationToken)) { if (Generics.StringExtensions.IsEmpty(query) || Generics.StringExtensions.IsEmpty(connectionString)) { return(false); } using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(connectionString)) { using (Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand(query, connection)) { command.CommandType = System.Data.CommandType.Text; try { await connection.OpenAsync(cancellationToken); var transaction = connection.BeginTransaction(); command.Transaction = transaction; var t = await command.ExecuteNonQueryAsync(cancellationToken); transaction.Commit(); } catch (AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); } finally { connection.Close(); } } } return(true); }