add openhack files

This commit is contained in:
Ryan Peters
2022-11-03 16:41:13 -04:00
commit b2c9f7e29f
920 changed files with 118861 additions and 0 deletions

264
apis/poi/web/.gitignore vendored Normal file
View File

@ -0,0 +1,264 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# Azure Functions localsettings file
local.settings.json
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
#*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

View File

@ -0,0 +1,64 @@
using System;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Collections.Generic;
using poi.Models;
using poi.Data;
namespace poi.Controllers
{
[Produces("application/json")]
[Route("api/poi")]
public class POIController : ControllerBase
{
private readonly POIContext _context;
public POIController(POIContext context)
{
_context = context;
}
[HttpGet(Name = "GetAllPOIs")]
[Produces("application/json", Type = typeof(POI))]
public List<POI> GetAll()
{
return _context.POIs.ToList();
}
[HttpGet("{ID}", Name = "GetPOIById")]
[Produces("application/json", Type = typeof(POI))]
public IActionResult GetById(string ID)
{
var item = _context.POIs.Find(ID);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
[HttpGet("trip/{tripID}", Name = "GetPOIsByTripId")]
[Produces("application/json", Type = typeof(POI))]
public IActionResult GetByTripId(string tripID)
{
var items = _context.POIs.Where(poi => poi.TripId == tripID).ToList<POI>();
if (items == null)
{
return NotFound();
}
return Ok(items);
}
[HttpPost(Name = "CreatePOI")]
public IActionResult CreatePoi([FromBody] POI poi)
{
poi.Id = Guid.NewGuid().ToString();
_context.POIs.Add(poi);
_context.SaveChanges();
return Ok(poi);
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using Microsoft.AspNetCore.Mvc;
namespace poi.Controllers
{
[Produces("application/json")]
[Route("api")]
public class VersionController : ControllerBase
{
[Route("version/poi")]
[HttpGet]
[Produces("text/plain", Type = typeof(String))]
public string GetVersion()
{
var version = Environment.GetEnvironmentVariable("APP_VERSION");
return version ?? "default";
}
}
}

View File

@ -0,0 +1,15 @@
using Microsoft.EntityFrameworkCore;
using poi.Models;
namespace poi.Data
{
public class POIContext : DbContext
{
public POIContext(DbContextOptions<POIContext> options) : base(options)
{
}
public DbSet<POI> POIs { get; set; }
}
}

37
apis/poi/web/Dockerfile Normal file
View File

@ -0,0 +1,37 @@
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app
# copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
# copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
COPY ./appsettings.*.json /app/out/
COPY ./appsettings.json /app/out/
# build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
# docker build argument
# This can be specified during the docker build step by adding " --build-arg build_version=<value>"
# App version can be accessed via the uri path /api/version/poi
# https://vsupalov.com/docker-build-pass-environment-variables/
ARG build_version="poi default"
ENV SQL_USER="YourUserName" \
SQL_PASSWORD="changeme" \
SQL_SERVER="changeme.database.windows.net" \
SQL_DBNAME="mydrivingDB" \
WEB_PORT="8080" \
WEB_SERVER_BASE_URI="http://0.0.0.0" \
ASPNETCORE_ENVIRONMENT="Production" \
APP_VERSION=$build_version
COPY --from=build-env /app/out .
EXPOSE 8080
ENTRYPOINT ["dotnet", "poi.dll"]

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace poi.Models
{
public class BaseDataObject
{
public string Id { get; set; }
public BaseDataObject()
{
Id = Guid.NewGuid().ToString();
}
}
}

View File

@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace poi.Models
{
public enum POIType
{
HardAcceleration = 1,
HardBrake = 2
}
public class POI : BaseDataObject
{
public string TripId { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public POIType PoiType { get; set; }
public DateTime Timestamp { get; set; }
public bool Deleted { get; set; }
}
}

52
apis/poi/web/Program.cs Normal file
View File

@ -0,0 +1,52 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using poi.Utility;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace poi
{
[ExcludeFromCodeCoverage]
public class Program
{
public static void Main(string[] args) => CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args)
{
//used to read env variables for host/port
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseConfiguration(configuration)
.UseIISIntegration()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
})
.UseStartup<Startup>()
.UseUrls(POIConfiguration.GetUri(configuration));
});
return host;
}
}
}

103
apis/poi/web/Startup.cs Normal file
View File

