<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Trevoir Williams</title>
    <description>The latest articles on DEV Community by Trevoir Williams (@trevoirwilliams).</description>
    <link>https://dev.to/trevoirwilliams</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F762080%2Fc4929d0d-df83-4065-8c3b-eaa94957e35c.png</url>
      <title>DEV Community: Trevoir Williams</title>
      <link>https://dev.to/trevoirwilliams</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/trevoirwilliams"/>
    <language>en</language>
    <item>
      <title>Getting Started with ASP.NET Core API, EF Core, and PostgreSQL on Neon</title>
      <dc:creator>Trevoir Williams</dc:creator>
      <pubDate>Fri, 01 Nov 2024 12:38:04 +0000</pubDate>
      <link>https://dev.to/trevoirwilliams/getting-started-with-aspnet-core-api-ef-core-and-postgresql-on-neon-29gi</link>
      <guid>https://dev.to/trevoirwilliams/getting-started-with-aspnet-core-api-ef-core-and-postgresql-on-neon-29gi</guid>
      <description>&lt;p&gt;Developing applications with ASP.NET Core is a powerful way to build high-performance and cross-platform web APIs. In this guide, we’ll integrate Entity Framework Core with PostgreSQL, hosted on Neon, to handle CRUD (Create, Read, Update, Delete) operations for a "Products" table.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Visual Studio 2022 (or later) or Visual Studio Code with the .NET SDK 6+.&lt;br&gt;
Free account on &lt;a href="//Neon.tech"&gt;Neon.tech&lt;/a&gt;, a fully managed serverless PostgreSQL provider.&lt;br&gt;
Postman (optional) to test the API endpoints.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 1: Setting Up a PostgreSQL Database on Neon
&lt;/h2&gt;

&lt;p&gt;Sign up on &lt;a href="//Neon.tech"&gt;Neon.tech&lt;/a&gt; and create a new project called aspnet-project (or your preferred name) and a database (with your preferred name).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fifyycv75oxjpt4hiate1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fifyycv75oxjpt4hiate1.png" alt="Screenshot 1" width="800" height="239"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F28vlf44tzs0msfyxsmwe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F28vlf44tzs0msfyxsmwe.png" alt="Screenshot 2" width="800" height="358"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Navigate to the Project Dashboard and note down your PostgreSQL instance's connection credentials (Host, Database, User, Password, Port). We’ll need these to connect our ASP.NET Core application to Neon.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhp21585fb2obcdhin9k9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhp21585fb2obcdhin9k9.png" alt="Screenshot 3" width="800" height="505"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 2: Create the ASP.NET Core API Project
&lt;/h2&gt;

&lt;p&gt;You can set up an ASP.NET Core project using Visual Studio or the .NET CLI. Below, I’ll demonstrate using the .NET CLI, but Visual Studio follows similar steps.&lt;br&gt;
Open a terminal, navigate to your preferred project directory, and run the following command:&lt;br&gt;
&lt;code&gt;dotnet new webapi -n ProductApi&lt;br&gt;
cd ProductApi&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This creates a new ASP.NET Core Web API project called &lt;code&gt;ProductApi&lt;/code&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you want to level up your API development skills, the &lt;a href="https://www.udemy.com/course/ultimate-aspnet-5-web-api-development-guide/?referr638A9196767B3alCode=354D04A" rel="noopener noreferrer"&gt;Ultimate ASP.NET Web API Development Guide on Udemy&lt;/a&gt; is the perfect course! 🎉&lt;br&gt;
With hands-on projects, expert-led lectures, and a step-by-step approach, you’ll learn to build robust, scalable APIs using ASP.NET Core. This course is ideal for beginners and experienced developers who want to enhance their backend skills.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  Step 3: Install Entity Framework Core and the PostgreSQL Provider
&lt;/h2&gt;

