Skip to content

Commit

Permalink
Initial Code
Browse files Browse the repository at this point in the history
  • Loading branch information
ColinWu0403 committed Sep 19, 2024
0 parents commit 3eae2aa
Show file tree
Hide file tree
Showing 14 changed files with 448 additions and 0 deletions.
25 changes: 25 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/.idea
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
39 changes: 39 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
.metro-health-check*

# Static
node_modules
dist
dist-ssr
*.local
wwwroot
npm-debug.*

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.env
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.jks
*.p8
*.p12
*.key
*.mobileprovision
*.orig.*
.expo/
obj
bin
web-build/
113 changes: 113 additions & 0 deletions Controllers/BuildingController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using Microsoft.AspNetCore.Mvc;
using SimpleWebAppReact.Entities;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using SimpleWebAppReact.Services;

namespace SimpleWebAppReact.Controllers
{
/// <summary>
/// Defines endpoints for operations relating the Building table
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class BuildingController : ControllerBase
{
private readonly ILogger<BuildingController> _logger;
private readonly IMongoCollection<Building>? _buildings;

public BuildingController(ILogger<BuildingController> logger, MongoDbService mongoDbService)
{
_logger = logger;
_buildings = mongoDbService.Database?.GetCollection<Building>("building");
}

/// <summary>
/// gets buildings, with optional query parameters
/// </summary>
/// <param name="name"></param>
/// <param name="address"></param>
/// <returns></returns>
[HttpGet]
public async Task<IEnumerable<Building>> Get([FromQuery] string? name = null, [FromQuery] string? address = null)
{
// Build the filter using a filter builder
var filterBuilder = Builders<Building>.Filter;
var filter = FilterDefinition<Building>.Empty;

// Apply the name filter if the parameter is provided
if (!string.IsNullOrEmpty(name))
{
filter &= filterBuilder.Eq(b => b.Name, name);
}

// Apply the address filter if the parameter is provided
if (!string.IsNullOrEmpty(address))
{
filter &= filterBuilder.Eq(b => b.Address, address);
}

// Fetch the buildings from the database using the filter
return await _buildings.Find(filter).ToListAsync();
}

/// <summary>
/// gets specific building with id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<ActionResult<Building?>> GetById(string id)
{
// Simple validation to check if the ID is not null
if (string.IsNullOrEmpty(id))
{
return BadRequest("Invalid ID format.");
}

var filter = Builders<Building>.Filter.Eq(x => x.Id, id);
var building = _buildings.Find(filter).FirstOrDefault();
return building is not null ? Ok(building) : NotFound();
}

/// <summary>
/// adds building entry to table
/// </summary>
/// <param name="building"></param>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult> Post(Building building)
{
await _buildings.InsertOneAsync(building);
return CreatedAtAction(nameof(GetById), new { id = building.Id }, building);

}

/// <summary>
/// updates a building entry
/// </summary>
/// <param name="building"></param>
/// <returns></returns>
[HttpPut]
public async Task<ActionResult> Update(Building building)
{
var filter = Builders<Building>.Filter.Eq(x => x.Id, building.Id);
await _buildings.ReplaceOneAsync(filter, building);
return Ok();
}

/// <summary>
/// deletes a building entry
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(string id)
{
var filter = Builders<Building>.Filter.Eq(x => x.Id, id);
await _buildings.DeleteOneAsync(filter);
return Ok();
}
}
}

15 changes: 15 additions & 0 deletions Controllers/MyController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Mvc;

namespace SimpleWebAppReact.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet("message")] // Define the route for this action
public IActionResult GetMessage()
{
return Ok(new { message = "Hello from ASP.NET Core!" });
}
}
}
20 changes: 20 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["SimpleWebAppReact.csproj", "./"]
RUN dotnet restore "SimpleWebAppReact.csproj"
COPY . .
WORKDIR "/src/"
RUN dotnet build "SimpleWebAppReact.csproj" -c $BUILD_CONFIGURATION -o /app/build

FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "SimpleWebAppReact.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "SimpleWebAppReact.dll"]
18 changes: 18 additions & 0 deletions Entities/Building.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace SimpleWebAppReact.Entities;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
/// <summary>
/// Class structure matches 1-1 with Building Table in database
/// </summary>
public class Building
{
[BsonId]
[BsonElement("_id"), BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }

[BsonElement("name"), BsonRepresentation(BsonType.String)]
public string? Name { get; set; }

[BsonElement("address"), BsonRepresentation(BsonType.String)]
public string? Address { get; set; }
}
42 changes: 42 additions & 0 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Diagnostics;
using SimpleWebAppReact.Services;

var builder = WebApplication.CreateBuilder(args);

// Add logging configuration
builder.Logging.AddConsole(); // Enable console logging

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<MongoDbService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}

// Configure logging
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Application started.");

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors("AllowAll"); // Enable CORS

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapFallbackToFile("/index.html"); // This will serve index.html for any routes not handled by the controller
});


app.UseSwagger();
app.UseSwaggerUI();
app.Run();
31 changes: 31 additions & 0 deletions Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58527",
"sslPort": 44354
}
},
"profiles": {
"SimpleWebAppReact": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://0.0.0.0:5128",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Housing Backend

Temp name
32 changes: 32 additions & 0 deletions Services/MongoDbService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using MongoDB.Driver;

namespace SimpleWebAppReact.Services;

/// <summary>
/// MongoDB Service
/// </summary>
public class MongoDbService
{
private readonly IConfiguration _configuration;
private readonly IMongoDatabase? _database;

/// <summary>
/// constructor connects to database
/// </summary>
/// <param name="configuration"></param>
public MongoDbService(IConfiguration configuration)
{
_configuration = configuration;

var connectionString = _configuration.GetConnectionString("DbConnection");
var databaseName = _configuration.GetConnectionString("DatabaseName");
Console.WriteLine("connection information:");
Console.WriteLine(connectionString);
Console.WriteLine(databaseName);
var mongoUrl = MongoUrl.Create(connectionString);
var mongoClient = new MongoClient(mongoUrl);
_database = mongoClient.GetDatabase(databaseName);
}

public IMongoDatabase? Database => _database;
}
29 changes: 29 additions & 0 deletions SimpleWebAppReact.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.33" />
<PackageReference Include="MongoDB.Driver" Version="2.28.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="xunit" Version="2.9.0" />
</ItemGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
<_ContentIncludedByDefault Remove="ClientApp\app.json" />
<_ContentIncludedByDefault Remove="ClientApp\package-lock.json" />
<_ContentIncludedByDefault Remove="ClientApp\package.json" />
<_ContentIncludedByDefault Remove="ClientApp\tsconfig.json" />
</ItemGroup>

</Project>
Loading

0 comments on commit 3eae2aa

Please sign in to comment.