top of page

Demo SQL WebApp

Step 1:

ASP.NET Core Web Application with Azure SQL Database on AWS EC2


This guide walks you through setting up and running an ASP.NET Core MVC web application using an Azure SQL Database, hosted on an AWS EC2 instance running Amazon Linux.


Prerequisites


- AWS account with access to create EC2 instances

- Azure account with access to create SQL Databases

- SSH client to connect to the EC2 instance


Steps


Step 1: Launch an EC2 Instance


1. **Launch an EC2 Instance**:

- Choose Amazon Linux 2 AMI.

- Choose an instance type (e.g., t2.micro for demo purposes).

- Configure instance details and security group to allow SSH (port 22) and HTTP (port 5000).


2. **Connect to the EC2 Instance**:

- Use SSH to connect to your EC2 instance:

```sh

ssh -i your-key-pair.pem ec2-user@your-ec2-public-ip

```


Step 2: Install Required Packages


1. **Update Your Package Manager and Install Docker**:

```sh

sudo yum update -y

sudo yum install -y docker

sudo service docker start

sudo usermod -a -G docker ec2-user


Step 2:

Install .NET SDK:

Add the Microsoft package signing key and repository:


Step 3: Create and Configure the Web Application


1. Create a New ASP.NET Core Application:

dotnet new mvc -o DemoWebApp
cd DemoWebApp

2. Add NuGet Packages for SQL Server:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 6.0.0
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 6.0.0
dotnet add package Microsoft.EntityFrameworkCore --version 6.0.0

3. Update appsettings.json:

Open appsettings.json and add the connection string:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=tcp:demodb7788.database.windows.net,1433;Initial Catalog=demodb77;Persist Security Info=False;User ID=sqladmin;Password=your_password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

4. Create a Data Model: Create a new model (e.g., Product):

mkdir Models
nano Models/Product.cs
namespace DemoWebApp.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public decimal Price { get; set; }
    }
}

5. Create a Database Context: Create a new context (e.g., ApplicationDbContext):

mkdir Data
nano Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using DemoWebApp.Models;

namespace DemoWebApp.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

        public DbSet<Product> Products { get; set; } = null!;
    }
}

6. Create and Configure Startup.cs: Create and edit Startup.cs:

nano Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using DemoWebApp.Data;

namespace DemoWebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

7. Update Program.cs: Ensure Program.cs contains the following code:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace DemoWebApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

8. Add a Controller: Create a new controller (e.g., ProductsController):

mkdir Controllers
nano Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using DemoWebApp.Data;
using DemoWebApp.Models;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

public class ProductsController : Controller
{
    private readonly ApplicationDbContext _context;

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

    public async Task<IActionResult> Index()
    {
        return View(await _context.Products.ToListAsync());
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Name,Price")] Product product)
    {
        if (ModelState.IsValid)
        {
            _context.Add(product);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(product);
    }
}

9. Create Views for Products:

a. Create Index.cshtml:

mkdir -p Views/Products
nano Views/Products/Index.cshtml
@model IEnumerable<DemoWebApp.Models.Product>

@foreach (var item in Model)
{
    <div>
        <h3>@item.Name</h3>
        <p>Price: @item.Price</p>
    </div>
}
<a href="/Products/Create">Add New Product</a>

b. Create Create.cshtml:

nano Views/Products/Create.cshtml
@model DemoWebApp.Models.Product

<h2>Create New Product</h2>

<form asp-action="Create">
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
    </div>
    <div>
        <label asp-for="Price"></label>
        <input asp-for="Price" />
    </div>
    <div>
        <input type="submit" value="Create" />
    </div>
</form>

<a href="/Products">Back to List</a>

Step 4: Run the Application

1. Modify launchSettings.json:

nano Properties/launchSettings.json

Update the configuration to listen on 0.0.0.0:

{
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://0.0.0.0:5000;https://0.0.0.0:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

2. Run the Application:

dotnet run

Step 5: Update Security Group

  1. Update Security Group:

  • Allow inbound traffic on ports 5000 (HTTP) and 5001 (HTTPS) in the security group associated with your EC2 instance.

Step 6: Access the Application

14 views0 comments

Commentaires


© Copyright
bottom of page