Repository: DanWahlin/AspNetCorePostgreSQLDockerApp Branch: master Commit: bd6384d22bd1 Files: 75 Total size: 79.0 KB Directory structure: gitextract_pe7d7h_7/ ├── .gitignore ├── AspNetCorePostgreSQLDockerApp/ │ ├── .docker/ │ │ └── wait-for-postgres.sh │ ├── .dockerignore │ ├── APIs/ │ │ └── CustomersServiceController.cs │ ├── AspNetCorePostgreSQLDockerApp.csproj │ ├── Client/ │ │ ├── .editorconfig │ │ ├── .gitignore │ │ ├── README.md │ │ ├── angular.json │ │ ├── browserslist │ │ ├── e2e/ │ │ │ ├── protractor.conf.js │ │ │ ├── src/ │ │ │ │ ├── app.e2e-spec.ts │ │ │ │ └── app.po.ts │ │ │ └── tsconfig.e2e.json │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app/ │ │ │ │ ├── app-routing.module.ts │ │ │ │ ├── app.component.css │ │ │ │ ├── app.component.html │ │ │ │ ├── app.component.spec.ts │ │ │ │ ├── app.component.ts │ │ │ │ ├── app.module.ts │ │ │ │ ├── core/ │ │ │ │ │ └── data.service.ts │ │ │ │ ├── customers/ │ │ │ │ │ ├── customers.component.html │ │ │ │ │ └── customers.component.ts │ │ │ │ └── shared/ │ │ │ │ └── interfaces.ts │ │ │ ├── assets/ │ │ │ │ └── .gitkeep │ │ │ ├── environments/ │ │ │ │ ├── environment.prod.ts │ │ │ │ └── environment.ts │ │ │ ├── index.html │ │ │ ├── karma.conf.js │ │ │ ├── main.ts │ │ │ ├── polyfills.ts │ │ │ ├── styles.css │ │ │ ├── test.ts │ │ │ ├── tsconfig.app.json │ │ │ ├── tsconfig.spec.json │ │ │ └── tslint.json │ │ ├── tsconfig.json │ │ └── tslint.json │ ├── Controllers/ │ │ ├── CustomersController.cs │ │ └── HomeController.cs │ ├── Models/ │ │ ├── Customer.cs │ │ ├── DockerCommand.cs │ │ ├── DockerCommandExample.cs │ │ ├── Order.cs │ │ └── State.cs │ ├── Program.cs │ ├── Properties/ │ │ └── launchSettings.json │ ├── Repository/ │ │ ├── CustomersDbContext.cs │ │ ├── CustomersDbSeeder.cs │ │ ├── CustomersRepository.cs │ │ ├── DockerCommandsDbContext.cs │ │ ├── DockerCommandsDbSeeder.cs │ │ ├── DockerCommandsRepository.cs │ │ ├── ICustomersRepository.cs │ │ └── IDockerCommandsRepository.cs │ ├── Startup.cs │ ├── Views/ │ │ ├── Customers/ │ │ │ └── Index.cshtml │ │ ├── Home/ │ │ │ └── Index.cshtml │ │ ├── Shared/ │ │ │ ├── Error.cshtml │ │ │ ├── _Layout.cshtml │ │ │ └── _ValidationScriptsPartial.cshtml │ │ ├── _ViewImports.cshtml │ │ └── _ViewStart.cshtml │ ├── appsettings.json │ ├── aspnetcore.dockerfile │ ├── aspnetcore.prod.dockerfile │ ├── docker-compose.azure.yml │ ├── docker-compose.prod.yml │ ├── docker-compose.yml │ └── wwwroot/ │ ├── css/ │ │ └── site.css │ ├── index2.html │ └── web.config ├── AspNetCorePostgreSQLDockerApp.sln └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ #project.json files project.json.old dist .vs #remove generated files **/wwwroot/app/**/*.js **/wwwroot/app/**/*.map #remove node_modules copied into wwwroot **/wwwroot/lib **/wwwroot/libs/* ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. # 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/ build/ bld/ [Bb]in/ [Oo]bj/ # 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 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 # 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 # 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 # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Microsoft Azure ApplicationInsights config file ApplicationInsights.config # Windows Store app package directory AppPackages/ BundleArtifacts/ # 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 *.pfx *.publishsettings node_modules/ orleans.codegen.cs # 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 # FAKE - F# Make .fake/ ================================================ FILE: AspNetCorePostgreSQLDockerApp/.docker/wait-for-postgres.sh ================================================ #!/bin/bash set -e host="$1" shift cmd="$@" until psql -h "$host" -U "postgres" -c '\l'; do >&2 echo "Postgres is unavailable - sleeping" sleep 1 done >&2 echo "Postgres is up - executing command" exec $cmd #Can call from docker-compose.yml by adding the following to dependent service entrypoint: ./.docker/wait-for-postgres.sh postgres:5432 ================================================ FILE: AspNetCorePostgreSQLDockerApp/.dockerignore ================================================ node_modules */node_modules ================================================ FILE: AspNetCorePostgreSQLDockerApp/APIs/CustomersServiceController.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using AspNetCorePostgreSQLDockerApp.Models; using AspNetCorePostgreSQLDockerApp.Repository; using Microsoft.AspNetCore.Http; namespace AspNetCorePostgreSQLDockerApp.Apis { [Route("api/[controller]/customers")] public class CustomersServiceController : Controller { ICustomersRepository _repo; public CustomersServiceController(ICustomersRepository repo) { _repo = repo; } // GET api/dataservice/customers [HttpGet()] [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(List), 404)] public async Task Customers() { var customers = await _repo.GetCustomersAsync(); if (customers == null) { return NotFound(); } return Ok(customers); } // GET api/dataservice/customers/5 [HttpGet("{id}", Name = "GetCustomersRoute")] [ProducesResponseType(typeof(Customer), 200)] [ProducesResponseType(typeof(Customer), 404)] public async Task Customers(int id) { var customer = await _repo.GetCustomerAsync(id); if (customer == null) { return NotFound(); } return Ok(customer); } // POST api/customers [HttpPost()] [ProducesResponseType(typeof(Customer), 201)] [ProducesResponseType(typeof(string), 400)] public async Task PostCustomer([FromBody]Customer customer) { if (!ModelState.IsValid) { return BadRequest(this.ModelState); } var newCustomer = await _repo.InsertCustomerAsync(customer); if (newCustomer == null) { return BadRequest("Unable to insert customer"); } return CreatedAtRoute("GetCustomersRoute", new { id = newCustomer.Id}, newCustomer); } // PUT api/dataservice/customers/5 [HttpPut("{id}")] [ProducesResponseType(typeof(bool), 200)] [ProducesResponseType(typeof(bool), 400)] public async Task PutCustomer(int id, [FromBody]Customer customer) { if (!ModelState.IsValid) { return BadRequest(this.ModelState); } var status = await _repo.UpdateCustomerAsync(customer); if (!status) { return BadRequest("Unable to update customer"); } return Ok(status); } // DELETE api/dataservice/customers/5 [HttpDelete("{id}")] [ProducesResponseType(typeof(bool), 200)] [ProducesResponseType(typeof(bool), 404)] public async Task DeleteCustomer(int id) { var status = await _repo.DeleteCustomerAsync(id); if (!status) { return NotFound(); } return Ok(status); } [HttpGet("states")] [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(List), 404)] public async Task States() { var states = await _repo.GetStatesAsync(); if (states == null) { return NotFound(); } return Ok(states); } } public static class HttpRequestExtensions { public static Uri ToUri(this HttpRequest request) { var hostComponents = request.Host.ToUriComponent().Split(':'); var builder = new UriBuilder { Scheme = request.Scheme, Host = hostComponents[0], Path = request.Path, Query = request.QueryString.ToUriComponent() }; if (hostComponents.Length == 2) { builder.Port = Convert.ToInt32(hostComponents[1]); } return builder.Uri; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/AspNetCorePostgreSQLDockerApp.csproj ================================================  netcoreapp3.1 ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/.editorconfig ================================================ # Editor configuration, see http://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [*.md] max_line_length = off trim_trailing_whitespace = false ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/.gitignore ================================================ # See http://help.github.com/ignore-files/ for more about ignoring files. # compiled output /dist /tmp /out-tsc # dependencies /node_modules # IDEs and editors /.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json # misc /.sass-cache /connect.lock /coverage /libpeerconnection.log npm-debug.log yarn-error.log testem.log /typings # System Files .DS_Store Thumbs.db ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/README.md ================================================ # CustomersApp This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.4. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/angular.json ================================================ { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "customers-app": { "root": "", "sourceRoot": "src", "projectType": "application", "prefix": "app", "schematics": {}, "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "aot": true, "outputPath": "../wwwroot/dist", "deleteOutputPath": false, "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "src/tsconfig.app.json", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.css" ], "scripts": [] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "6kb" } ] } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "customers-app:build" }, "configurations": { "production": { "browserTarget": "customers-app:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "customers-app:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "src/tsconfig.spec.json", "karmaConfig": "src/karma.conf.js", "styles": [ "src/styles.css" ], "scripts": [], "assets": [ "src/favicon.ico", "src/assets" ] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "src/tsconfig.app.json", "src/tsconfig.spec.json" ], "exclude": [ "**/node_modules/**" ] } } } }, "customers-app-e2e": { "root": "e2e/", "projectType": "application", "prefix": "", "architect": { "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "customers-app:serve" }, "configurations": { "production": { "devServerTarget": "customers-app:serve:production" } } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": "e2e/tsconfig.e2e.json", "exclude": [ "**/node_modules/**" ] } } } } }, "defaultProject": "customers-app" } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/browserslist ================================================ # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers # For additional information regarding the format and rule options, please see: # https://github.com/browserslist/browserslist#queries # # For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed > 0.5% last 2 versions Firefox ESR not dead not IE 9-11 ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/e2e/protractor.conf.js ================================================ // Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter } = require('jasmine-spec-reporter'); exports.config = { allScriptsTimeout: 11000, specs: [ './src/**/*.e2e-spec.ts' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.e2e.json') }); jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); } }; ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/e2e/src/app.e2e-spec.ts ================================================ import { AppPage } from './app.po'; describe('workspace-project App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Welcome to customers-app!'); }); }); ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/e2e/src/app.po.ts ================================================ import { browser, by, element } from 'protractor'; export class AppPage { navigateTo() { return browser.get('/'); } getParagraphText() { return element(by.css('app-root h1')).getText(); } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/e2e/tsconfig.e2e.json ================================================ { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/app", "module": "commonjs", "target": "es5", "types": [ "jasmine", "jasminewd2", "node" ] } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/package.json ================================================ { "name": "customers-app", "version": "1.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "~9.0.6", "@angular/common": "~9.0.6", "@angular/compiler": "~9.0.6", "@angular/core": "~11.0.5", "@angular/forms": "~9.0.6", "@angular/platform-browser": "~9.0.6", "@angular/platform-browser-dynamic": "~9.0.6", "@angular/router": "~9.0.6", "core-js": "^2.5.4", "rxjs": "~6.5.4", "tslib": "^1.10.0", "zone.js": "~0.10.2" }, "devDependencies": { "@angular-devkit/build-angular": "~0.900.6", "@angular/cli": "~9.0.6", "@angular/compiler-cli": "~9.0.6", "@angular/language-service": "~9.0.6", "@types/node": "^12.11.1", "@types/jasmine": "~3.3.8", "@types/jasminewd2": "~2.0.3", "codelyzer": "^5.1.2", "jasmine-core": "~3.4.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~6.3.16", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~2.0.1", "karma-jasmine": "~2.0.1", "karma-jasmine-html-reporter": "^1.4.0", "protractor": "~5.4.4", "ts-node": "~7.0.0", "tslint": "~5.15.0", "typescript": "~3.7.5" } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/app-routing.module.ts ================================================ import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CustomersComponent } from './customers/customers.component'; const routes: Routes = [ { path: '', pathMatch:'full', redirectTo: '/customers' }, { path: 'customers', component: CustomersComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/app.component.css ================================================ ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/app.component.html ================================================ ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/app.component.spec.ts ================================================ import { TestBed, async } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it(`should have as title 'customers-app'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('customers-app'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('Welcome to customers-app!'); }); }); ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/app.component.ts ================================================ import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'customers-app'; } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/app.module.ts ================================================ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CustomersComponent } from './customers/customers.component'; @NgModule({ declarations: [ AppComponent, CustomersComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/core/data.service.ts ================================================ import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map, catchError } from 'rxjs/operators'; import { ICustomer } from '../shared/interfaces'; @Injectable({ providedIn: 'root' }) export class DataService { private url: string = 'api/customersservice/customers/'; constructor(private http: HttpClient) { } getCustomersSummary() : Observable { return this.http.get(this.url) .pipe( catchError(this.handleError) ); } updateCustomer(customer: ICustomer) { return this.http.put(this.url + customer.id, customer) .pipe( catchError(this.handleError) ); } handleError(error: any) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/customers/customers.component.html ================================================