@ -0,0 +1,103 @@
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using poi.Data;
namespace poi
{
[ExcludeFromCodeCoverage]
public class Startup
{
public Startup(IConfiguration configuration)
=> Configuration = configuration;
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson((options =>
{
options.SerializerSettings.Formatting = Formatting.Indented;
}));
services.AddHealthChecks()
.AddDbContextCheck<POIContext>()
.AddCheck<Utility.HealthCheck>("poi_health_check");
var connectionString = poi.Utility.POIConfiguration.GetConnectionString(this.Configuration);
services.AddDbContext<POIContext>(options =>
options.UseSqlServer(connectionString));
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("docs", new OpenApiInfo {
Title = "Points Of Interest(POI) API",
Version = "v1",
Description = "API for the POI in the My Driving example app. https://github.com/Azure-Samples/openhack-devops"
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, POIContext dbcontext)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseRewriter(new RewriteOptions().AddRedirect("(.*)api/docs/poi$", "$1api/docs/poi/index.html"));
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(c =>
c.RouteTemplate = "swagger/{documentName}/poi/swagger.json"
);
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/docs/poi/swagger.json", "Points Of Interest(POI) API V1");
c.DocumentTitle = "POI Swagger UI";
c.RoutePrefix = "api/docs/poi";
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("api/healthcheck/poi", new HealthCheckOptions()
{
AllowCachingResponses = false,
ResponseWriter = HealthCheckResponse
});
});
}
private static Task HealthCheckResponse(HttpContext context, HealthReport result)
{
context.Response.ContentType = "application/json";
var json = new JObject(
new JProperty("message", "POI Service Healthcheck"),
new JProperty("status", result.Status.ToString()));
return context.Response.WriteAsync(
json.ToString(Formatting.Indented));
}
}
}

View File

@ -0,0 +1,19 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System.Threading;
using System.Threading.Tasks;
namespace poi.Utility
{
public class HealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
var healthCheckResultHealthy = true; //TODO: implement a proper health check
if (healthCheckResultHealthy)
return Task.FromResult(HealthCheckResult.Healthy("POI is healthy."));
return Task.FromResult(HealthCheckResult.Unhealthy("POI is UNHEALTHY!!!"));
}
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace poi.Utility
{
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class LoggingEvents
{
public const int Healthcheck = 1000;
public const int GetAllPOIs = 2001;
public const int GetPOIByID = 2002;
public const int GetPOIByTripID = 2002;
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace poi.Utility
{
public static class POIConfiguration
{
public static string GetConnectionString(IConfiguration configuration)
{
var SQL_USER = configuration.GetSection("SQL_USER").Value;
var SQL_PASSWORD = configuration.GetSection("SQL_PASSWORD").Value;
var SQL_SERVER = configuration.GetSection("SQL_SERVER").Value;
var SQL_DBNAME = configuration.GetSection("SQL_DBNAME").Value;
var connectionString = configuration["ConnectionStrings:myDrivingDB"];
connectionString = connectionString.Replace("[SQL_USER]", SQL_USER);
connectionString = connectionString.Replace("[SQL_PASSWORD]", SQL_PASSWORD);
connectionString = connectionString.Replace("[SQL_SERVER]", SQL_SERVER);
connectionString = connectionString.Replace("[SQL_DBNAME]", SQL_DBNAME);
return connectionString;
}
public static string GetUri(IConfiguration configuration)
{
var WEB_PORT = configuration.GetValue(typeof(string),"WEB_PORT","8080");
var WEB_SERVER_BASE_URI = configuration.GetValue(typeof(string), "WEB_SERVER_BASE_URI", "http://localhost");
return WEB_SERVER_BASE_URI + ":" + WEB_PORT;
}
}
}

View File

@ -0,0 +1,13 @@
{
"ConnectionStrings": {
"myDrivingDB": "Server=tcp:[SQL_SERVER],1433;Initial Catalog=[SQL_DBNAME];Persist Security Info=False;User ID=[SQL_USER];Password=[SQL_PASSWORD];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@ -0,0 +1,18 @@
{
"ConnectionStrings": {
"myDrivingDB": "Server=tcp:[SQL_SERVER],1433;Initial Catalog=[SQL_DBNAME];Persist Security Info=False;User ID=[SQL_USER];Password=[SQL_PASSWORD];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Information"
}
}
}
}

View File

@ -0,0 +1,18 @@
{
"ConnectionStrings": {
"myDrivingDB": "Server=tcp:[SQL_SERVER],1433;Initial Catalog=[SQL_DBNAME];Persist Security Info=False;User ID=[SQL_USER];Password=[SQL_PASSWORD];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Debug"
}
}
}
}

View File

@ -0,0 +1,5 @@
{
"ConnectionStrings": {
"myDrivingDB": "Server=tcp:[SQL_SERVER],1433;Initial Catalog=[SQL_DBNAME];Persist Security Info=False;User ID=[SQL_USER];Password=[SQL_PASSWORD];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
}

23
apis/poi/web/poi.csproj Normal file
View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Remove="wwwroot\**" />
<Content Remove="wwwroot\**" />
<EmbeddedResource Remove="wwwroot\**" />
<None Remove="wwwroot\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.3" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="3.1.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.4.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.4.1" />
</ItemGroup>
</Project>