&lt;p&gt;In the terminal, run the following command to install Entity Framework Core and the Npgsql provider for PostgreSQL:&lt;br&gt;
&lt;code&gt;dotnet add package Microsoft.EntityFrameworkCore&lt;br&gt;
dotnet add package Microsoft.EntityFrameworkCore.Design&lt;br&gt;
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;These packages allow us to use PostgreSQL as our database provider in Entity Framework Core.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 4: Define the Product Model
&lt;/h2&gt;

&lt;p&gt;In your project, create a folder named Models and add a &lt;code&gt;Product.cs&lt;/code&gt; file inside it. This file will contain the definition of our Product entity:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace ProductApi.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This Product model represents a simple product with an ID, Name, Description, and Price.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 5: Create the Database Context
&lt;/h2&gt;

&lt;p&gt;In the Data folder, add a new class called &lt;code&gt;AppDbContext.cs&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.EntityFrameworkCore;
using ProductApi.Models;

namespace ProductApi.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions&amp;lt;AppDbContext&amp;gt; options) : base(options) { }

        public DbSet&amp;lt;Product&amp;gt; Products { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;AppDbContext&lt;/code&gt;class inherits from &lt;code&gt;DbContext&lt;/code&gt; and specifies a DbSet for Product, enabling CRUD operations on the &lt;code&gt;Products&lt;/code&gt; table.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 6: Configure the Database Connection
&lt;/h2&gt;

&lt;p&gt;Open the &lt;code&gt;appsettings.json&lt;/code&gt; file.&lt;br&gt;
Add a connection string for your Neon PostgreSQL database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"ConnectionStrings": {
    "DefaultConnection": "Host=your_neon_host;Database=your_database;Username=your_user;Password=your_password;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace: &lt;br&gt;
your_neon_host with PGHOST &lt;br&gt;
your_database with PGDATABASE&lt;br&gt;
your_user  with PGUSER&lt;br&gt;
your_password  with PGPASSWORD&lt;/p&gt;
&lt;h3&gt;
  
  
  Recommendation: Use .NET Core User Secrets
&lt;/h3&gt;

&lt;p&gt;When deploying to production, it's crucial to never store sensitive data—such as database connection strings—in plain text within your source code or configuration files. Exposing secrets can lead to security vulnerabilities and unauthorized access.&lt;/p&gt;

&lt;p&gt;For local development, consider using .NET Core User Secrets to securely store sensitive information outside your codebase. You can leverage secure environment variables or a dedicated secrets manager in production.&lt;/p&gt;

&lt;p&gt;To set up secrets in .NET Core:&lt;br&gt;
In your project directory, run this command &lt;br&gt;
&lt;code&gt;dotnet user-secrets init&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then, add your connection string securely&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet user-secrets set "ConnectionStrings:DefaultConnection" "YourConnectionStringHere"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For added security, look into options like &lt;strong&gt;Azure Key Vault&lt;/strong&gt; or &lt;strong&gt;AWS Secrets Manager&lt;/strong&gt; to manage production secrets securely.&lt;/p&gt;

&lt;p&gt;Next, open &lt;code&gt;Program.cs&lt;/code&gt; and modify it to configure the database context:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var builder = WebApplication.CreateBuilder(args);

// Configure DbContext with PostgreSQL connection
builder.Services.AddDbContext&amp;lt;AppDbContext&amp;gt;(options =&amp;gt;
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

// Add services to the container
builder.Services.AddControllers();

var app = builder.Build();

// Configure middleware
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 7: Add a Migration and Update the Database
&lt;/h2&gt;

&lt;p&gt;Now, let’s generate a migration and apply it to our Neon PostgreSQL database to create the Products table.&lt;br&gt;
In the terminal, run:&lt;br&gt;
&lt;code&gt;dotnet ef migrations add InitialCreate&lt;br&gt;
dotnet ef database update&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Entity Framework will create a migration that defines the structure of the Products table and apply it to the Neon PostgreSQL database. You can confirm that this table is created by visiting the Tables option in the side nav.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flrwlh85w7gjocjk3u4iu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flrwlh85w7gjocjk3u4iu.png" alt="Screenshot 4" width="800" height="442"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 8: Create the Products Controller
&lt;/h2&gt;

&lt;p&gt;In the Controllers folder, add a new &lt;code&gt;ProductsController.cs&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace ProductApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly AppDbContext _context;

        public ProductsController(AppDbContext context)
        {
            _context = context;
        }

        // GET: api/products
        [HttpGet]
        public async Task&amp;lt;ActionResult&amp;lt;IEnumerable&amp;lt;Product&amp;gt;&amp;gt;&amp;gt; GetProducts()
        {
            return await _context.Products.ToListAsync();
        }

        // GET: api/products/{id}
        [HttpGet("{id}")]
        public async Task&amp;lt;ActionResult&amp;lt;Product&amp;gt;&amp;gt; GetProduct(int id)
        {
            var product = await _context.Products.FindAsync(id);

            if (product == null)
                return NotFound();

            return product;
        }

        // POST: api/products
        [HttpPost]
        public async Task&amp;lt;ActionResult&amp;lt;Product&amp;gt;&amp;gt; PostProduct(Product product)
        {
            _context.Products.Add(product);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
        }

        // PUT: api/products/{id}
        [HttpPut("{id}")]
        public async Task&amp;lt;IActionResult&amp;gt; PutProduct(int id, Product product)
        {
            if (id != product.Id)
                return BadRequest();

            _context.Entry(product).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                    return NotFound();
                throw;
            }

            return NoContent();
        }

        // DELETE: api/products/{id}
        [HttpDelete("{id}")]
        public async Task&amp;lt;IActionResult&amp;gt; DeleteProduct(int id)
        {
            var product = await _context.Products.FindAsync(id);
            if (product == null)
                return NotFound();

            _context.Products.Remove(product);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool ProductExists(int id)
        {
            return _context.Products.Any(e =&amp;gt; e.Id == id);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This controller provides methods to handle CRUD operations for the Products table. Each action method is decorated with HTTP verb attributes (HttpGet, HttpPost, HttpPut, HttpDelete) to indicate the type of operation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 9: Testing the API
&lt;/h2&gt;

&lt;p&gt;You can use tools like Postman or curl to test your API. Here are some example requests:&lt;br&gt;
&lt;code&gt;GET all products: GET https://localhost:5001/api/products&lt;br&gt;
POST a new product:{&lt;br&gt;
  "name": "Sample Product",&lt;br&gt;
  "description": "A description of the sample product",&lt;br&gt;
  "price": 19.99&lt;br&gt;
}&lt;/code&gt;&lt;/p&gt;




&lt;p&gt;And there you have it! You now have a fully functional ASP.NET Core API connected to a PostgreSQL database hosted on Neon. This setup makes building robust applications with serverless PostgreSQL and .NET Core easy.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>postgressql</category>
      <category>saas</category>
      <category>webdev</category>
    </item>
    <item>
      <title>5 Programming Principles To Live By</title>
      <dc:creator>Trevoir Williams</dc:creator>
      <pubDate>Wed, 01 Dec 2021 13:12:52 +0000</pubDate>
      <link>https://dev.to/trevoirwilliams/5-programming-principles-to-live-by-1km8</link>
      <guid>https://dev.to/trevoirwilliams/5-programming-principles-to-live-by-1km8</guid>
      <description>&lt;p&gt;As programmers, we try to follow certain rules and patterns to govern how we write code that delivers software. While these patterns might not make the software 'work better', they are important for the maintenance and longevity of the application and contribute to easily newer developers can take up the baton and run. &lt;/p&gt;

&lt;p&gt;Never forget that code should be reusable and maintainable. The following are 5 principles that will help you to maintain those standards. &lt;/p&gt;

&lt;h2&gt;
  
  
  1. KISS (Keep It 'Simple Stupid' or 'Super Simple')
&lt;/h2&gt;

&lt;p&gt;This is first on the list because it can determine how easily another developer can come and see and understand your code. Frankly, it also affect how well you can understand it after a weekend off. &lt;/p&gt;

&lt;p&gt;Commenting code is good, but when code is written in a simple and efficient manner, it can speak for itself. &lt;/p&gt;

&lt;p&gt;Always ensure that your code is solving specific problems, using the simplest and most understandable techniques possible. &lt;/p&gt;

&lt;h2&gt;
  
  
  2. DRY (Don't Repeat Yourself)
&lt;/h2&gt;

&lt;p&gt;Sometimes, it seems harmless to repeat a block of code.  But then, we need the block another time...and in another place. Then the requirement changes, that's 5 places that this block of code was repeated and 5 additional bouts of maintenance work.&lt;/p&gt;

&lt;p&gt;This is why methods and then classes exist. Try to abstract code that will be used multiple times and place in a central location that other places and developers can access it. This makes it easier to maintain in the long run and takes pressure off of maintenance and refactoring activities. &lt;/p&gt;

&lt;h2&gt;
  
  
  3. YAGNI (You Aren't Going To Need It)
&lt;/h2&gt;

&lt;p&gt;I have seen too many times where the super star developer on the team writes some code for an edge case. Edge case meaning, maybe it will...maybe it won't. Sometimes, the code is no longer needed and they just comment it out and leave it there...just in case. &lt;/p&gt;

&lt;p&gt;If you don't need code now, then don't write it. That is time that could be better spent ensuring that the current objectives are being met with relevant code. Also, don't develop attachment syndrome to code that is being deprecated. If you are using source control, then you can always retrieve the version of the code after you have removed (not just commented...but removed) it from the code base. &lt;/p&gt;

&lt;p&gt;This ultimately leads to much cleaner code and readability. &lt;/p&gt;

&lt;h2&gt;
  
  
  4. Separation of Concern
&lt;/h2&gt;

&lt;p&gt;The foundation of this principle is that you should always ensure that your blocks of code are dealing with one thing at a time. In practice, this isn't always easy to accomplish based of the framework or even language you are using, but it is something to always remember. &lt;/p&gt;

&lt;p&gt;Here are simple examples of how this can be ensured:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A &lt;strong&gt;function&lt;/strong&gt; should complete one operation. &lt;br&gt;
Don't have it doing 2 or 3. eg. Sum(int num1, int num2)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Anything written in that function should be towards a &lt;strong&gt;single outcome&lt;/strong&gt;.&lt;br&gt;
eg. Sum(4, 1) returns 5. Not 4 (Product) and .25 (quotient)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;All &lt;strong&gt;functions&lt;/strong&gt; related to &lt;strong&gt;common tasks&lt;/strong&gt;, should be put into &lt;strong&gt;one class&lt;/strong&gt;. &lt;br&gt;
class Calculator&lt;br&gt;
{&lt;br&gt;
int Sum(int num1, int num2){...}&lt;br&gt;
int Difference(int num1, int num2){...}&lt;br&gt;
int Product(int num1, int num2){...}&lt;br&gt;
int Quotient(int num1, int num2){...}&lt;br&gt;
}&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;All related classes get compiled into *&lt;em&gt;one library *&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I am sure you get the point, ensure that your code has one major task to completed per block. &lt;/p&gt;

&lt;h2&gt;
  
  
  5. Do A Design Document
&lt;/h2&gt;

&lt;p&gt;Sometimes in our zeal, we rush head first into development based on a vision and then end up making major changes in the middle of it all. &lt;/p&gt;

&lt;p&gt;It is important to have a clear design and I would extend that and say, design document. This helps you to think ahead and realize potential gaps beforehand and have a clear goal and path in mind. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Sometimes it is not about being a &lt;strong&gt;great programmer&lt;/strong&gt;, it is more about being &lt;strong&gt;proficient&lt;/strong&gt;, but adhering to &lt;strong&gt;good habits&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;You might not always get it right the first time, but always be willing to critique yourself and accept feedback as you grow in your profession.  &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>dotnet</category>
      <category>career</category>
    </item>
  </channel>
</rss>