Customers


Name
Email
Address
City
{{ customer.firstName }} {{ customer.lastName }}
{{ customer.email }}
{{ customer.address }}
{{ customer.city }}

{{ customer.firstName }} {{ customer.lastName }}
Edit

{{ customer.firstName }} {{ customer.lastName }}


First Name is required
Last Name is required
Email is required
City is required
Address is required
  Cancel

{{ errorMessage }}
================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/customers/customers.component.ts ================================================ import { Component, OnInit } from '@angular/core'; import { DataService } from '../core/data.service'; import { ICustomer } from '../shared/interfaces'; @Component({ selector: 'app-customers', templateUrl: 'customers.component.html' }) export class CustomersComponent implements OnInit { customers: ICustomer[] = []; editId: number = 0; errorMessage: string; editViewEnabled = false; constructor(private dataService: DataService) { } ngOnInit() { this.dataService.getCustomersSummary() .subscribe((data: ICustomer[]) => this.customers = data); } save(customer: ICustomer) { this.dataService.updateCustomer(customer) .subscribe((status: boolean) => { if (status) { this.editId = 0; } else { this.errorMessage = 'Unable to save customer'; } }) } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/app/shared/interfaces.ts ================================================ export interface ICustomer { id: number; firstName: string; lastName: string; email: string; address: string; city: string; state: IState; zip: number; gender: string; latitude: number; longitude: number; orderCount?: number; orders?: IOrder[]; ordersTotal?: number; } export interface IState { abbreviation: string; name: string; } export interface IOrder { product: string; price: number; quantity: number; orderTotal?: number; } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/assets/.gitkeep ================================================ ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/environments/environment.prod.ts ================================================ export const environment = { production: true }; ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/environments/environment.ts ================================================ // This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI. ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/index.html ================================================ CustomersApp ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/karma.conf.js ================================================ // Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, '../coverage'), reports: ['html', 'lcovonly'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); }; ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/main.ts ================================================ import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/polyfills.ts ================================================ /** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in https://angular.io/guide/browser-support */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** IE10 and IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). */ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /** * By default, zone.js will patch all possible macroTask and DomEvents * user can disable parts of macroTask/DomEvents patch by setting following flags * because those flags need to be set before `zone.js` being loaded, and webpack * will put import in the top of bundle, so user need to create a separate file * in this directory (for example: zone-flags.ts), and put the following flags * into that file, and then add the following code before importing zone.js. * import './zone-flags.ts'; * * The flags allowed in zone-flags.ts are listed here. * * The following flags will work for all browsers. * * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames * * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js * with the following flag, it will bypass `zone.js` patch for IE/Edge * * (window as any).__Zone_enable_cross_context_check = true; * */ /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */ ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/styles.css ================================================ /* You can add global styles to this file, and also import other style files */ ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/test.ts ================================================ // This file is required by karma.conf.js and loads recursively all the .spec and framework files import 'zone.js/dist/zone-testing'; import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; declare const require: any; // First, initialize the Angular testing environment. getTestBed().initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting() ); // Then we find all the tests. const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. context.keys().map(context); ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/tsconfig.app.json ================================================ { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/app", "types": [] }, "files": [ "main.ts", "polyfills.ts" ], "include": [ "src/**/*.d.ts" ] } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/tsconfig.spec.json ================================================ { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/spec", "types": [ "jasmine", "node" ] }, "files": [ "test.ts", "polyfills.ts" ], "include": [ "**/*.spec.ts", "**/*.d.ts" ] } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/src/tslint.json ================================================ { "extends": "../tslint.json", "rules": { "directive-selector": [ true, "attribute", "app", "camelCase" ], "component-selector": [ true, "element", "app", "kebab-case" ] } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/tsconfig.json ================================================ { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "downlevelIteration": true, "importHelpers": true, "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "module": "esnext", "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es2015", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2018", "dom" ] } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Client/tslint.json ================================================ { "rulesDirectory": [ "node_modules/codelyzer" ], "rules": { "arrow-return-shorthand": true, "callable-types": true, "class-name": true, "comment-format": [ true, "check-space" ], "curly": true, "deprecation": { "severity": "warn" }, "eofline": true, "forin": true, "import-blacklist": [ true, "rxjs/Rx" ], "import-spacing": true, "indent": [ true, "spaces" ], "interface-over-type-literal": true, "label-position": true, "max-line-length": [ true, 140 ], "member-access": false, "member-ordering": [ true, { "order": [ "static-field", "instance-field", "static-method", "instance-method" ] } ], "no-arg": true, "no-bitwise": true, "no-console": [ true, "debug", "info", "time", "timeEnd", "trace" ], "no-construct": true, "no-debugger": true, "no-duplicate-super": true, "no-empty": false, "no-empty-interface": true, "no-eval": true, "no-inferrable-types": [ true, "ignore-params" ], "no-misused-new": true, "no-non-null-assertion": true, "no-redundant-jsdoc": true, "no-shadowed-variable": true, "no-string-literal": false, "no-string-throw": true, "no-switch-case-fall-through": true, "no-trailing-whitespace": true, "no-unnecessary-initializer": true, "no-unused-expression": true, "no-use-before-declare": true, "no-var-keyword": true, "object-literal-sort-keys": false, "one-line": [ true, "check-open-brace", "check-catch", "check-else", "check-whitespace" ], "prefer-const": true, "quotemark": [ true, "single" ], "radix": true, "semicolon": [ true, "always" ], "triple-equals": [ true, "allow-null-check" ], "typedef-whitespace": [ true, { "call-signature": "nospace", "index-signature": "nospace", "parameter": "nospace", "property-declaration": "nospace", "variable-declaration": "nospace" } ], "unified-signatures": true, "variable-name": false, "whitespace": [ true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type" ], "no-output-on-prefix": true, "no-inputs-metadata-property": true, "no-outputs-metadata-property": true, "no-host-metadata-property": true, "no-input-rename": true, "no-output-rename": true, "use-lifecycle-interface": true, "use-pipe-transform-interface": true, "component-class-suffix": true, "directive-class-suffix": true } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Controllers/CustomersController.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace AspNetCorePostgreSQLDockerApp.Controllers { public class CustomersController : Controller { public ActionResult Index() { return View(); } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Controllers/HomeController.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using AspNetCorePostgreSQLDockerApp.Repository; namespace AspNetCorePostgreSQLDockerApp.Controllers { public class HomeController : Controller { IDockerCommandsRepository _repo; public HomeController(IDockerCommandsRepository repo) { _repo = repo; } public async Task Index() { //Call into PostgreSQL var commands = await _repo.GetDockerCommandsAsync(); return View(commands); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } // public IActionResult Error() // { // return View(); // } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Models/Customer.cs ================================================ using System.Collections.Generic; namespace AspNetCorePostgreSQLDockerApp.Models { public class Customer { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Address { get; set; } public string City { get; set; } public State State { get; set; } public int Zip { get; set; } public string Gender { get; set; } public int OrderCount { get; set; } public List Orders { get; set; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Models/DockerCommand.cs ================================================ using System; using System.Collections.Generic; namespace AspNetCorePostgreSQLDockerApp.Models { public class DockerCommand { public int Id { get; set; } public string Command { get; set; } public string Description { get; set; } public List Examples { get; set; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Models/DockerCommandExample.cs ================================================ using System; namespace AspNetCorePostgreSQLDockerApp.Models { public class DockerCommandExample { public int Id { get; set; } public string Example { get; set; } public string Description { get; set; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Models/Order.cs ================================================ namespace AspNetCorePostgreSQLDockerApp.Models { public class Order { public int Id { get; set; } public string Product { get; set; } public int Quantity { get; set; } public decimal Price { get; set; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Models/State.cs ================================================ namespace AspNetCorePostgreSQLDockerApp.Models { public class State { public int Id { get; set; } public string Abbreviation { get; set; } public string Name { get; set; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Program.cs ================================================ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace AspNetCorePostgreSQLDockerApp { 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(); }); } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Properties/launchSettings.json ================================================ { "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:50389/", "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "AspNetCorePostgreSQLDockerApp": { "commandName": "Project", "launchBrowser": true, "launchUrl": "http://0.0.0.0:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Repository/CustomersDbContext.cs ================================================ using Microsoft.EntityFrameworkCore; using AspNetCorePostgreSQLDockerApp.Models; namespace AspNetCorePostgreSQLDockerApp.Repository { public class CustomersDbContext : DbContext { public DbSet Customers { get; set; } public DbSet Orders { get; set; } public DbSet States { get; set; } public CustomersDbContext (DbContextOptions options) : base(options) { } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Repository/CustomersDbSeeder.cs ================================================ using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using AspNetCorePostgreSQLDockerApp.Models; namespace AspNetCorePostgreSQLDockerApp.Repository { public class CustomersDbSeeder { readonly ILogger _logger; public CustomersDbSeeder(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger("CustomersDbSeederLogger"); } public async Task SeedAsync(IServiceProvider serviceProvider) { //Based on EF team's example at https://github.com/aspnet/MusicStore/blob/dev/samples/MusicStore/Models/SampleData.cs using (var serviceScope = serviceProvider.GetRequiredService().CreateScope()) { var customersDb = serviceScope.ServiceProvider.GetService(); if (await customersDb.Database.EnsureCreatedAsync()) { if (!await customersDb.Customers.AnyAsync()) { await InsertCustomersSampleData(customersDb); } } } } public async Task InsertCustomersSampleData(CustomersDbContext db) { var states = GetStates(); db.States.AddRange(states); try { await db.SaveChangesAsync(); } catch (Exception exp) { _logger.LogError($"Error in {nameof(CustomersDbSeeder)}: " + exp.Message); throw; } var customers = GetCustomers(states); db.Customers.AddRange(customers); try { await db.SaveChangesAsync(); } catch (Exception exp) { _logger.LogError($"Error in {nameof(CustomersDbSeeder)}: " + exp.Message); throw; } } private List GetCustomers(List states) { //Customers var customerNames = new string[] { "Marcus,HighTower,Male,acmecorp.com", "Jesse,Smith,Female,gmail.com", "Albert,Einstein,Male,outlook.com", "Dan,Wahlin,Male,yahoo.com", "Ward,Bell,Male,gmail.com", "Brad,Green,Male,gmail.com", "Igor,Minar,Male,gmail.com", "Miško,Hevery,Male,gmail.com", "Michelle,Avery,Female,acmecorp.com", "Heedy,Wahlin,Female,hotmail.com", "Thomas,Martin,Male,outlook.com", "Jean,Martin,Female,outlook.com", "Robin,Cleark,Female,acmecorp.com", "Juan,Paulo,Male,yahoo.com", "Gene,Thomas,Male,gmail.com", "Pinal,Dave,Male,gmail.com", "Fred,Roberts,Male,outlook.com", "Tina,Roberts,Female,outlook.com", "Cindy,Jamison,Female,gmail.com", "Robyn,Flores,Female,yahoo.com", "Jeff,Wahlin,Male,gmail.com", "Danny,Wahlin,Male,gmail.com", "Elaine,Jones,Female,yahoo.com", "John,Papa,Male,gmail.com" }; var addresses = new string[] { "1234 Anywhere St.", "435 Main St.", "1 Atomic St.", "85 Cedar Dr.", "12 Ocean View St.", "1600 Amphitheatre Parkway", "1604 Amphitheatre Parkway", "1607 Amphitheatre Parkway", "346 Cedar Ave.", "4576 Main St.", "964 Point St.", "98756 Center St.", "35632 Richmond Circle Apt B", "2352 Angular Way", "23566 Directive Pl.", "235235 Yaz Blvd.", "7656 Crescent St.", "76543 Moon Ave.", "84533 Hardrock St.", "5687534 Jefferson Way", "346346 Blue Pl.", "23423 Adams St.", "633 Main St.", "899 Mickey Way" }; var citiesStates = new string[] { "Phoenix,AZ,Arizona", "Encinitas,CA,California", "Seattle,WA,Washington", "Chandler,AZ,Arizona", "Dallas,TX,Texas", "Orlando,FL,Florida", "Carey,NC,North Carolina", "Anaheim,CA,California", "Dallas,TX,Texas", "New York,NY,New York", "White Plains,NY,New York", "Las Vegas,NV,Nevada", "Los Angeles,CA,California", "Portland,OR,Oregon", "Seattle,WA,Washington", "Houston,TX,Texas", "Chicago,IL,Illinois", "Atlanta,GA,Georgia", "Chandler,AZ,Arizona", "Buffalo,NY,New York", "Albuquerque,AZ,Arizona", "Boise,ID,Idaho", "Salt Lake City,UT,Utah", "Orlando,FL,Florida" }; var citiesIds = new int[] {5, 9, 44, 5, 36, 17, 16, 9, 36, 14, 14, 6, 9, 24, 44, 36, 25, 19, 5, 14, 5, 23, 38, 17}; var zip = 85229; var orders = new List { new Order { Product = "Basket", Price = 29.99M, Quantity = 1 }, new Order { Product = "Yarn", Price = 9.99M, Quantity = 1 }, new Order { Product = "Needes", Price = 5.99M, Quantity = 1 }, new Order { Product = "Speakers", Price = 499.99M, Quantity = 1 }, new Order { Product = "iPod", Price = 399.99M, Quantity = 1 }, new Order { Product = "Table", Price = 329.99M, Quantity = 1 }, new Order { Product = "Chair", Price = 129.99M, Quantity = 4 }, new Order { Product = "Lamp", Price = 89.99M, Quantity = 5 }, new Order { Product = "Call of Duty", Price = 59.99M, Quantity = 1 }, new Order { Product = "Controller", Price = 49.99M, Quantity = 1 }, new Order { Product = "Gears of War", Price = 49.99M, Quantity = 1 }, new Order { Product = "Lego City", Price = 49.99M, Quantity = 1 }, new Order { Product = "Baseball", Price = 9.99M, Quantity = 5 }, new Order { Product = "Bat", Price = 19.99M, Quantity = 1 } }; int firstOrder, lastOrder, tempOrder = 0; var ordersLength = orders.Count; var customers = new List(); var random = new Random(); for (var i = 0; i < customerNames.Length; i++) { var nameGenderHost = customerNames[i].Split(','); var cityState = citiesStates[i].Split(','); var state = states.Where(s => s.Abbreviation == cityState[1]).SingleOrDefault(); var customer = new Customer { FirstName = nameGenderHost[0], LastName = nameGenderHost[1], Email = nameGenderHost[0] + '.' + nameGenderHost[1] + '@' + nameGenderHost[3], Address = addresses[i], City = cityState[0], State = state, Zip = zip + i, Gender = nameGenderHost[2], OrderCount = 0 }; firstOrder = (int)Math.Floor(random.NextDouble() * orders.Count); lastOrder = (int)Math.Floor(random.NextDouble() * orders.Count); if (firstOrder > lastOrder) { tempOrder = firstOrder; firstOrder = lastOrder; lastOrder = tempOrder; } customer.Orders = new List(); for (var j = firstOrder; j <= lastOrder && j < ordersLength; j++) { var order = new Order { Product = orders[j].Product, Price = orders[j].Price, Quantity = orders[j].Quantity }; customer.Orders.Add(order); } customer.OrderCount = customer.Orders.Count; customers.Add(customer); } return customers; } private List GetStates() { var states = new List { new State { Name = "Alabama", Abbreviation = "AL" }, new State { Name = "Montana", Abbreviation = "MT" }, new State { Name = "Alaska", Abbreviation = "AK" }, new State { Name = "Nebraska", Abbreviation = "NE" }, new State { Name = "Arizona", Abbreviation = "AZ" }, new State { Name = "Nevada", Abbreviation = "NV" }, new State { Name = "Arkansas", Abbreviation = "AR" }, new State { Name = "New Hampshire", Abbreviation = "NH" }, new State { Name = "California", Abbreviation = "CA" }, new State { Name = "New Jersey", Abbreviation = "NJ" }, new State { Name = "Colorado", Abbreviation = "CO" }, new State { Name = "New Mexico", Abbreviation = "NM" }, new State { Name = "Connecticut", Abbreviation = "CT" }, new State { Name = "New York", Abbreviation = "NY" }, new State { Name = "Delaware", Abbreviation = "DE" }, new State { Name = "North Carolina", Abbreviation = "NC" }, new State { Name = "Florida", Abbreviation = "FL" }, new State { Name = "North Dakota", Abbreviation = "ND" }, new State { Name = "Georgia", Abbreviation = "GA" }, new State { Name = "Ohio", Abbreviation = "OH" }, new State { Name = "Hawaii", Abbreviation = "HI" }, new State { Name = "Oklahoma", Abbreviation = "OK" }, new State { Name = "Idaho", Abbreviation = "ID" }, new State { Name = "Oregon", Abbreviation = "OR" }, new State { Name = "Illinois", Abbreviation = "IL" }, new State { Name = "Pennsylvania", Abbreviation = "PA" }, new State { Name = "Indiana", Abbreviation = "IN" }, new State { Name = "Rhode Island", Abbreviation = "RI" }, new State { Name = "Iowa", Abbreviation = "IA" }, new State { Name = "South Carolina", Abbreviation = "SC" }, new State { Name = "Kansas", Abbreviation = "KS" }, new State { Name = "South Dakota", Abbreviation = "SD" }, new State { Name = "Kentucky", Abbreviation = "KY" }, new State { Name = "Tennessee", Abbreviation = "TN" }, new State { Name = "Louisiana", Abbreviation = "LA" }, new State { Name = "Texas", Abbreviation = "TX" }, new State { Name = "Maine", Abbreviation = "ME" }, new State { Name = "Utah", Abbreviation = "UT" }, new State { Name = "Maryland", Abbreviation = "MD" }, new State { Name = "Vermont", Abbreviation = "VT" }, new State { Name = "Massachusetts", Abbreviation = "MA" }, new State { Name = "Virginia", Abbreviation = "VA" }, new State { Name = "Michigan", Abbreviation = "MI" }, new State { Name = "Washington", Abbreviation = "WA" }, new State { Name = "Minnesota", Abbreviation = "MN" }, new State { Name = "West Virginia", Abbreviation = "WV" }, new State { Name = "Mississippi", Abbreviation = "MS" }, new State { Name = "Wisconsin", Abbreviation = "WI" }, new State { Name = "Missouri", Abbreviation = "MO" }, new State { Name = "Wyoming", Abbreviation = "WY" } }; return states; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Repository/CustomersRepository.cs ================================================ using System; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using AspNetCorePostgreSQLDockerApp.Models; namespace AspNetCorePostgreSQLDockerApp.Repository { public class CustomersRepository : ICustomersRepository { private readonly CustomersDbContext _context; private readonly ILogger _logger; public CustomersRepository(CustomersDbContext context, ILoggerFactory loggerFactory) { _context = context; _logger = loggerFactory.CreateLogger("CustomersRepository"); } public async Task> GetCustomersAsync() { return await _context.Customers.OrderBy(c => c.LastName).ToListAsync(); } public async Task GetCustomerAsync(int id) { return await _context.Customers.SingleOrDefaultAsync(c => c.Id == id); } public async Task> GetStatesAsync() { return await _context.States.OrderBy(s => s.Abbreviation).ToListAsync(); } public async Task InsertCustomerAsync(Customer customer) { _context.Add(customer); try { await _context.SaveChangesAsync(); } catch (System.Exception exp) { _logger.LogError($"Error in {nameof(InsertCustomerAsync)}: " + exp.Message); } return customer; } public async Task UpdateCustomerAsync(Customer customer) { //Will update all properties of the Customer _context.Customers.Attach(customer); _context.Entry(customer).State = EntityState.Modified; try { return (await _context.SaveChangesAsync() > 0 ? true : false); } catch (Exception exp) { _logger.LogError($"Error in {nameof(UpdateCustomerAsync)}: " + exp.Message); } return false; } public async Task DeleteCustomerAsync(int id) { //Extra hop to the database but keeps it nice and simple for this demo var customer = await _context.Customers.SingleOrDefaultAsync(c => c.Id == id); _context.Remove(customer); try { return (await _context.SaveChangesAsync() > 0 ? true : false); } catch (System.Exception exp) { _logger.LogError($"Error in {nameof(DeleteCustomerAsync)}: " + exp.Message); } return false; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Repository/DockerCommandsDbContext.cs ================================================ using Microsoft.EntityFrameworkCore; using AspNetCorePostgreSQLDockerApp.Models; namespace AspNetCorePostgreSQLDockerApp.Repository { public class DockerCommandsDbContext : DbContext { public DbSet DockerCommands { get; set; } public DockerCommandsDbContext(DbContextOptions options) : base(options) { } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Repository/DockerCommandsDbSeeder.cs ================================================ using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using AspNetCorePostgreSQLDockerApp.Models; namespace AspNetCorePostgreSQLDockerApp.Repository { public class DockerCommandsDbSeeder { readonly ILogger _logger; public DockerCommandsDbSeeder(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger("DockerCommandsDbSeederLogger"); } public async Task SeedAsync(IServiceProvider serviceProvider) { //Based on EF team's example at https://github.com/aspnet/MusicStore/blob/dev/samples/MusicStore/Models/SampleData.cs using (var serviceScope = serviceProvider.GetRequiredService().CreateScope()) { var dockerDb = serviceScope.ServiceProvider.GetService(); var customersDb = serviceScope.ServiceProvider.GetService(); if (await dockerDb.Database.EnsureCreatedAsync()) { if (!await dockerDb.DockerCommands.AnyAsync()) { await InsertDockerSampleData(dockerDb); } } } } public async Task InsertDockerSampleData(DockerCommandsDbContext db) { var commands = GetDockerCommands(); db.DockerCommands.AddRange(commands); try { await db.SaveChangesAsync(); } catch (Exception exp) { _logger.LogError($"Error in {nameof(DockerCommandsDbSeeder)}: " + exp.Message); } } private List GetDockerCommands() { var cmd1 = new DockerCommand { Command = "run", Description = "Runs a Docker container", Examples = new List { new DockerCommandExample { Example = "docker run imageName", Description = "Creates a running container from the image. Pulls it from Docker Hub if the image is not local" }, new DockerCommandExample { Example = "docker run -d -p 8080:3000 imageName", Description = "Runs a container in 'daemon' mode with an external port of 8080 and a container port of 3000." } } }; var cmd2 = new DockerCommand { Command = "ps", Description = "Lists containers", Examples = new List { new DockerCommandExample { Example = "docker ps", Description = "Lists all running containers" }, new DockerCommandExample { Example = "docker ps -a", Description = "Lists all containers (even if they are not running)" } } }; return new List { cmd1, cmd2 }; } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Repository/DockerCommandsRepository.cs ================================================ using System; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using AspNetCorePostgreSQLDockerApp.Models; namespace AspNetCorePostgreSQLDockerApp.Repository { public class DockerCommandsRepository : IDockerCommandsRepository { private readonly DockerCommandsDbContext _context; private readonly ILogger _logger; public DockerCommandsRepository(DockerCommandsDbContext context, ILoggerFactory loggerFactory) { _context = context; _logger = loggerFactory.CreateLogger("DockerCommandsRepository"); } public async Task> GetDockerCommandsAsync() { return await _context.DockerCommands.Include(dc => dc.Examples).ToListAsync(); } public async Task InsertDockerCommandAsync(DockerCommand command) { _context.DockerCommands.Add(command); try { await _context.SaveChangesAsync(); } catch (Exception exp) { _logger.LogError($"Error in {nameof(InsertDockerCommandAsync)}: " + exp.Message); } } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Repository/ICustomersRepository.cs ================================================ using System.Collections.Generic; using System.Threading.Tasks; using AspNetCorePostgreSQLDockerApp.Models; namespace AspNetCorePostgreSQLDockerApp.Repository { public interface ICustomersRepository { Task> GetCustomersAsync(); Task GetCustomerAsync(int id); Task InsertCustomerAsync(Customer customer); Task UpdateCustomerAsync(Customer customer); Task DeleteCustomerAsync(int id); Task> GetStatesAsync(); } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Repository/IDockerCommandsRepository.cs ================================================ using System.Collections.Generic; using System.Threading.Tasks; using AspNetCorePostgreSQLDockerApp.Models; namespace AspNetCorePostgreSQLDockerApp.Repository { public interface IDockerCommandsRepository { Task> GetDockerCommandsAsync(); Task InsertDockerCommandAsync(DockerCommand command); } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Startup.cs ================================================ using System; using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.FileProviders; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.OpenApi.Models; using AspNetCorePostgreSQLDockerApp.Repository; namespace AspNetCorePostgreSQLDockerApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Add PostgreSQL support services.AddEntityFrameworkNpgsql() .AddDbContext(options => options.UseNpgsql(Configuration["Data:DbContext:DockerCommandsConnectionString"])) .AddDbContext(options => options.UseNpgsql(Configuration["Data:DbContext:CustomersConnectionString"])); services.AddControllersWithViews(); // Add our PostgreSQL Repositories (scoped to each request) services.AddScoped(); services.AddScoped(); //Transient: Created each time they're needed services.AddTransient(); services.AddTransient(); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "Application API", Description = "Application Documentation", Contact = new OpenApiContact { Name = "Author" }, License = new OpenApiLicense { Name = "MIT", Url = new Uri("https://en.wikipedia.org/wiki/MIT_License") } }); // Add XML comment document by uncommenting the following // var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "MyApi.xml"); // options.IncludeXmlComments(filePath); }); services.AddCors(o => o.AddPolicy("AllowAllPolicy", options => { options.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "dist"; }); // services.AddRouting(options => options.LowercaseUrls = true); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DockerCommandsDbSeeder dockerCommandsDbSeeder, CustomersDbSeeder customersDbSeeder) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseCors("AllowAllPolicy"); app.UseStaticFiles(); app.UseSpaStaticFiles(); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) // Visit http://localhost:5000/swagger app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action}/{id?}"); // Handle redirecting client-side routes to Customers/Index route endpoints.MapFallbackToController("Index", "Customers"); }); customersDbSeeder.SeedAsync(app.ApplicationServices).Wait(); dockerCommandsDbSeeder.SeedAsync(app.ApplicationServices).Wait(); } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/Views/Customers/Index.cshtml ================================================
Loading...

================================================ FILE: AspNetCorePostgreSQLDockerApp/Views/Home/Index.cshtml ================================================ @model List @{ ViewData["Title"] = "Home Page"; }

Docker Commands

From the Docker for Web Developers course on Pluralsight.

@foreach (var dockerCommand in Model) {

@dockerCommand.Command Command

@dockerCommand.Description
@foreach (var commandExample in dockerCommand.Examples) {

@commandExample.Example

@commandExample.Description
}
} ================================================ FILE: AspNetCorePostgreSQLDockerApp/Views/Shared/Error.cshtml ================================================ @{ ViewData["Title"] = "Error"; }

Error.

An error occurred while processing your request.

================================================ FILE: AspNetCorePostgreSQLDockerApp/Views/Shared/_Layout.cshtml ================================================ @ViewData["Title"] - Asp.Net Core PostgreSQL Docker/Angular App
@RenderBody()

© 2020 - Wahlin Consulting

@RenderSection("scripts", required: false) ================================================ FILE: AspNetCorePostgreSQLDockerApp/Views/Shared/_ValidationScriptsPartial.cshtml ================================================ ================================================ FILE: AspNetCorePostgreSQLDockerApp/Views/_ViewImports.cshtml ================================================ @using AspNetCorePostgreSQLDockerApp @using AspNetCorePostgreSQLDockerApp.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ================================================ FILE: AspNetCorePostgreSQLDockerApp/Views/_ViewStart.cshtml ================================================ @{ Layout = "_Layout"; } ================================================ FILE: AspNetCorePostgreSQLDockerApp/appsettings.json ================================================ { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } }, "Data": { "DbContext": { "LocalConnectionString": "User ID=;Password=;Server=127.0.0.1;Port=5432;Database=;Pooling=true;", "ConnectionString": "User ID=postgres;Password=password;Server=postgres;Port=5432;Database=POSTGRES_USER;Integrated Security=true;Pooling=true;", "DockerCommandsConnectionString": "User ID=postgres;Password=password;Server=postgres;Port=5432;Database=DockerCommands;Integrated Security=true;Pooling=true;", "CustomersConnectionString": "User ID=postgres;Password=password;Server=postgres;Port=5432;Database=Customers;Integrated Security=true;Pooling=true;" } } } ================================================ FILE: AspNetCorePostgreSQLDockerApp/aspnetcore.dockerfile ================================================ FROM mcr.microsoft.com/dotnet/core/sdk LABEL author="Dan Wahlin" ENV ASPNETCORE_URLS=http://+:5000 WORKDIR /var/www/aspnetcoreapp COPY . . EXPOSE 5000 ENTRYPOINT ["/bin/bash", "-c", "dotnet restore && dotnet run"] # Note that this is only for demo and is intended to keep things simple. # A multi-stage dockerfile would normally be used here to build the .dll and use # the mcr.microsoft.com/dotnet/core/aspnet image for the final image # Legacy linking commands. While these work, they aren't the preferred way now. # Instead, use networks (see the docker-compose.yml file for an example). # docker build -f aspnetcore.dockerfile -t danwahlin/aspnetcore . # docker run -d --name my-postgres -e POSTGRES_PASSWORD=password postgres # docker run -d -p 5000:5000 --link my-postgres:postgres danwahlin/aspnetcore ================================================ FILE: AspNetCorePostgreSQLDockerApp/aspnetcore.prod.dockerfile ================================================ FROM mcr.microsoft.com/dotnet/core/sdk AS build WORKDIR /var/www/aspnetcoreapp # copy csproj and restore as distinct layers COPY ./*.csproj ./ RUN dotnet restore # copy everything else and build app COPY ./ ./ RUN dotnet publish -c Release -o out FROM mcr.microsoft.com/dotnet/core/aspnet ENV ASPNETCORE_URLS=http://+:5000 WORKDIR /var/www/aspnetcoreapp COPY --from=build /var/www/aspnetcoreapp/out ./ ENTRYPOINT ["dotnet", "AspNetCorePostgreSQLDockerApp.dll"] ================================================ FILE: AspNetCorePostgreSQLDockerApp/docker-compose.azure.yml ================================================ version: '3.7' services: web: container_name: 'aspnetcoreapp' # would need to tag aspnetcoreapp image as shown below to run # used to setup a Web App for Containers example # https://docs.microsoft.com/en-us/azure/app-service/containers/quickstart-multi-container image: 'danwahlin/aspnetcoreapp' ports: - "80:5000" depends_on: - "postgres" networks: - aspnetcoreapp-network postgres: container_name: 'postgres' image: postgres environment: # change this for a "real" app! POSTGRES_PASSWORD: password networks: - aspnetcoreapp-network networks: aspnetcoreapp-network: driver: bridge ================================================ FILE: AspNetCorePostgreSQLDockerApp/docker-compose.prod.yml ================================================ version: '3.7' services: web: container_name: 'aspnetcoreapp' image: 'aspnetcoreapp' build: context: . dockerfile: aspnetcore.prod.dockerfile ports: - "5000:5000" depends_on: - "postgres" networks: - aspnetcoreapp-network postgres: container_name: 'postgres' image: postgres environment: # change this for a "real" app! POSTGRES_PASSWORD: password networks: - aspnetcoreapp-network networks: aspnetcoreapp-network: driver: bridge ================================================ FILE: AspNetCorePostgreSQLDockerApp/docker-compose.yml ================================================ version: '3.7' services: web: container_name: 'aspnetcoreapp' image: 'aspnetcoreapp' build: context: . dockerfile: aspnetcore.dockerfile ports: - "5000:5000" depends_on: - "postgres" networks: - aspnetcoreapp-network postgres: container_name: 'postgres' image: postgres environment: # change this for a "real" app! POSTGRES_PASSWORD: password networks: - aspnetcoreapp-network networks: aspnetcoreapp-network: driver: bridge ================================================ FILE: AspNetCorePostgreSQLDockerApp/wwwroot/css/site.css ================================================ body { padding-top: 50px; padding-bottom: 20px; } /* Wrapping element */ /* Set some basic padding to keep content from hitting the edges */ .body-content { padding-left: 15px; padding-right: 15px; } .header-row { background-color: #efefef; } .header-row div { font-weight: bold; margin: 10px 00px 10px 0px; } /* Set widths on the form inputs since otherwise they're 100% wide */ input, select, textarea, .alert-danger { max-width: 300px; } .toolbar-item a { cursor: pointer; } input.ng-invalid, select.ng-invalid { border-left: 5px solid #a94442; } input.ng-valid, select.ng-valid { border-left: 5px solid #42A948; } ================================================ FILE: AspNetCorePostgreSQLDockerApp/wwwroot/index2.html ================================================ Angular and ASP.NET Core
Loading...

================================================ FILE: AspNetCorePostgreSQLDockerApp/wwwroot/web.config ================================================ ================================================ FILE: AspNetCorePostgreSQLDockerApp.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26228.9 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AspNetCorePostgreSQLDockerApp", "AspNetCorePostgreSQLDockerApp/AspNetCorePostgreSQLDockerApp.csproj", "{94FF9455-201B-452A-8262-AFB25D1CF615}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCorePostgreSQLDockerApp", "AspNetCorePostgreSQLDockerApp\AspNetCorePostgreSQLDockerApp.csproj", "{E32E1866-48E9-47FA-9DEF-3F91BC29C5C8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {E32E1866-48E9-47FA-9DEF-3F91BC29C5C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E32E1866-48E9-47FA-9DEF-3F91BC29C5C8}.Debug|Any CPU.Build.0 = Debug|Any CPU {E32E1866-48E9-47FA-9DEF-3F91BC29C5C8}.Release|Any CPU.ActiveCfg = Release|Any CPU {E32E1866-48E9-47FA-9DEF-3F91BC29C5C8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {E32E1866-48E9-47FA-9DEF-3F91BC29C5C8} = {94FF9455-201B-452A-8262-AFB25D1CF615} EndGlobalSection EndGlobal ================================================ FILE: README.md ================================================ # ASP.NET Core with PostgreSQL and Docker Demo Application demo designed to show how ASP.NET Core and PostgreSQL can be run in Docker containers. The app uses Entity Framework to create a simple database that stores Docker commands and examples. It also shows how Angular can be integrated with Web API to display customer information. ### Running the App with Docker Compose 1. Install `Docker Desktop for Mac` or `Docker Desktop for Windows`. 1. Navigate to the `AspNetCorePostgreSQLDockerApp` subfolder in a console window. 1. Open the `Client` folder in a terminal window and run the following commands at the root of the folder (requires Node.js): - `npm install` - `npm install -g @angular/cli` - `ng build` 1. Move back up a level to the `AspNetCorePostgreSQLDockerApp` in the terminal window: - Run `docker-compose build` - Run `docker-compose up` 1. Navigate to http://localhost:5000 in your browser to view the site. ## Using the Web App for Container Services on Azure 1. Run `docker-compose -f docker-compose.prod.yml build`. 1. Tag the `aspnetcoreapp` image as `[yourDockerHubUserAccount]/aspnetcoreapp`. Make sure you substitute your Docker Hub user account for `[yourDockerHubUserAccount]`. 1. Push the image to Docker Hub using `docker push [yourDockerHubUserAccount]/aspnetcoreapp`. 1. Open `docker-compose azure.yml` file and change the image for the `web` service to `[yourDockerHubUserAccount]/aspnetcoreapp`. 1. Create a new `Web App for Containers` service in Azure. You'll need to add it to a new or existing Resource Group. 1. On the `Docker` tab, switch `Options` to `Docker Compose`, `Image Source` to `Docker Hub` and upload the `docker-compose azure.yml` file using the `Configuration File` section of the screen. 1. Wait for the service to start (it may take a few minutes to pull the image and fire up the Web App Service) and then click the web link it provides in the `Overview` section to hit the app.