Upload project.
This commit is contained in:
parent
251cec2dac
commit
15556e92aa
490
ThAmCo-Products/.gitignore
vendored
Normal file
490
ThAmCo-Products/.gitignore
vendored
Normal file
@ -0,0 +1,490 @@
|
||||
|
||||
# Created by https://www.gitignore.io/api/dotnetcore,aspnetcore,visualstudio
|
||||
# Edit at https://www.gitignore.io/?templates=dotnetcore,aspnetcore,visualstudio
|
||||
|
||||
### ASPNETCore ###
|
||||
## 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/
|
||||
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
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# 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
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/
|
||||
|
||||
### DotnetCore ###
|
||||
# .NET Core build folders
|
||||
/bin
|
||||
/obj
|
||||
|
||||
# Common node modules locations
|
||||
/node_modules
|
||||
/wwwroot/node_modules
|
||||
|
||||
|
||||
### VisualStudio ###
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
|
||||
# NUnit
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_h.h
|
||||
*.iobj
|
||||
*.ipdb
|
||||
*_wpftmp.csproj
|
||||
|
||||
# Chutzpah Test files
|
||||
|
||||
# Visual C++ cache files
|
||||
|
||||
# Visual Studio profiler
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
|
||||
# TeamCity is a build add-in
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Visual Studio code coverage results
|
||||
|
||||
# NCrunch
|
||||
|
||||
# MightyMoose
|
||||
|
||||
# Web workbench (sass)
|
||||
|
||||
# Installshield output folder
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
|
||||
# Click-Once directory
|
||||
|
||||
# Publish Web Output
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
|
||||
# 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
|
||||
|
||||
# NuGet Packages
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
|
||||
# Windows Store app package directories and files
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
|
||||
# RIA/Silverlight projects
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
|
||||
# Visual Studio 6 build log
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
|
||||
# Paket dependency manager
|
||||
|
||||
# FAKE - F# Make
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# End of https://www.gitignore.io/api/dotnetcore,aspnetcore,visualstudio
|
5
ThAmCo-Products/Dockerfile
Normal file
5
ThAmCo-Products/Dockerfile
Normal file
@ -0,0 +1,5 @@
|
||||
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim
|
||||
COPY products/ /app
|
||||
WORKDIR /app
|
||||
EXPOSE 80
|
||||
ENTRYPOINT ["dotnet", "ThAmCo.Products.dll"]
|
@ -0,0 +1,267 @@
|
||||
using System;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Moq;
|
||||
using Moq.Protected;
|
||||
using Newtonsoft.Json;
|
||||
using ThAmCo.Products.Controllers;
|
||||
using ThAmCo.Products.Data;
|
||||
using ThAmCo.Products.Data.ProductsContext;
|
||||
using ThAmCo.Products.Models.DTOs;
|
||||
using ThAmCo.Products.Models.ViewModels;
|
||||
|
||||
namespace ThAmCo.Products.Tests.Controllers
|
||||
{
|
||||
[TestClass]
|
||||
public class ProductsControllerTests
|
||||
{
|
||||
private static class Data
|
||||
{
|
||||
public static List<Brand> Brands()
|
||||
{
|
||||
return new List<Brand>
|
||||
{
|
||||
new Brand { Id = 1, Name = "Brand 1", Description = "Description 1", AvailableProductCount = 4 },
|
||||
new Brand { Id = 2, Name = "Brand 2", Description = "Description 2", AvailableProductCount = 2 }
|
||||
};
|
||||
}
|
||||
|
||||
public static List<Category> Categories()
|
||||
{
|
||||
return new List<Category>
|
||||
{
|
||||
new Category { Id = 1, Name = "Category 1", AvailableProductCount = 4 },
|
||||
new Category { Id = 2, Name = "Category 2", AvailableProductCount = 12 }
|
||||
};
|
||||
}
|
||||
|
||||
public static List<Product> Products()
|
||||
{
|
||||
return new List<Product>
|
||||
{
|
||||
new Product{ Id = 1, Name = "Product 1", Description = "Description 1", BrandId = 1, Brand = Brands()[0], CategoryId = 1, Category = Categories()[0], Active = true},
|
||||
new Product{ Id = 2, Name = "Product 2", Description = "Description 2", BrandId = 2, Brand = Brands()[1], CategoryId = 2, Category = Categories()[1], Active = true}
|
||||
};
|
||||
}
|
||||
|
||||
public static List<ProductStockDTO> ProductStocks() => new List<ProductStockDTO>
|
||||
{
|
||||
new ProductStockDTO { Id = 1, Stock = 10, PriceId = 1, ProductId = 1 },
|
||||
new ProductStockDTO { Id = 2, Stock = 0, PriceId = 3, ProductId = 2 }
|
||||
};
|
||||
|
||||
public static List<PriceDTO> Prices() => new List<PriceDTO>
|
||||
{
|
||||
new PriceDTO { Id = 1, ProductStockId = 1, ProductPrice = 8.99 },
|
||||
new PriceDTO { Id = 2, ProductStockId = 2, ProductPrice = 24.99 },
|
||||
new PriceDTO { Id = 3, ProductStockId = 2, ProductPrice = 19.99 }
|
||||
};
|
||||
}
|
||||
|
||||
private Mock<HttpMessageHandler> CreateHttpMock(HttpResponseMessage expected)
|
||||
{
|
||||
var mock = new Mock<HttpMessageHandler>();
|
||||
mock.Protected()
|
||||
.Setup<Task<HttpResponseMessage>>(
|
||||
"SendAsync",
|
||||
ItExpr.IsAny<HttpRequestMessage>(),
|
||||
ItExpr.IsAny<CancellationToken>())
|
||||
.ReturnsAsync(expected)
|
||||
.Verifiable();
|
||||
return mock;
|
||||
}
|
||||
|
||||
private const int outOfBoundsId = 3;
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetProductIndex_AllValid_AllReturned()
|
||||
{
|
||||
var expectedResult = new List<MultipleStockDTO>
|
||||
{
|
||||
new MultipleStockDTO { ProductStock = Data.ProductStocks()[0], Price = Data.Prices()[0]},
|
||||
new MultipleStockDTO { ProductStock = Data.ProductStocks()[1], Price = Data.Prices()[2] }
|
||||
};
|
||||
|
||||
var expectedJson = JsonConvert.SerializeObject(expectedResult);
|
||||
Console.WriteLine(expectedJson);
|
||||
var expectedUri = new Uri("https://localhost:44385/stock/");
|
||||
var expectedResponse = new HttpResponseMessage
|
||||
{
|
||||
StatusCode = HttpStatusCode.OK,
|
||||
Content = new StringContent(expectedJson,
|
||||
Encoding.UTF8,
|
||||
"application/json")
|
||||
};
|
||||
var mock = CreateHttpMock(expectedResponse);
|
||||
|
||||
var httpClient = new HttpClient(mock.Object);
|
||||
|
||||
var brands = Data.Brands();
|
||||
var categories = Data.Categories();
|
||||
var products = Data.Products();
|
||||
var context = new MockProductsContext(products, brands, categories);
|
||||
var controller = new ProductsController(context, null);
|
||||
controller.HttpClient = new HttpClient(mock.Object);
|
||||
|
||||
var result = await controller.Index(null, null, null, null);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as ViewResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var dtoResult = objectResult.Model as ProductsIndexModel;
|
||||
Assert.IsNotNull(dtoResult);
|
||||
|
||||
Assert.IsNull(dtoResult.PriceLow);
|
||||
Assert.IsNull(dtoResult.PriceHigh);
|
||||
Assert.AreEqual(dtoResult.Name, string.Empty);
|
||||
Assert.AreEqual(dtoResult.Description, string.Empty);
|
||||
|
||||
foreach (var p in dtoResult.Products)
|
||||
{
|
||||
var productExpected = Data.Products().FirstOrDefault(prod => prod.Id == p.Product.Id);
|
||||
Assert.IsNotNull(productExpected);
|
||||
var brandExpected = Data.Brands().FirstOrDefault(brand => brand.Id == productExpected.BrandId);
|
||||
Assert.IsNotNull(brandExpected);
|
||||
var categoryExpected = Data.Categories().FirstOrDefault(cat => cat.Id == productExpected.CategoryId);
|
||||
Assert.IsNotNull(categoryExpected);
|
||||
var stockExpected = Data.ProductStocks().FirstOrDefault(stocks => stocks.ProductId == p.Product.Id);
|
||||
Assert.IsNotNull(stockExpected);
|
||||
var priceExpected = Data.Prices().FirstOrDefault(price => price.Id == stockExpected.PriceId);
|
||||
Assert.IsNotNull(priceExpected);
|
||||
|
||||
Assert.AreEqual(priceExpected.ProductPrice, p.Price);
|
||||
|
||||
Assert.AreEqual(productExpected.Active, p.Product.Active);
|
||||
Assert.AreEqual(productExpected.Description, p.Product.Description);
|
||||
Assert.AreEqual(productExpected.Id, p.Product.Id);
|
||||
Assert.AreEqual(productExpected.Name, p.Product.Name);
|
||||
Assert.AreEqual(productExpected.BrandId, p.Product.BrandId);
|
||||
Assert.AreEqual(productExpected.CategoryId, p.Product.CategoryId);
|
||||
|
||||
Assert.AreEqual(brandExpected.Description, p.Product.Brand.Description);
|
||||
Assert.AreEqual(brandExpected.Id, p.Product.Brand.Id);
|
||||
Assert.AreEqual(brandExpected.Name, p.Product.Brand.Name);
|
||||
Assert.AreEqual(brandExpected.AvailableProductCount, p.Product.Brand.AvailableProductCount);
|
||||
|
||||
Assert.AreEqual(categoryExpected.Id, p.Product.Category.Id);
|
||||
Assert.AreEqual(categoryExpected.Name, p.Product.Category.Name);
|
||||
Assert.AreEqual(categoryExpected.AvailableProductCount, p.Product.Category.AvailableProductCount);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetProductDetails_OutOfBounds_NotFoundReturned()
|
||||
{
|
||||
var brands = Data.Brands();
|
||||
var categories = Data.Categories();
|
||||
var products = Data.Products();
|
||||
var context = new MockProductsContext(products, brands, categories);
|
||||
var controller = new ProductsController(context, null);
|
||||
|
||||
var result = await controller.Details(outOfBoundsId);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var productResult = result as NotFoundResult;
|
||||
Assert.IsNotNull(productResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetProductDetails_NullPassed_NotFoundReturned()
|
||||
{
|
||||
var brands = Data.Brands();
|
||||
var categories = Data.Categories();
|
||||
var products = Data.Products();
|
||||
var context = new MockProductsContext(products, brands, categories);
|
||||
var controller = new ProductsController(context, null);
|
||||
|
||||
var result = await controller.Details(-1);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var productResult = result as NotFoundResult;
|
||||
Assert.IsNotNull(productResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SoftDeleteProduct_Valid_ActiveIsFalse()
|
||||
{
|
||||
var brands = Data.Brands();
|
||||
var categories = Data.Categories();
|
||||
var products = Data.Products();
|
||||
var context = new MockProductsContext(products, brands, categories);
|
||||
var controller = new ProductsController(context, null);
|
||||
|
||||
var result = await controller.DeleteConfirmed(1);
|
||||
var resultContent = context.GetProductAsync(1).Result;
|
||||
var expectedResult = products.FirstOrDefault(p => p.Id == 1);
|
||||
if (expectedResult != null)
|
||||
expectedResult.Active = false;
|
||||
|
||||
Assert.IsNotNull(expectedResult);
|
||||
Assert.IsNotNull(result);
|
||||
var productResult = result as RedirectToActionResult;
|
||||
Assert.IsNotNull(productResult);
|
||||
|
||||
Assert.AreEqual(expectedResult.Id, resultContent.Id);
|
||||
Assert.AreEqual(expectedResult.Name, resultContent.Name);
|
||||
Assert.AreEqual(expectedResult.Active, resultContent.Active);
|
||||
Assert.AreEqual(expectedResult.BrandId, resultContent.BrandId);
|
||||
Assert.AreEqual(expectedResult.CategoryId, resultContent.CategoryId);
|
||||
Assert.AreEqual(expectedResult.Description, resultContent.Description);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SoftDeleteProduct_OutOfBounds_NoChange()
|
||||
{
|
||||
var brands = Data.Brands();
|
||||
var categories = Data.Categories();
|
||||
var products = Data.Products();
|
||||
var context = new MockProductsContext(products, brands, categories);
|
||||
var controller = new ProductsController(context, null);
|
||||
|
||||
var unchangedResult = context.GetAll().Result.ToList();
|
||||
var result = await controller.DeleteConfirmed(outOfBoundsId);
|
||||
var resultContent = context.GetAll().Result.ToList();
|
||||
|
||||
Assert.AreEqual(unchangedResult.Count, resultContent.Count);
|
||||
Assert.IsNotNull(result);
|
||||
var productResult = result as RedirectToActionResult;
|
||||
Assert.IsNotNull(productResult);
|
||||
|
||||
CollectionAssert.AreEqual(unchangedResult, resultContent);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetAllProducts_AllProductsReturned()
|
||||
{
|
||||
var brands = Data.Brands();
|
||||
var categories = Data.Categories();
|
||||
var products = Data.Products();
|
||||
var context = new MockProductsContext(products, brands, categories);
|
||||
var controller = new ProductsController(context, null);
|
||||
|
||||
var result = await controller.GetAllProducts();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var productResult = result.Result as OkObjectResult;
|
||||
var productEnumerable = productResult.Value as IEnumerable<Product>;
|
||||
var productList = productEnumerable.ToList();
|
||||
Assert.AreEqual(products.Count, productList.Count);
|
||||
for (int i = 0; i < products.Count; i++)
|
||||
{
|
||||
Assert.AreEqual(products[i].Id, productList[i].Id);
|
||||
Assert.AreEqual(products[i].Active, productList[i].Active);
|
||||
Assert.AreEqual(products[i].BrandId, productList[i].BrandId);
|
||||
Assert.AreEqual(products[i].CategoryId, productList[i].CategoryId);
|
||||
Assert.AreEqual(products[i].Description, productList[i].Description);
|
||||
Assert.AreEqual(products[i].Name, productList[i].Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="IdentityModel" Version="4.1.1" />
|
||||
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.6" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
|
||||
<PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
|
||||
<PackageReference Include="Moq" Version="4.13.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ThAmCo.Products\ThAmCo.Products.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
31
ThAmCo-Products/ThAmCo.Products.sln
Normal file
31
ThAmCo-Products/ThAmCo.Products.sln
Normal file
@ -0,0 +1,31 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.29102.190
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThAmCo.Products", "ThAmCo.Products\ThAmCo.Products.csproj", "{BFC488E9-317C-4B68-80C3-92D4F43C1316}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThAmCo.Products.Tests", "ThAmCo.Products.Tests\ThAmCo.Products.Tests.csproj", "{0191D9C8-E20B-4A2A-8263-172314CBDF4A}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{BFC488E9-317C-4B68-80C3-92D4F43C1316}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{BFC488E9-317C-4B68-80C3-92D4F43C1316}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{BFC488E9-317C-4B68-80C3-92D4F43C1316}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{BFC488E9-317C-4B68-80C3-92D4F43C1316}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0191D9C8-E20B-4A2A-8263-172314CBDF4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0191D9C8-E20B-4A2A-8263-172314CBDF4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0191D9C8-E20B-4A2A-8263-172314CBDF4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0191D9C8-E20B-4A2A-8263-172314CBDF4A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {8C15F4CA-2AB2-4A26-B6C9-C0CB7B0465C7}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
105
ThAmCo-Products/ThAmCo.Products/Controllers/AccountController.cs
Normal file
105
ThAmCo-Products/ThAmCo.Products/Controllers/AccountController.cs
Normal file
@ -0,0 +1,105 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using IdentityModel.Client;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ThAmCo.Products.Models;
|
||||
|
||||
namespace ThAmCo.Products.Controllers
|
||||
{
|
||||
public class AccountController : Controller
|
||||
{
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
|
||||
public AccountController(IHttpClientFactory clientFactory)
|
||||
{
|
||||
_clientFactory = clientFactory;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> Login()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[AllowAnonymous]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Login([FromForm] LoginModel model)
|
||||
{
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
|
||||
var disco = await client.GetDiscoveryDocumentAsync("https://localhost:43389");
|
||||
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
|
||||
{
|
||||
Address = disco.TokenEndpoint,
|
||||
ClientId = "my_web_app",
|
||||
ClientSecret = "secret",
|
||||
|
||||
UserName = model.Email,
|
||||
Password = model.Password
|
||||
});
|
||||
|
||||
if (tokenResponse.IsError)
|
||||
return View();
|
||||
|
||||
var userInfoResponse = await client.GetUserInfoAsync(new UserInfoRequest
|
||||
{
|
||||
Address = disco.UserInfoEndpoint,
|
||||
Token = tokenResponse.AccessToken
|
||||
});
|
||||
|
||||
if (userInfoResponse.IsError)
|
||||
return View();
|
||||
|
||||
var claimsIdentity = new ClaimsIdentity(userInfoResponse.Claims, "Cookies");
|
||||
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
|
||||
|
||||
var tokensToStore = new AuthenticationToken[]
|
||||
{
|
||||
new AuthenticationToken { Name = "access_token", Value = tokenResponse.AccessToken }
|
||||
};
|
||||
var authProperties = new AuthenticationProperties();
|
||||
authProperties.StoreTokens(tokensToStore);
|
||||
|
||||
await HttpContext.SignInAsync("Cookies", claimsPrincipal, authProperties);
|
||||
|
||||
return LocalRedirect("/");
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
await HttpContext.SignOutAsync("Cookies");
|
||||
return Ok("Signed Out");
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
public IActionResult Authed()
|
||||
{
|
||||
return Ok("Authed");
|
||||
}
|
||||
|
||||
[Authorize(Policy = "StaffOnly")]
|
||||
public IActionResult StaffAuthed()
|
||||
{
|
||||
return Ok("Authed");
|
||||
}
|
||||
|
||||
public IActionResult AccessDenied()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
private HttpClient GetHttpClient(string s)
|
||||
{
|
||||
return _clientFactory.CreateClient(s);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
using System.Diagnostics;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ThAmCo.Products.Models;
|
||||
|
||||
namespace ThAmCo.Products.Controllers
|
||||
{
|
||||
public class HomeController : Controller
|
||||
{
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult Privacy()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
|
||||
public IActionResult Error()
|
||||
{
|
||||
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,186 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
using ThAmCo.Products.Data;
|
||||
using ThAmCo.Products.Data.ProductsContext;
|
||||
using ThAmCo.Products.Models.DTOs;
|
||||
using ThAmCo.Products.Models.ViewModels;
|
||||
|
||||
namespace ThAmCo.Products.Controllers
|
||||
{
|
||||
public class ProductsController : Controller
|
||||
{
|
||||
private readonly IProductsContext _context;
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
|
||||
public HttpClient HttpClient { get; set; }
|
||||
|
||||
public ProductsController(IProductsContext context, IHttpClientFactory clientFactory)
|
||||
{
|
||||
_context = context;
|
||||
_clientFactory = clientFactory;
|
||||
}
|
||||
|
||||
// GET: Products
|
||||
//Auth here?
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> Index(double? PriceLow, double? PriceHigh, string Name, string Description, int BrandId = 0, int CategoryId = 0)
|
||||
{
|
||||
var authenticated = false;
|
||||
|
||||
try
|
||||
{
|
||||
var authentication = await HttpContext.AuthenticateAsync();
|
||||
authenticated = authentication.Succeeded;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
var products = await _context.GetAllActive();
|
||||
|
||||
if (BrandId != 0)
|
||||
products = products.Where(p => p.BrandId == BrandId).ToList();
|
||||
if (CategoryId != 0)
|
||||
products = products.Where(p => p.CategoryId == CategoryId).ToList();
|
||||
|
||||
if (!String.IsNullOrEmpty(Name))
|
||||
products = products.Where(p => p.Name.ToLower().Contains(Name.ToLower())).ToList();
|
||||
if (!String.IsNullOrEmpty(Description))
|
||||
products = products.Where(p => p.Description.Contains(Description)).ToList();
|
||||
|
||||
var productsWithPriceStock = new List<ProductsPriceStockModel>();
|
||||
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
var response = await client.GetAsync("https://localhost:44385/stock/ProductStocks");
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var objectResult = await response.Content.ReadAsAsync<List<MultipleStockDTO>>();
|
||||
foreach (var t in products)
|
||||
{
|
||||
int? stock = null;
|
||||
if (authenticated)
|
||||
stock = objectResult.FirstOrDefault(or => or.ProductStock.ProductId == t.Id).ProductStock.Stock;
|
||||
productsWithPriceStock.Add(new ProductsPriceStockModel
|
||||
{
|
||||
Product = t,
|
||||
Price = objectResult.FirstOrDefault(or => or.ProductStock.ProductId == t.Id).Price.ProductPrice,
|
||||
Stock = stock
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
productsWithPriceStock.AddRange(products.Select(p => new ProductsPriceStockModel { Product = p, Price = null, Stock = null }));
|
||||
|
||||
var productIndex = new ProductsIndexModel
|
||||
{
|
||||
Name = Name ?? "",
|
||||
Description = Description ?? "",
|
||||
Products = productsWithPriceStock,
|
||||
BrandId = BrandId,
|
||||
CategoryId = CategoryId
|
||||
};
|
||||
|
||||
var selectListBrands = new List<Brand> { new Brand { Id = 0, Name = "All Brands" } };
|
||||
selectListBrands.AddRange(await _context.GetBrandsAsync());
|
||||
var selectListCategories = new List<Category> { new Category { Id = 0, Name = "All Categories" } };
|
||||
selectListCategories.AddRange(await _context.GetCategoriesAsync());
|
||||
|
||||
ViewData["BrandList"] = new SelectList(selectListBrands, "Id", "Name");
|
||||
ViewData["CategoryList"] = new SelectList(selectListCategories, "Id", "Name");
|
||||
|
||||
return View(productIndex);
|
||||
}
|
||||
|
||||
// GET: Products/Details/5
|
||||
public async Task<IActionResult> Details(int id)
|
||||
{
|
||||
if (id <= 0)
|
||||
return NotFound();
|
||||
|
||||
var product = await _context.GetProductAsync(id);
|
||||
|
||||
if (product == null)
|
||||
return NotFound();
|
||||
|
||||
var client = GetHttpClient("ReviewRequest");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
var objectResult = new List<ReviewDto>();
|
||||
HttpResponseMessage response = null;
|
||||
try
|
||||
{
|
||||
response = await client.GetAsync("https://localhost:44367/reviews/GetReviewProduct?prodid=" + id);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
if (response != null && response.IsSuccessStatusCode)
|
||||
{
|
||||
objectResult = await response.Content.ReadAsAsync<List<ReviewDto>>();
|
||||
}
|
||||
|
||||
return View(new DetailsWithReviewsModelcs { Product = product, Reviews = objectResult });
|
||||
}
|
||||
|
||||
// GET: Products/Delete/5
|
||||
public async Task<IActionResult> Delete(int? id)
|
||||
{
|
||||
if (id == null)
|
||||
return NotFound();
|
||||
|
||||
var product = await _context.GetProductAsync(id ?? 0);
|
||||
|
||||
if (product == null)
|
||||
return NotFound();
|
||||
|
||||
return View(product);
|
||||
}
|
||||
|
||||
// POST: Products/Delete/5
|
||||
[Authorize]
|
||||
[HttpPost, ActionName("Delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> DeleteConfirmed(int id)
|
||||
{
|
||||
var product = await _context.GetProductAsync(id);
|
||||
_context.SoftDeleteProductAsync(product);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<Product>> GetProduct(int id)
|
||||
{
|
||||
return Ok(await _context.GetProductAsync(id));
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<IEnumerable<Product>>> GetAllProducts()
|
||||
{
|
||||
return Ok(await _context.GetAllActive());
|
||||
}
|
||||
|
||||
private bool ProductExists(int id)
|
||||
{
|
||||
return _context.GetAll().Result.Any(e => e.Id == id);
|
||||
}
|
||||
|
||||
private HttpClient GetHttpClient(string s)
|
||||
{
|
||||
if (_clientFactory == null && HttpClient != null) return HttpClient;
|
||||
|
||||
return _clientFactory.CreateClient(s);
|
||||
}
|
||||
}
|
||||
}
|
10
ThAmCo-Products/ThAmCo.Products/Data/Brand.cs
Normal file
10
ThAmCo-Products/ThAmCo.Products/Data/Brand.cs
Normal file
@ -0,0 +1,10 @@
|
||||
namespace ThAmCo.Products.Data
|
||||
{
|
||||
public class Brand
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Description { get; set; }
|
||||
public int AvailableProductCount { get; set; }
|
||||
}
|
||||
}
|
9
ThAmCo-Products/ThAmCo.Products/Data/Category.cs
Normal file
9
ThAmCo-Products/ThAmCo.Products/Data/Category.cs
Normal file
@ -0,0 +1,9 @@
|
||||
namespace ThAmCo.Products.Data
|
||||
{
|
||||
public class Category
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public int AvailableProductCount { get; set; }
|
||||
}
|
||||
}
|
88
ThAmCo-Products/ThAmCo.Products/Data/Migrations/20191105145333_InitialCreate.Designer.cs
generated
Normal file
88
ThAmCo-Products/ThAmCo.Products/Data/Migrations/20191105145333_InitialCreate.Designer.cs
generated
Normal file
@ -0,0 +1,88 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using ThAmCo.Products.Data;
|
||||
|
||||
namespace ThAmCo.Products.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(ProductsDbContext))]
|
||||
[Migration("20191105145333_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "2.2.6-servicing-10079")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128)
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Brand", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Brands");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Category", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Category");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Product", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<bool>("Active");
|
||||
|
||||
b.Property<int?>("BrandId");
|
||||
|
||||
b.Property<int?>("CategoryId");
|
||||
|
||||
b.Property<string>("Description");
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("BrandId");
|
||||
|
||||
b.HasIndex("CategoryId");
|
||||
|
||||
b.ToTable("Products");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Product", b =>
|
||||
{
|
||||
b.HasOne("ThAmCo.Products.Data.Brand", "Brand")
|
||||
.WithMany()
|
||||
.HasForeignKey("BrandId");
|
||||
|
||||
b.HasOne("ThAmCo.Products.Data.Category", "Category")
|
||||
.WithMany()
|
||||
.HasForeignKey("CategoryId");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,88 @@
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
namespace ThAmCo.Products.Data.Migrations
|
||||
{
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Brands",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(nullable: false)
|
||||
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
|
||||
Name = table.Column<string>(nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Brands", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Category",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(nullable: false)
|
||||
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
|
||||
Name = table.Column<string>(nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Category", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Products",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(nullable: false)
|
||||
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
|
||||
Name = table.Column<string>(nullable: true),
|
||||
Description = table.Column<string>(nullable: true),
|
||||
BrandId = table.Column<int>(nullable: true),
|
||||
CategoryId = table.Column<int>(nullable: true),
|
||||
Active = table.Column<bool>(nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Products", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Products_Brands_BrandId",
|
||||
column: x => x.BrandId,
|
||||
principalTable: "Brands",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
table.ForeignKey(
|
||||
name: "FK_Products_Category_CategoryId",
|
||||
column: x => x.CategoryId,
|
||||
principalTable: "Category",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Products_BrandId",
|
||||
table: "Products",
|
||||
column: "BrandId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Products_CategoryId",
|
||||
table: "Products",
|
||||
column: "CategoryId");
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Products");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Brands");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Category");
|
||||
}
|
||||
}
|
||||
}
|
188
ThAmCo-Products/ThAmCo.Products/Data/Migrations/20191107105050_InitialProductTestData.Designer.cs
generated
Normal file
188
ThAmCo-Products/ThAmCo.Products/Data/Migrations/20191107105050_InitialProductTestData.Designer.cs
generated
Normal file
@ -0,0 +1,188 @@
|
||||
// <auto-generated />
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using ThAmCo.Products.Data;
|
||||
|
||||
namespace ThAmCo.Products.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(ProductsDbContext))]
|
||||
[Migration("20191107105050_InitialProductTestData")]
|
||||
partial class InitialProductTestData
|
||||
{
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "2.2.0-rtm-35687")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128)
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Brand", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Brands");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Name = "Brand 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
Name = "Brand 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
Name = "Brand 3"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Category", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Category");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Name = "Category 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
Name = "Category 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
Name = "Category 3"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Product", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<bool>("Active");
|
||||
|
||||
b.Property<int>("BrandId");
|
||||
|
||||
b.Property<int>("CategoryId");
|
||||
|
||||
b.Property<string>("Description");
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("BrandId");
|
||||
|
||||
b.HasIndex("CategoryId");
|
||||
|
||||
b.ToTable("Products");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 1.",
|
||||
Name = "Product 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
Active = true,
|
||||
BrandId = 2,
|
||||
CategoryId = 3,
|
||||
Description = "Description of product 2.",
|
||||
Name = "Product 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
Active = true,
|
||||
BrandId = 3,
|
||||
CategoryId = 1,
|
||||
Description = "Description of product 3.",
|
||||
Name = "Product 3"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 4,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 4.",
|
||||
Name = "Product 4"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 5,
|
||||
Active = true,
|
||||
BrandId = 2,
|
||||
CategoryId = 3,
|
||||
Description = "Description of product 5.",
|
||||
Name = "Product 5"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 6,
|
||||
Active = true,
|
||||
BrandId = 3,
|
||||
CategoryId = 1,
|
||||
Description = "Description of product 6.",
|
||||
Name = "Product 6"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 7,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 7.",
|
||||
Name = "Product 7"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Product", b =>
|
||||
{
|
||||
b.HasOne("ThAmCo.Products.Data.Brand", "Brand")
|
||||
.WithMany()
|
||||
.HasForeignKey("BrandId")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
b.HasOne("ThAmCo.Products.Data.Category", "Category")
|
||||
.WithMany()
|
||||
.HasForeignKey("CategoryId")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,186 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
namespace ThAmCo.Products.Data.Migrations
|
||||
{
|
||||
public partial class InitialProductTestData : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_Products_Brands_BrandId",
|
||||
table: "Products");
|
||||
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_Products_Category_CategoryId",
|
||||
table: "Products");
|
||||
|
||||
migrationBuilder.AlterColumn<int>(
|
||||
name: "CategoryId",
|
||||
table: "Products",
|
||||
nullable: false,
|
||||
oldClrType: typeof(int),
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AlterColumn<int>(
|
||||
name: "BrandId",
|
||||
table: "Products",
|
||||
nullable: false,
|
||||
oldClrType: typeof(int),
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "Brands",
|
||||
columns: new[] { "Id", "Name" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ 1, "Brand 1" },
|
||||
{ 2, "Brand 2" },
|
||||
{ 3, "Brand 3" }
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "Category",
|
||||
columns: new[] { "Id", "Name" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ 1, "Category 1" },
|
||||
{ 2, "Category 2" },
|
||||
{ 3, "Category 3" }
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "Products",
|
||||
columns: new[] { "Id", "Active", "BrandId", "CategoryId", "Description", "Name" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ 3, true, 3, 1, "Description of product 3.", "Product 3" },
|
||||
{ 6, true, 3, 1, "Description of product 6.", "Product 6" },
|
||||
{ 1, true, 1, 2, "Description of product 1.", "Product 1" },
|
||||
{ 4, true, 1, 2, "Description of product 4.", "Product 4" },
|
||||
{ 7, true, 1, 2, "Description of product 7.", "Product 7" },
|
||||
{ 2, true, 2, 3, "Description of product 2.", "Product 2" },
|
||||
{ 5, true, 2, 3, "Description of product 5.", "Product 5" }
|
||||
});
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_Products_Brands_BrandId",
|
||||
table: "Products",
|
||||
column: "BrandId",
|
||||
principalTable: "Brands",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_Products_Category_CategoryId",
|
||||
table: "Products",
|
||||
column: "CategoryId",
|
||||
principalTable: "Category",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_Products_Brands_BrandId",
|
||||
table: "Products");
|
||||
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_Products_Category_CategoryId",
|
||||
table: "Products");
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Products",
|
||||
keyColumn: "Id",
|
||||
keyValue: 1);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Products",
|
||||
keyColumn: "Id",
|
||||
keyValue: 2);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Products",
|
||||
keyColumn: "Id",
|
||||
keyValue: 3);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Products",
|
||||
keyColumn: "Id",
|
||||
keyValue: 4);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Products",
|
||||
keyColumn: "Id",
|
||||
keyValue: 5);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Products",
|
||||
keyColumn: "Id",
|
||||
keyValue: 6);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Products",
|
||||
keyColumn: "Id",
|
||||
keyValue: 7);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Brands",
|
||||
keyColumn: "Id",
|
||||
keyValue: 1);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Brands",
|
||||
keyColumn: "Id",
|
||||
keyValue: 2);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Brands",
|
||||
keyColumn: "Id",
|
||||
keyValue: 3);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Category",
|
||||
keyColumn: "Id",
|
||||
keyValue: 1);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Category",
|
||||
keyColumn: "Id",
|
||||
keyValue: 2);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Category",
|
||||
keyColumn: "Id",
|
||||
keyValue: 3);
|
||||
|
||||
migrationBuilder.AlterColumn<int>(
|
||||
name: "CategoryId",
|
||||
table: "Products",
|
||||
nullable: true,
|
||||
oldClrType: typeof(int));
|
||||
|
||||
migrationBuilder.AlterColumn<int>(
|
||||
name: "BrandId",
|
||||
table: "Products",
|
||||
nullable: true,
|
||||
oldClrType: typeof(int));
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_Products_Brands_BrandId",
|
||||
table: "Products",
|
||||
column: "BrandId",
|
||||
principalTable: "Brands",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_Products_Category_CategoryId",
|
||||
table: "Products",
|
||||
column: "CategoryId",
|
||||
principalTable: "Category",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
}
|
||||
}
|
||||
}
|
203
ThAmCo-Products/ThAmCo.Products/Data/Migrations/20191223014356_NewBrandAndCategoryObjects.Designer.cs
generated
Normal file
203
ThAmCo-Products/ThAmCo.Products/Data/Migrations/20191223014356_NewBrandAndCategoryObjects.Designer.cs
generated
Normal file
@ -0,0 +1,203 @@
|
||||
// <auto-generated />
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using ThAmCo.Products.Data;
|
||||
|
||||
namespace ThAmCo.Products.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(ProductsDbContext))]
|
||||
[Migration("20191223014356_NewBrandAndCategoryObjects")]
|
||||
partial class NewBrandAndCategoryObjects
|
||||
{
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "2.2.0-rtm-35687")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128)
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Brand", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<int>("AvailableProductCount");
|
||||
|
||||
b.Property<string>("Description");
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Brands");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvailableProductCount = 3,
|
||||
Description = "Description 1",
|
||||
Name = "Brand 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
AvailableProductCount = 2,
|
||||
Description = "Description 2",
|
||||
Name = "Brand 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
AvailableProductCount = 3,
|
||||
Description = "Description 3",
|
||||
Name = "Brand 3"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Category", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<int>("AvailableProductCount");
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Category");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvailableProductCount = 4,
|
||||
Name = "Category 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
AvailableProductCount = 3,
|
||||
Name = "Category 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
AvailableProductCount = 2,
|
||||
Name = "Category 3"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Product", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<bool>("Active");
|
||||
|
||||
b.Property<int>("BrandId");
|
||||
|
||||
b.Property<int>("CategoryId");
|
||||
|
||||
b.Property<string>("Description");
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("BrandId");
|
||||
|
||||
b.HasIndex("CategoryId");
|
||||
|
||||
b.ToTable("Products");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 1.",
|
||||
Name = "Product 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
Active = true,
|
||||
BrandId = 2,
|
||||
CategoryId = 3,
|
||||
Description = "Description of product 2.",
|
||||
Name = "Product 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
Active = true,
|
||||
BrandId = 3,
|
||||
CategoryId = 1,
|
||||
Description = "Description of product 3.",
|
||||
Name = "Product 3"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 4,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 4.",
|
||||
Name = "Product 4"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 5,
|
||||
Active = true,
|
||||
BrandId = 2,
|
||||
CategoryId = 3,
|
||||
Description = "Description of product 5.",
|
||||
Name = "Product 5"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 6,
|
||||
Active = true,
|
||||
BrandId = 3,
|
||||
CategoryId = 1,
|
||||
Description = "Description of product 6.",
|
||||
Name = "Product 6"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 7,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 7.",
|
||||
Name = "Product 7"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Product", b =>
|
||||
{
|
||||
b.HasOne("ThAmCo.Products.Data.Brand", "Brand")
|
||||
.WithMany()
|
||||
.HasForeignKey("BrandId")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
b.HasOne("ThAmCo.Products.Data.Category", "Category")
|
||||
.WithMany()
|
||||
.HasForeignKey("CategoryId")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,84 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
namespace ThAmCo.Products.Data.Migrations
|
||||
{
|
||||
public partial class NewBrandAndCategoryObjects : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "AvailableProductCount",
|
||||
table: "Category",
|
||||
nullable: false,
|
||||
defaultValue: 0);
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "AvailableProductCount",
|
||||
table: "Brands",
|
||||
nullable: false,
|
||||
defaultValue: 0);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Description",
|
||||
table: "Brands",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Brands",
|
||||
keyColumn: "Id",
|
||||
keyValue: 1,
|
||||
columns: new[] { "AvailableProductCount", "Description" },
|
||||
values: new object[] { 3, "Description 1" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Brands",
|
||||
keyColumn: "Id",
|
||||
keyValue: 2,
|
||||
columns: new[] { "AvailableProductCount", "Description" },
|
||||
values: new object[] { 2, "Description 2" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Brands",
|
||||
keyColumn: "Id",
|
||||
keyValue: 3,
|
||||
columns: new[] { "AvailableProductCount", "Description" },
|
||||
values: new object[] { 3, "Description 3" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Category",
|
||||
keyColumn: "Id",
|
||||
keyValue: 1,
|
||||
column: "AvailableProductCount",
|
||||
value: 4);
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Category",
|
||||
keyColumn: "Id",
|
||||
keyValue: 2,
|
||||
column: "AvailableProductCount",
|
||||
value: 3);
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Category",
|
||||
keyColumn: "Id",
|
||||
keyValue: 3,
|
||||
column: "AvailableProductCount",
|
||||
value: 2);
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "AvailableProductCount",
|
||||
table: "Category");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "AvailableProductCount",
|
||||
table: "Brands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Description",
|
||||
table: "Brands");
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,201 @@
|
||||
// <auto-generated />
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using ThAmCo.Products.Data;
|
||||
|
||||
namespace ThAmCo.Products.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(ProductsDbContext))]
|
||||
partial class ProductsDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "2.2.0-rtm-35687")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128)
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Brand", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<int>("AvailableProductCount");
|
||||
|
||||
b.Property<string>("Description");
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Brands");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvailableProductCount = 3,
|
||||
Description = "Description 1",
|
||||
Name = "Brand 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
AvailableProductCount = 2,
|
||||
Description = "Description 2",
|
||||
Name = "Brand 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
AvailableProductCount = 3,
|
||||
Description = "Description 3",
|
||||
Name = "Brand 3"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Category", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<int>("AvailableProductCount");
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Category");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvailableProductCount = 4,
|
||||
Name = "Category 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
AvailableProductCount = 3,
|
||||
Name = "Category 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
AvailableProductCount = 2,
|
||||
Name = "Category 3"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Product", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
b.Property<bool>("Active");
|
||||
|
||||
b.Property<int>("BrandId");
|
||||
|
||||
b.Property<int>("CategoryId");
|
||||
|
||||
b.Property<string>("Description");
|
||||
|
||||
b.Property<string>("Name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("BrandId");
|
||||
|
||||
b.HasIndex("CategoryId");
|
||||
|
||||
b.ToTable("Products");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 1.",
|
||||
Name = "Product 1"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 2,
|
||||
Active = true,
|
||||
BrandId = 2,
|
||||
CategoryId = 3,
|
||||
Description = "Description of product 2.",
|
||||
Name = "Product 2"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 3,
|
||||
Active = true,
|
||||
BrandId = 3,
|
||||
CategoryId = 1,
|
||||
Description = "Description of product 3.",
|
||||
Name = "Product 3"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 4,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 4.",
|
||||
Name = "Product 4"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 5,
|
||||
Active = true,
|
||||
BrandId = 2,
|
||||
CategoryId = 3,
|
||||
Description = "Description of product 5.",
|
||||
Name = "Product 5"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 6,
|
||||
Active = true,
|
||||
BrandId = 3,
|
||||
CategoryId = 1,
|
||||
Description = "Description of product 6.",
|
||||
Name = "Product 6"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 7,
|
||||
Active = true,
|
||||
BrandId = 1,
|
||||
CategoryId = 2,
|
||||
Description = "Description of product 7.",
|
||||
Name = "Product 7"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ThAmCo.Products.Data.Product", b =>
|
||||
{
|
||||
b.HasOne("ThAmCo.Products.Data.Brand", "Brand")
|
||||
.WithMany()
|
||||
.HasForeignKey("BrandId")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
b.HasOne("ThAmCo.Products.Data.Category", "Category")
|
||||
.WithMany()
|
||||
.HasForeignKey("CategoryId")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
14
ThAmCo-Products/ThAmCo.Products/Data/Product.cs
Normal file
14
ThAmCo-Products/ThAmCo.Products/Data/Product.cs
Normal file
@ -0,0 +1,14 @@
|
||||
namespace ThAmCo.Products.Data
|
||||
{
|
||||
public class Product
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Description { get; set; }
|
||||
public int BrandId { get; set; }
|
||||
public Brand Brand { get; set; }
|
||||
public int CategoryId { get; set; }
|
||||
public Category Category { get; set; }
|
||||
public bool Active { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ThAmCo.Products.Data.ProductsContext
|
||||
{
|
||||
public interface IProductsContext
|
||||
{
|
||||
Task<IEnumerable<Product>> GetAll();
|
||||
Task<IEnumerable<Product>> GetAllActive();
|
||||
Task<Product> GetProductAsync(int id);
|
||||
void AddProductAsync(Product product);
|
||||
void SoftDeleteProductAsync(Product product = null, int? id = null);
|
||||
Task<IEnumerable<Brand>> GetBrandsAsync();
|
||||
Task<IEnumerable<Category>> GetCategoriesAsync();
|
||||
void SaveAndUpdateContext();
|
||||
}
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ThAmCo.Products.Data.ProductsContext
|
||||
{
|
||||
public class MockProductsContext : IProductsContext
|
||||
{
|
||||
private readonly List<Product> _products;
|
||||
private List<Brand> _brands;
|
||||
private List<Category> _categories;
|
||||
|
||||
public MockProductsContext(List<Product> products, List<Brand> brands, List<Category> categories)
|
||||
{
|
||||
_products = products;
|
||||
_brands = brands;
|
||||
_categories = categories;
|
||||
}
|
||||
|
||||
public Task<IEnumerable<Product>> GetAll()
|
||||
{
|
||||
return Task.FromResult(_products.AsEnumerable());
|
||||
}
|
||||
|
||||
public Task<IEnumerable<Product>> GetAllActive()
|
||||
{
|
||||
return Task.FromResult(_products.Where(p => p.Active));
|
||||
}
|
||||
|
||||
public Task<Product> GetProductAsync(int id)
|
||||
{
|
||||
return Task.FromResult(_products.FirstOrDefault(p => p.Id == id));
|
||||
}
|
||||
|
||||
public void AddProductAsync(Product product)
|
||||
{
|
||||
_products.Add(product);
|
||||
}
|
||||
|
||||
public void SoftDeleteProductAsync(Product product = null, int? id = null)
|
||||
{
|
||||
var chosenId = 0;
|
||||
if (product == null && id != null)
|
||||
chosenId = id ?? 0;
|
||||
if (product != null && id == null)
|
||||
chosenId = product.Id;
|
||||
var productFromList = _products.FirstOrDefault(p => p.Id == chosenId);
|
||||
if (productFromList != null)
|
||||
{
|
||||
_products.Remove(product);
|
||||
_products.Add(product);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IEnumerable<Brand>> GetBrandsAsync()
|
||||
{
|
||||
return Task.FromResult(_brands.AsEnumerable());
|
||||
}
|
||||
|
||||
public Task<IEnumerable<Category>> GetCategoriesAsync()
|
||||
{
|
||||
return Task.FromResult(_categories.AsEnumerable());
|
||||
}
|
||||
|
||||
public void SaveAndUpdateContext()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ThAmCo.Products.Data.ProductsContext
|
||||
{
|
||||
public class ProductsContext : IProductsContext
|
||||
{
|
||||
private readonly ProductsDbContext _context;
|
||||
|
||||
public ProductsContext(ProductsDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Product>> GetAll()
|
||||
{
|
||||
return await _context.Products.Include(p => p.Category).Include(p => p.Brand).ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Product>> GetAllActive()
|
||||
{
|
||||
return await _context.Products.Where(p => p.Active).Include(p => p.Category).Include(p => p.Brand).ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<Product> GetProductAsync(int id)
|
||||
{
|
||||
return await _context.Products.FirstOrDefaultAsync(p => p.Id == id);
|
||||
}
|
||||
|
||||
public void AddProductAsync(Product product)
|
||||
{
|
||||
_context.Add(product);
|
||||
SaveAndUpdateContext();
|
||||
}
|
||||
|
||||
public async void SoftDeleteProductAsync(Product product = null, int? id = null)
|
||||
{
|
||||
if (product != null)
|
||||
{
|
||||
product.Active = false;
|
||||
_context.Update(product);
|
||||
SaveAndUpdateContext();
|
||||
return;
|
||||
}
|
||||
|
||||
if (id == null || id <= 0) return;
|
||||
var productToChange = await _context.Products.FirstOrDefaultAsync(p => p.Id == id);
|
||||
if (productToChange != null)
|
||||
{
|
||||
productToChange.Active = false;
|
||||
_context.Update(productToChange);
|
||||
SaveAndUpdateContext();
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IEnumerable<Brand>> GetBrandsAsync()
|
||||
{
|
||||
return Task.FromResult(_context.Brands.AsEnumerable());
|
||||
}
|
||||
|
||||
public Task<IEnumerable<Category>> GetCategoriesAsync()
|
||||
{
|
||||
return Task.FromResult(_context.Category.AsEnumerable());
|
||||
}
|
||||
|
||||
public async void SaveAndUpdateContext()
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
72
ThAmCo-Products/ThAmCo.Products/Data/ProductsDbContext.cs
Normal file
72
ThAmCo-Products/ThAmCo.Products/Data/ProductsDbContext.cs
Normal file
@ -0,0 +1,72 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ThAmCo.Products.Data
|
||||
{
|
||||
public class ProductsDbContext : DbContext
|
||||
{
|
||||
public DbSet<Product> Products { get; set; }
|
||||
public DbSet<Brand> Brands { get; set; }
|
||||
public DbSet<Category> Category { get; set; }
|
||||
|
||||
private IHostingEnvironment HostEnv { get; }
|
||||
|
||||
public ProductsDbContext(DbContextOptions<ProductsDbContext> options, IHostingEnvironment env) : base(options)
|
||||
{
|
||||
HostEnv = env;
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder builder)
|
||||
{
|
||||
base.OnConfiguring(builder);
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
base.OnModelCreating(builder);
|
||||
|
||||
builder.Entity<Brand>()
|
||||
.HasKey(b => b.Id);
|
||||
|
||||
builder.Entity<Category>()
|
||||
.HasKey(c => c.Id);
|
||||
|
||||
builder.Entity<Product>()
|
||||
.HasOne(b => b.Brand);
|
||||
|
||||
builder.Entity<Product>()
|
||||
.HasOne(c => c.Category);
|
||||
|
||||
builder.Entity<Product>()
|
||||
.HasKey(p => p.Id);
|
||||
|
||||
if (HostEnv != null && HostEnv.IsDevelopment())
|
||||
{
|
||||
builder.Entity<Brand>()
|
||||
.HasData(
|
||||
new Brand { Id = 1, Name = "Brand 1", Description = "Description 1", AvailableProductCount = 3 },
|
||||
new Brand { Id = 2, Name = "Brand 2", Description = "Description 2", AvailableProductCount = 2 },
|
||||
new Brand { Id = 3, Name = "Brand 3", Description = "Description 3", AvailableProductCount = 3 }
|
||||
);
|
||||
|
||||
builder.Entity<Category>()
|
||||
.HasData(
|
||||
new Category { Id = 1, Name = "Category 1", AvailableProductCount = 4 },
|
||||
new Category { Id = 2, Name = "Category 2", AvailableProductCount = 3 },
|
||||
new Category { Id = 3, Name = "Category 3", AvailableProductCount = 2 }
|
||||
);
|
||||
|
||||
builder.Entity<Product>()
|
||||
.HasData(
|
||||
new Product { Id = 1, Name = "Product 1", Description = "Description of product 1.", BrandId = 1, CategoryId = 2, Active = true },
|
||||
new Product { Id = 2, Name = "Product 2", Description = "Description of product 2.", BrandId = 2, CategoryId = 3, Active = true },
|
||||
new Product { Id = 3, Name = "Product 3", Description = "Description of product 3.", BrandId = 3, CategoryId = 1, Active = true },
|
||||
new Product { Id = 4, Name = "Product 4", Description = "Description of product 4.", BrandId = 1, CategoryId = 2, Active = true },
|
||||
new Product { Id = 5, Name = "Product 5", Description = "Description of product 5.", BrandId = 2, CategoryId = 3, Active = true },
|
||||
new Product { Id = 6, Name = "Product 6", Description = "Description of product 6.", BrandId = 3, CategoryId = 1, Active = true },
|
||||
new Product { Id = 7, Name = "Product 7", Description = "Description of product 7.", BrandId = 1, CategoryId = 2, Active = true }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
namespace ThAmCo.Products.Models.DTOs
|
||||
{
|
||||
public class FromSingleStockDTO
|
||||
{
|
||||
public int ProductID { get; set; }
|
||||
public int Stock { get; set; }
|
||||
public double Price { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ThAmCo.Products.Models.DTOs
|
||||
{
|
||||
public class MultipleStockDTO
|
||||
{
|
||||
public ProductStockDTO ProductStock { get; set; }
|
||||
public PriceDTO Price { get; set; }
|
||||
}
|
||||
}
|
12
ThAmCo-Products/ThAmCo.Products/Models/DTOs/PriceDTO.cs
Normal file
12
ThAmCo-Products/ThAmCo.Products/Models/DTOs/PriceDTO.cs
Normal file
@ -0,0 +1,12 @@
|
||||
using System;
|
||||
|
||||
namespace ThAmCo.Products.Models.DTOs
|
||||
{
|
||||
public class PriceDTO
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int ProductStockId { get; set; }
|
||||
public double ProductPrice { get; set; }
|
||||
public DateTime Date { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
namespace ThAmCo.Products.Models.DTOs
|
||||
{
|
||||
public class ProductStockDTO
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int ProductId { get; set; }
|
||||
public int Stock { get; set; }
|
||||
public int PriceId { get; set; }
|
||||
}
|
||||
}
|
16
ThAmCo-Products/ThAmCo.Products/Models/DTOs/ReviewDto.cs
Normal file
16
ThAmCo-Products/ThAmCo.Products/Models/DTOs/ReviewDto.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ThAmCo.Products.Models.DTOs
|
||||
{
|
||||
public class ReviewDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int PurchaseId { get; set; }
|
||||
public bool IsVisible { get; set; }
|
||||
public int Rating { get; set; }
|
||||
public string Content { get; set; }
|
||||
}
|
||||
}
|
11
ThAmCo-Products/ThAmCo.Products/Models/ErrorViewModel.cs
Normal file
11
ThAmCo-Products/ThAmCo.Products/Models/ErrorViewModel.cs
Normal file
@ -0,0 +1,11 @@
|
||||
using System;
|
||||
|
||||
namespace ThAmCo.Products.Models
|
||||
{
|
||||
public class ErrorViewModel
|
||||
{
|
||||
public string RequestId { get; set; }
|
||||
|
||||
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
|
||||
}
|
||||
}
|
15
ThAmCo-Products/ThAmCo.Products/Models/LoginModel.cs
Normal file
15
ThAmCo-Products/ThAmCo.Products/Models/LoginModel.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ThAmCo.Products.Models
|
||||
{
|
||||
public class LoginModel
|
||||
{
|
||||
//[Required, EmailAddress]
|
||||
public string Email { get; set; }
|
||||
public string Password { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using ThAmCo.Products.Data;
|
||||
using ThAmCo.Products.Models.DTOs;
|
||||
|
||||
namespace ThAmCo.Products.Models.ViewModels
|
||||
{
|
||||
public class DetailsWithReviewsModelcs
|
||||
{
|
||||
public Product Product { get; set; }
|
||||
public List<ReviewDto> Reviews { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ThAmCo.Products.Models.ViewModels
|
||||
{
|
||||
public class ProductsIndexModel
|
||||
{
|
||||
public IEnumerable<ProductsPriceStockModel> Products { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Description { get; set; }
|
||||
public int? BrandId { get; set; }
|
||||
public int? CategoryId { get; set; }
|
||||
public double? PriceLow { get; set; }
|
||||
public double? PriceHigh { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
using ThAmCo.Products.Data;
|
||||
|
||||
namespace ThAmCo.Products.Models.ViewModels
|
||||
{
|
||||
public class ProductsPriceStockModel
|
||||
{
|
||||
public Product Product { get; set; }
|
||||
public int? Stock { get; set; }
|
||||
public double? Price { get; set; }
|
||||
}
|
||||
}
|
34
ThAmCo-Products/ThAmCo.Products/Program.cs
Normal file
34
ThAmCo-Products/ThAmCo.Products/Program.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using Microsoft.AspNetCore;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ThAmCo.Products.Data;
|
||||
|
||||
namespace ThAmCo.Products
|
||||
{
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var host = CreateWebHostBuilder(args).Build();
|
||||
|
||||
using (var scope = host.Services.CreateScope())
|
||||
{
|
||||
var services = scope.ServiceProvider;
|
||||
var env = services.GetRequiredService<IHostingEnvironment>();
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
var context = services.GetRequiredService<ProductsDbContext>();
|
||||
context.Database.EnsureDeleted();
|
||||
context.Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
host.Run();
|
||||
}
|
||||
|
||||
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
|
||||
WebHost.CreateDefaultBuilder(args)
|
||||
.UseStartup<Startup>();
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
{
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:63618",
|
||||
"sslPort": 44375
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"ThAmCo.Products": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "https://localhost:5001;http://localhost:5000",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
102
ThAmCo-Products/ThAmCo.Products/Startup.cs
Normal file
102
ThAmCo-Products/ThAmCo.Products/Startup.cs
Normal file
@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Polly;
|
||||
using ThAmCo.Products.Data;
|
||||
using ThAmCo.Products.Data.ProductsContext;
|
||||
|
||||
namespace ThAmCo.Products
|
||||
{
|
||||
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.Configure<CookiePolicyOptions>(options =>
|
||||
{
|
||||
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
|
||||
options.CheckConsentNeeded = context => true;
|
||||
options.MinimumSameSitePolicy = SameSiteMode.None;
|
||||
});
|
||||
|
||||
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
|
||||
|
||||
services.AddDbContext<ProductsDbContext>(options => options.UseSqlServer(
|
||||
Configuration.GetConnectionString("ProductsSqlConnection"), optionsBuilder =>
|
||||
optionsBuilder.EnableRetryOnFailure(3, TimeSpan.FromSeconds(10), null)));
|
||||
|
||||
services.AddHttpClient("StandardRequest")
|
||||
.AddTransientHttpErrorPolicy(p =>
|
||||
p.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
|
||||
.AddTransientHttpErrorPolicy(p =>
|
||||
p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));
|
||||
|
||||
services.AddHttpClient("ReviewRequest")
|
||||
.AddTransientHttpErrorPolicy(p =>
|
||||
p.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
.WaitAndRetryAsync(1, retryAttempt => TimeSpan.FromSeconds(2)));
|
||||
|
||||
services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy("StaffOnly", builder =>
|
||||
{
|
||||
builder.RequireClaim("role", "Staff");
|
||||
});
|
||||
});
|
||||
|
||||
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
options =>
|
||||
{
|
||||
options.LoginPath = new PathString("/account/login");
|
||||
options.AccessDeniedPath = new PathString("/account/AccessDenied");
|
||||
});
|
||||
|
||||
services.AddScoped<IProductsContext, ProductsContext>();
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
|
||||
{
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
}
|
||||
else
|
||||
{
|
||||
app.UseExceptionHandler("/Home/Error");
|
||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseStaticFiles();
|
||||
app.UseCookiePolicy();
|
||||
|
||||
app.UseAuthentication();
|
||||
|
||||
app.UseMvc(routes =>
|
||||
{
|
||||
routes.MapRoute(
|
||||
name: "default",
|
||||
template: "{controller=Products}/{action=Index}");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
23
ThAmCo-Products/ThAmCo.Products/ThAmCo.Products.csproj
Normal file
23
ThAmCo-Products/ThAmCo.Products/ThAmCo.Products.csproj
Normal file
@ -0,0 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="Data\Migrations\20191105145110_InitialCreate.cs" />
|
||||
<Compile Remove="Data\Migrations\20191105145110_InitialCreate.Designer.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="IdentityModel" Version="4.1.1" />
|
||||
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.6" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.App" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.4" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,9 @@
|
||||
|
||||
@{
|
||||
ViewData["Title"] = "AccessDenied";
|
||||
}
|
||||
|
||||
<h1>AccessDenied</h1><br />
|
||||
|
||||
Access to page has been denied.
|
||||
|
17
ThAmCo-Products/ThAmCo.Products/Views/Account/Login.cshtml
Normal file
17
ThAmCo-Products/ThAmCo.Products/Views/Account/Login.cshtml
Normal file
@ -0,0 +1,17 @@
|
||||
@{
|
||||
ViewData["Title"] = "Login";
|
||||
}
|
||||
|
||||
<h1>Login</h1>
|
||||
|
||||
<form asp-action="Login">
|
||||
<div class="form-group">
|
||||
<label for="emailInput">Username</label>
|
||||
<input type="email" name="email" class="form-control" placeholder="Enter email">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="passwordInput">Password</label>
|
||||
<input type="password" name="password" class="form-control" placeholder="Password">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Login</button>
|
||||
</form>
|
8
ThAmCo-Products/ThAmCo.Products/Views/Home/Index.cshtml
Normal file
8
ThAmCo-Products/ThAmCo.Products/Views/Home/Index.cshtml
Normal file
@ -0,0 +1,8 @@
|
||||
@{
|
||||
ViewData["Title"] = "Home Page";
|
||||
}
|
||||
|
||||
<div class="text-center">
|
||||
<h1 class="display-4">Welcome</h1>
|
||||
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
|
||||
</div>
|
@ -0,0 +1,6 @@
|
||||
@{
|
||||
ViewData["Title"] = "Privacy Policy";
|
||||
}
|
||||
<h1>@ViewData["Title"]</h1>
|
||||
|
||||
<p>Use this page to detail your site's privacy policy.</p>
|
43
ThAmCo-Products/ThAmCo.Products/Views/Products/Create.cshtml
Normal file
43
ThAmCo-Products/ThAmCo.Products/Views/Products/Create.cshtml
Normal file
@ -0,0 +1,43 @@
|
||||
@model ThAmCo.Products.Data.Product
|
||||
|
||||
@{
|
||||
ViewData["Title"] = "Create";
|
||||
}
|
||||
|
||||
<h1>Create</h1>
|
||||
|
||||
<h4>Product</h4>
|
||||
<hr />
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<form asp-action="Create">
|
||||
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
|
||||
<div class="form-group">
|
||||
<label asp-for="Name" class="control-label"></label>
|
||||
<input asp-for="Name" class="form-control" />
|
||||
<span asp-validation-for="Name" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label asp-for="Description" class="control-label"></label>
|
||||
<input asp-for="Description" class="form-control" />
|
||||
<span asp-validation-for="Description" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="form-group form-check">
|
||||
<label class="form-check-label">
|
||||
<input class="form-check-input" asp-for="Active" /> @Html.DisplayNameFor(model => model.Active)
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<input type="submit" value="Create" class="btn btn-primary" />
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<a asp-action="Index">Back to List</a>
|
||||
</div>
|
||||
|
||||
@section Scripts {
|
||||
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
|
||||
}
|
39
ThAmCo-Products/ThAmCo.Products/Views/Products/Delete.cshtml
Normal file
39
ThAmCo-Products/ThAmCo.Products/Views/Products/Delete.cshtml
Normal file
@ -0,0 +1,39 @@
|
||||
@model ThAmCo.Products.Data.Product
|
||||
|
||||
@{
|
||||
ViewData["Title"] = "Delete";
|
||||
}
|
||||
|
||||
<h1>Delete</h1>
|
||||
|
||||
<h3>Are you sure you want to delete this?</h3>
|
||||
<div>
|
||||
<h4>Product</h4>
|
||||
<hr />
|
||||
<dl class="row">
|
||||
<dt class = "col-sm-2">
|
||||
@Html.DisplayNameFor(model => model.Name)
|
||||
</dt>
|
||||
<dd class = "col-sm-10">
|
||||
@Html.DisplayFor(model => model.Name)
|
||||
</dd>
|
||||
<dt class = "col-sm-2">
|
||||
@Html.DisplayNameFor(model => model.Description)
|
||||
</dt>
|
||||
<dd class = "col-sm-10">
|
||||
@Html.DisplayFor(model => model.Description)
|
||||
</dd>
|
||||
<dt class = "col-sm-2">
|
||||
@Html.DisplayNameFor(model => model.Active)
|
||||
</dt>
|
||||
<dd class = "col-sm-10">
|
||||
@Html.DisplayFor(model => model.Active)
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
<form asp-action="Delete">
|
||||
<input type="hidden" asp-for="Id" />
|
||||
<input type="submit" value="Delete" class="btn btn-danger" /> |
|
||||
<a asp-action="Index">Back to List</a>
|
||||
</form>
|
||||
</div>
|
@ -0,0 +1,56 @@
|
||||
@model ThAmCo.Products.Models.ViewModels.DetailsWithReviewsModelcs
|
||||
|
||||
@{
|
||||
ViewData["Title"] = "Product Details";
|
||||
}
|
||||
|
||||
<h1>Details</h1>
|
||||
|
||||
<div>
|
||||
<h4>Product</h4>
|
||||
<hr />
|
||||
<dl class="row">
|
||||
<dt class = "col-sm-2">
|
||||
@Html.DisplayNameFor(model => model.Product.Name)
|
||||
</dt>
|
||||
<dd class = "col-sm-10">
|
||||
@Html.DisplayFor(model => model.Product.Name)
|
||||
</dd>
|
||||
<dt class = "col-sm-2">
|
||||
@Html.DisplayNameFor(model => model.Product.Description)
|
||||
</dt>
|
||||
<dd class = "col-sm-10">
|
||||
@Html.DisplayFor(model => model.Product.Description)
|
||||
</dd>
|
||||
</dl>
|
||||
</div>
|
||||
<div><h3>Reviews</h3></div><br />
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
@Html.DisplayNameFor(model => model.Reviews.FirstOrDefault().Content)
|
||||
</th>
|
||||
<th>
|
||||
@Html.DisplayNameFor(model => model.Reviews.FirstOrDefault().Rating)
|
||||
</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var item in Model.Reviews)
|
||||
{
|
||||
<tr>
|
||||
<td>
|
||||
@Html.DisplayFor(modelItem => item.Content)
|
||||
</td>
|
||||
<td>
|
||||
@Html.DisplayFor(modelItem => item.Rating)
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
<div>
|
||||
<a asp-action="Index">Back to List</a>
|
||||
</div>
|
44
ThAmCo-Products/ThAmCo.Products/Views/Products/Edit.cshtml
Normal file
44
ThAmCo-Products/ThAmCo.Products/Views/Products/Edit.cshtml
Normal file
@ -0,0 +1,44 @@
|
||||
@model ThAmCo.Products.Data.Product
|
||||
|
||||
@{
|
||||
ViewData["Title"] = "Edit";
|
||||
}
|
||||
|
||||
<h1>Edit</h1>
|
||||
|
||||
<h4>Product</h4>
|
||||
<hr />
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<form asp-action="Edit">
|
||||
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
|
||||
<input type="hidden" asp-for="Id" />
|
||||
<div class="form-group">
|
||||
<label asp-for="Name" class="control-label"></label>
|
||||
<input asp-for="Name" class="form-control" />
|
||||
<span asp-validation-for="Name" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label asp-for="Description" class="control-label"></label>
|
||||
<input asp-for="Description" class="form-control" />
|
||||
<span asp-validation-for="Description" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="form-group form-check">
|
||||
<label class="form-check-label">
|
||||
<input class="form-check-input" asp-for="Active" /> @Html.DisplayNameFor(model => model.Active)
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<input type="submit" value="Save" class="btn btn-primary" />
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<a asp-action="Index">Back to List</a>
|
||||
</div>
|
||||
|
||||
@section Scripts {
|
||||
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
|
||||
}
|
90
ThAmCo-Products/ThAmCo.Products/Views/Products/Index.cshtml
Normal file
90
ThAmCo-Products/ThAmCo.Products/Views/Products/Index.cshtml
Normal file
@ -0,0 +1,90 @@
|
||||
@model ThAmCo.Products.Models.ViewModels.ProductsIndexModel
|
||||
|
||||
@{
|
||||
ViewData["Title"] = "Index";
|
||||
}
|
||||
|
||||
<h1>Index</h1>
|
||||
|
||||
<form asp-action="Index" method="get">
|
||||
<div class="form-group">
|
||||
<label>Name</label>
|
||||
<input type="text" class="form-control" asp-for="Name" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Description</label>
|
||||
<input type="text" class="form-control" asp-for="Description" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Brand</label>
|
||||
<select asp-for="BrandId" class="form-control" asp-items="ViewBag.BrandList"></select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Category</label>
|
||||
<select asp-for="CategoryId" class="form-control" asp-items="ViewBag.CategoryList"></select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Lowest Price</label>
|
||||
<input type="number" min="0" step="0.01" asp-for="PriceLow" class="form-control" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Highest Price</label>
|
||||
<input type="number" min="0" step="0.01" asp-for="PriceHigh" class="form-control" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<input type="submit" value="Search" class="btn btn-default" />
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
@Html.DisplayNameFor(model => model.Products.FirstOrDefault().Product.Name)
|
||||
</th>
|
||||
<th>
|
||||
@Html.DisplayNameFor(model => model.Products.FirstOrDefault().Product.Description)
|
||||
</th>
|
||||
<th>
|
||||
@Html.DisplayNameFor(model => model.Products.FirstOrDefault().Price)
|
||||
</th>
|
||||
<th>
|
||||
@Html.DisplayNameFor(model => model.Products.FirstOrDefault().Stock)
|
||||
</th>
|
||||
<th>
|
||||
@Html.DisplayNameFor(model => model.Products.FirstOrDefault().Product.Brand)
|
||||
</th>
|
||||
<th>
|
||||
@Html.DisplayNameFor(model => model.Products.FirstOrDefault().Product.Category)
|
||||
</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var item in Model.Products) {
|
||||
<tr>
|
||||
<td>
|
||||
@Html.DisplayFor(modelItem => item.Product.Name)
|
||||
</td>
|
||||
<td>
|
||||
@Html.DisplayFor(modelItem => item.Product.Description)
|
||||
</td>
|
||||
<td>
|
||||
@Html.DisplayFor(modelItem => item.Price)
|
||||
</td>
|
||||
<td>
|
||||
@Html.DisplayFor(modelItem => item.Stock)
|
||||
</td>
|
||||
<td>
|
||||
@Html.DisplayFor(modelItem => item.Product.Brand.Name)
|
||||
</td>
|
||||
<td>
|
||||
@Html.DisplayFor(modelItem => item.Product.Category.Name)
|
||||
</td>
|
||||
<td>
|
||||
<a asp-action="Details" asp-route-id="@item.Product.Id">View</a>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
25
ThAmCo-Products/ThAmCo.Products/Views/Shared/Error.cshtml
Normal file
25
ThAmCo-Products/ThAmCo.Products/Views/Shared/Error.cshtml
Normal file
@ -0,0 +1,25 @@
|
||||
@model ErrorViewModel
|
||||
@{
|
||||
ViewData["Title"] = "Error";
|
||||
}
|
||||
|
||||
<h1 class="text-danger">Error.</h1>
|
||||
<h2 class="text-danger">An error occurred while processing your request.</h2>
|
||||
|
||||
@if (Model.ShowRequestId)
|
||||
{
|
||||
<p>
|
||||
<strong>Request ID:</strong> <code>@Model.RequestId</code>
|
||||
</p>
|
||||
}
|
||||
|
||||
<h3>Development Mode</h3>
|
||||
<p>
|
||||
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
|
||||
</p>
|
||||
<p>
|
||||
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
|
||||
It can result in displaying sensitive information from exceptions to end users.
|
||||
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
|
||||
and restarting the app.
|
||||
</p>
|
@ -0,0 +1,25 @@
|
||||
@using Microsoft.AspNetCore.Http.Features
|
||||
|
||||
@{
|
||||
var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
|
||||
var showBanner = !consentFeature?.CanTrack ?? false;
|
||||
var cookieString = consentFeature?.CreateConsentCookie();
|
||||
}
|
||||
|
||||
@if (showBanner)
|
||||
{
|
||||
<div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
|
||||
Use this space to summarize your privacy and cookie use policy. <a asp-area="" asp-controller="Home" asp-action="Privacy">Learn More</a>.
|
||||
<button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString">
|
||||
<span aria-hidden="true">Accept</span>
|
||||
</button>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
var button = document.querySelector("#cookieConsent button[data-cookie-string]");
|
||||
button.addEventListener("click", function (event) {
|
||||
document.cookie = button.dataset.cookieString;
|
||||
}, false);
|
||||
})();
|
||||
</script>
|
||||
}
|
83
ThAmCo-Products/ThAmCo.Products/Views/Shared/_Layout.cshtml
Normal file
83
ThAmCo-Products/ThAmCo.Products/Views/Shared/_Layout.cshtml
Normal file
@ -0,0 +1,83 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>@ViewData["Title"] - ThAmCo</title>
|
||||
|
||||
<environment include="Development">
|
||||
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
|
||||
</environment>
|
||||
<environment exclude="Development">
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
|
||||
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
|
||||
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
|
||||
crossorigin="anonymous"
|
||||
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"/>
|
||||
</environment>
|
||||
<link rel="stylesheet" href="~/css/site.css" />
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
|
||||
<div class="container">
|
||||
<a class="navbar-brand">ThAmCo</a>
|
||||
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
|
||||
aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
|
||||
<ul class="navbar-nav flex-grow-1">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-dark" asp-area="" asp-controller="Products" asp-action="Index">Products</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-dark" href="https://localhost:44385">Admin</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="Login">Login</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="Logout">Logout</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="container">
|
||||
<partial name="_CookieConsentPartial" />
|
||||
<main role="main" class="pb-3">
|
||||
@RenderBody()
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<footer class="border-top footer text-muted">
|
||||
<div class="container">
|
||||
© 2019 - ThAmCo.Products - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<environment include="Development">
|
||||
<script src="~/lib/jquery/dist/jquery.js"></script>
|
||||
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
|
||||
</environment>
|
||||
<environment exclude="Development">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
|
||||
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
|
||||
asp-fallback-test="window.jQuery"
|
||||
crossorigin="anonymous"
|
||||
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
|
||||
</script>
|
||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
|
||||
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
|
||||
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
|
||||
crossorigin="anonymous"
|
||||
integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
|
||||
</script>
|
||||
</environment>
|
||||
<script src="~/js/site.js" asp-append-version="true"></script>
|
||||
|
||||
@RenderSection("Scripts", required: false)
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,18 @@
|
||||
<environment include="Development">
|
||||
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
|
||||
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
|
||||
</environment>
|
||||
<environment exclude="Development">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"
|
||||
asp-fallback-src="~/lib/jquery-validation/dist/jquery.validate.min.js"
|
||||
asp-fallback-test="window.jQuery && window.jQuery.validator"
|
||||
crossorigin="anonymous"
|
||||
integrity="sha256-F6h55Qw6sweK+t7SiOJX+2bpSAa3b/fnlrVCJvmEj1A=">
|
||||
</script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"
|
||||
asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
|
||||
asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"
|
||||
crossorigin="anonymous"
|
||||
integrity="sha256-9GycpJnliUjJDVDqP0UEu/bsm9U+3dnQUH8+3W10vkY=">
|
||||
</script>
|
||||
</environment>
|
@ -0,0 +1,3 @@
|
||||
@using ThAmCo.Products
|
||||
@using ThAmCo.Products.Models
|
||||
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
3
ThAmCo-Products/ThAmCo.Products/Views/_ViewStart.cshtml
Normal file
3
ThAmCo-Products/ThAmCo.Products/Views/_ViewStart.cshtml
Normal file
@ -0,0 +1,3 @@
|
||||
@{
|
||||
Layout = "_Layout";
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
}
|
||||
}
|
||||
}
|
11
ThAmCo-Products/ThAmCo.Products/appsettings.json
Normal file
11
ThAmCo-Products/ThAmCo.Products/appsettings.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"ProductsSqlConnection": "Server=(localdb)\\mssqllocaldb;Database=Products;Trusted_Connection=True;MultipleActiveResultSets=true"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
56
ThAmCo-Products/ThAmCo.Products/wwwroot/css/site.css
Normal file
56
ThAmCo-Products/ThAmCo.Products/wwwroot/css/site.css
Normal file
@ -0,0 +1,56 @@
|
||||
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
|
||||
for details on configuring this project to bundle and minify static web assets. */
|
||||
|
||||
a.navbar-brand {
|
||||
white-space: normal;
|
||||
text-align: center;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* Sticky footer styles
|
||||
-------------------------------------------------- */
|
||||
html {
|
||||
font-size: 14px;
|
||||
}
|
||||
@media (min-width: 768px) {
|
||||
html {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.border-top {
|
||||
border-top: 1px solid #e5e5e5;
|
||||
}
|
||||
.border-bottom {
|
||||
border-bottom: 1px solid #e5e5e5;
|
||||
}
|
||||
|
||||
.box-shadow {
|
||||
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
|
||||
}
|
||||
|
||||
button.accept-policy {
|
||||
font-size: 1rem;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
/* Sticky footer styles
|
||||
-------------------------------------------------- */
|
||||
html {
|
||||
position: relative;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
/* Margin bottom by footer height */
|
||||
margin-bottom: 60px;
|
||||
}
|
||||
.footer {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
width: 100%;
|
||||
white-space: nowrap;
|
||||
/* Set the fixed height of the footer here */
|
||||
height: 60px;
|
||||
line-height: 60px; /* Vertically center the text there */
|
||||
}
|
BIN
ThAmCo-Products/ThAmCo.Products/wwwroot/favicon.ico
Normal file
BIN
ThAmCo-Products/ThAmCo.Products/wwwroot/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 31 KiB |
4
ThAmCo-Products/ThAmCo.Products/wwwroot/js/site.js
Normal file
4
ThAmCo-Products/ThAmCo.Products/wwwroot/js/site.js
Normal file
@ -0,0 +1,4 @@
|
||||
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
|
||||
// for details on configuring this project to bundle and minify static web assets.
|
||||
|
||||
// Write your JavaScript code.
|
@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2011-2018 Twitter, Inc.
|
||||
Copyright (c) 2011-2018 The Bootstrap Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
3719
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.css
vendored
Normal file
3719
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.css
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.css.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
7
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.min.css
vendored
Normal file
7
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.min.css.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
331
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.css
vendored
Normal file
331
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.css
vendored
Normal file
@ -0,0 +1,331 @@
|
||||
/*!
|
||||
* Bootstrap Reboot v4.3.1 (https://getbootstrap.com/)
|
||||
* Copyright 2011-2019 The Bootstrap Authors
|
||||
* Copyright 2011-2019 Twitter, Inc.
|
||||
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
|
||||
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
|
||||
*/
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html {
|
||||
font-family: sans-serif;
|
||||
line-height: 1.15;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
article, aside, figcaption, figure, footer, header, hgroup, main, nav, section {
|
||||
display: block;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
font-size: 1rem;
|
||||
font-weight: 400;
|
||||
line-height: 1.5;
|
||||
color: #212529;
|
||||
text-align: left;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
[tabindex="-1"]:focus {
|
||||
outline: 0 !important;
|
||||
}
|
||||
|
||||
hr {
|
||||
box-sizing: content-box;
|
||||
height: 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
abbr[title],
|
||||
abbr[data-original-title] {
|
||||
text-decoration: underline;
|
||||
-webkit-text-decoration: underline dotted;
|
||||
text-decoration: underline dotted;
|
||||
cursor: help;
|
||||
border-bottom: 0;
|
||||
-webkit-text-decoration-skip-ink: none;
|
||||
text-decoration-skip-ink: none;
|
||||
}
|
||||
|
||||
address {
|
||||
margin-bottom: 1rem;
|
||||
font-style: normal;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
ol,
|
||||
ul,
|
||||
dl {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
ol ol,
|
||||
ul ul,
|
||||
ol ul,
|
||||
ul ol {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
dt {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
dd {
|
||||
margin-bottom: .5rem;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
b,
|
||||
strong {
|
||||
font-weight: bolder;
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 80%;
|
||||
}
|
||||
|
||||
sub,
|
||||
sup {
|
||||
position: relative;
|
||||
font-size: 75%;
|
||||
line-height: 0;
|
||||
vertical-align: baseline;
|
||||
}
|
||||
|
||||
sub {
|
||||
bottom: -.25em;
|
||||
}
|
||||
|
||||
sup {
|
||||
top: -.5em;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #007bff;
|
||||
text-decoration: none;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #0056b3;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
a:not([href]):not([tabindex]) {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:not([href]):not([tabindex]):hover, a:not([href]):not([tabindex]):focus {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:not([href]):not([tabindex]):focus {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
pre,
|
||||
code,
|
||||
kbd,
|
||||
samp {
|
||||
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
pre {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
figure {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
img {
|
||||
vertical-align: middle;
|
||||
border-style: none;
|
||||
}
|
||||
|
||||
svg {
|
||||
overflow: hidden;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
caption {
|
||||
padding-top: 0.75rem;
|
||||
padding-bottom: 0.75rem;
|
||||
color: #6c757d;
|
||||
text-align: left;
|
||||
caption-side: bottom;
|
||||
}
|
||||
|
||||
th {
|
||||
text-align: inherit;
|
||||
}
|
||||
|
||||
label {
|
||||
display: inline-block;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
button:focus {
|
||||
outline: 1px dotted;
|
||||
outline: 5px auto -webkit-focus-ring-color;
|
||||
}
|
||||
|
||||
input,
|
||||
button,
|
||||
select,
|
||||
optgroup,
|
||||
textarea {
|
||||
margin: 0;
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
button,
|
||||
select {
|
||||
text-transform: none;
|
||||
}
|
||||
|
||||
select {
|
||||
word-wrap: normal;
|
||||
}
|
||||
|
||||
button,
|
||||
[type="button"],
|
||||
[type="reset"],
|
||||
[type="submit"] {
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
|
||||
button:not(:disabled),
|
||||
[type="button"]:not(:disabled),
|
||||
[type="reset"]:not(:disabled),
|
||||
[type="submit"]:not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button::-moz-focus-inner,
|
||||
[type="button"]::-moz-focus-inner,
|
||||
[type="reset"]::-moz-focus-inner,
|
||||
[type="submit"]::-moz-focus-inner {
|
||||
padding: 0;
|
||||
border-style: none;
|
||||
}
|
||||
|
||||
input[type="radio"],
|
||||
input[type="checkbox"] {
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
input[type="date"],
|
||||
input[type="time"],
|
||||
input[type="datetime-local"],
|
||||
input[type="month"] {
|
||||
-webkit-appearance: listbox;
|
||||
}
|
||||
|
||||
textarea {
|
||||
overflow: auto;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
fieldset {
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
legend {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
padding: 0;
|
||||
margin-bottom: .5rem;
|
||||
font-size: 1.5rem;
|
||||
line-height: inherit;
|
||||
color: inherit;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
progress {
|
||||
vertical-align: baseline;
|
||||
}
|
||||
|
||||
[type="number"]::-webkit-inner-spin-button,
|
||||
[type="number"]::-webkit-outer-spin-button {
|
||||
height: auto;
|
||||
}
|
||||
|
||||
[type="search"] {
|
||||
outline-offset: -2px;
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
[type="search"]::-webkit-search-decoration {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
::-webkit-file-upload-button {
|
||||
font: inherit;
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
|
||||
output {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
summary {
|
||||
display: list-item;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
template {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
/*# sourceMappingURL=bootstrap-reboot.css.map */
|
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.css.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
8
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css
vendored
Normal file
8
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
/*!
|
||||
* Bootstrap Reboot v4.3.1 (https://getbootstrap.com/)
|
||||
* Copyright 2011-2019 The Bootstrap Authors
|
||||
* Copyright 2011-2019 Twitter, Inc.
|
||||
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
|
||||
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
|
||||
*/*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}
|
||||
/*# sourceMappingURL=bootstrap-reboot.min.css.map */
|
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
10039
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap.css
vendored
Normal file
10039
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap.css
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap.css.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
7
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap.min.css
vendored
Normal file
7
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap.min.css.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/css/bootstrap.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
7013
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.js
vendored
Normal file
7013
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.js.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
7
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.min.js
vendored
Normal file
7
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.min.js.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.min.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
4435
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.js
vendored
Normal file
4435
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.js.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
7
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.min.js
vendored
Normal file
7
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.min.js.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/bootstrap/dist/js/bootstrap.min.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
@ -0,0 +1,12 @@
|
||||
Copyright (c) .NET Foundation. All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
these files except in compliance with the License. You may obtain a copy of the
|
||||
License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software distributed
|
||||
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations under the License.
|
@ -0,0 +1,432 @@
|
||||
// Unobtrusive validation support library for jQuery and jQuery Validate
|
||||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
// @version v3.2.11
|
||||
|
||||
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
|
||||
/*global document: false, jQuery: false */
|
||||
|
||||
(function (factory) {
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
// AMD. Register as an anonymous module.
|
||||
define("jquery.validate.unobtrusive", ['jquery-validation'], factory);
|
||||
} else if (typeof module === 'object' && module.exports) {
|
||||
// CommonJS-like environments that support module.exports
|
||||
module.exports = factory(require('jquery-validation'));
|
||||
} else {
|
||||
// Browser global
|
||||
jQuery.validator.unobtrusive = factory(jQuery);
|
||||
}
|
||||
}(function ($) {
|
||||
var $jQval = $.validator,
|
||||
adapters,
|
||||
data_validation = "unobtrusiveValidation";
|
||||
|
||||
function setValidationValues(options, ruleName, value) {
|
||||
options.rules[ruleName] = value;
|
||||
if (options.message) {
|
||||
options.messages[ruleName] = options.message;
|
||||
}
|
||||
}
|
||||
|
||||
function splitAndTrim(value) {
|
||||
return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
|
||||
}
|
||||
|
||||
function escapeAttributeValue(value) {
|
||||
// As mentioned on http://api.jquery.com/category/selectors/
|
||||
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
|
||||
}
|
||||
|
||||
function getModelPrefix(fieldName) {
|
||||
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
|
||||
}
|
||||
|
||||
function appendModelPrefix(value, prefix) {
|
||||
if (value.indexOf("*.") === 0) {
|
||||
value = value.replace("*.", prefix);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function onError(error, inputElement) { // 'this' is the form element
|
||||
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
|
||||
replaceAttrValue = container.attr("data-valmsg-replace"),
|
||||
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
|
||||
|
||||
container.removeClass("field-validation-valid").addClass("field-validation-error");
|
||||
error.data("unobtrusiveContainer", container);
|
||||
|
||||
if (replace) {
|
||||
container.empty();
|
||||
error.removeClass("input-validation-error").appendTo(container);
|
||||
}
|
||||
else {
|
||||
error.hide();
|
||||
}
|
||||
}
|
||||
|
||||
function onErrors(event, validator) { // 'this' is the form element
|
||||
var container = $(this).find("[data-valmsg-summary=true]"),
|
||||
list = container.find("ul");
|
||||
|
||||
if (list && list.length && validator.errorList.length) {
|
||||
list.empty();
|
||||
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
|
||||
|
||||
$.each(validator.errorList, function () {
|
||||
$("<li />").html(this.message).appendTo(list);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function onSuccess(error) { // 'this' is the form element
|
||||
var container = error.data("unobtrusiveContainer");
|
||||
|
||||
if (container) {
|
||||
var replaceAttrValue = container.attr("data-valmsg-replace"),
|
||||
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
|
||||
|
||||
container.addClass("field-validation-valid").removeClass("field-validation-error");
|
||||
error.removeData("unobtrusiveContainer");
|
||||
|
||||
if (replace) {
|
||||
container.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onReset(event) { // 'this' is the form element
|
||||
var $form = $(this),
|
||||
key = '__jquery_unobtrusive_validation_form_reset';
|
||||
if ($form.data(key)) {
|
||||
return;
|
||||
}
|
||||
// Set a flag that indicates we're currently resetting the form.
|
||||
$form.data(key, true);
|
||||
try {
|
||||
$form.data("validator").resetForm();
|
||||
} finally {
|
||||
$form.removeData(key);
|
||||
}
|
||||
|
||||
$form.find(".validation-summary-errors")
|
||||
.addClass("validation-summary-valid")
|
||||
.removeClass("validation-summary-errors");
|
||||
$form.find(".field-validation-error")
|
||||
.addClass("field-validation-valid")
|
||||
.removeClass("field-validation-error")
|
||||
.removeData("unobtrusiveContainer")
|
||||
.find(">*") // If we were using valmsg-replace, get the underlying error
|
||||
.removeData("unobtrusiveContainer");
|
||||
}
|
||||
|
||||
function validationInfo(form) {
|
||||
var $form = $(form),
|
||||
result = $form.data(data_validation),
|
||||
onResetProxy = $.proxy(onReset, form),
|
||||
defaultOptions = $jQval.unobtrusive.options || {},
|
||||
execInContext = function (name, args) {
|
||||
var func = defaultOptions[name];
|
||||
func && $.isFunction(func) && func.apply(form, args);
|
||||
};
|
||||
|
||||
if (!result) {
|
||||
result = {
|
||||
options: { // options structure passed to jQuery Validate's validate() method
|
||||
errorClass: defaultOptions.errorClass || "input-validation-error",
|
||||
errorElement: defaultOptions.errorElement || "span",
|
||||
errorPlacement: function () {
|
||||
onError.apply(form, arguments);
|
||||
execInContext("errorPlacement", arguments);
|
||||
},
|
||||
invalidHandler: function () {
|
||||
onErrors.apply(form, arguments);
|
||||
execInContext("invalidHandler", arguments);
|
||||
},
|
||||
messages: {},
|
||||
rules: {},
|
||||
success: function () {
|
||||
onSuccess.apply(form, arguments);
|
||||
execInContext("success", arguments);
|
||||
}
|
||||
},
|
||||
attachValidation: function () {
|
||||
$form
|
||||
.off("reset." + data_validation, onResetProxy)
|
||||
.on("reset." + data_validation, onResetProxy)
|
||||
.validate(this.options);
|
||||
},
|
||||
validate: function () { // a validation function that is called by unobtrusive Ajax
|
||||
$form.validate();
|
||||
return $form.valid();
|
||||
}
|
||||
};
|
||||
$form.data(data_validation, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
$jQval.unobtrusive = {
|
||||
adapters: [],
|
||||
|
||||
parseElement: function (element, skipAttach) {
|
||||
/// <summary>
|
||||
/// Parses a single HTML element for unobtrusive validation attributes.
|
||||
/// </summary>
|
||||
/// <param name="element" domElement="true">The HTML element to be parsed.</param>
|
||||
/// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
|
||||
/// validation to the form. If parsing just this single element, you should specify true.
|
||||
/// If parsing several elements, you should specify false, and manually attach the validation
|
||||
/// to the form when you are finished. The default is false.</param>
|
||||
var $element = $(element),
|
||||
form = $element.parents("form")[0],
|
||||
valInfo, rules, messages;
|
||||
|
||||
if (!form) { // Cannot do client-side validation without a form
|
||||
return;
|
||||
}
|
||||
|
||||
valInfo = validationInfo(form);
|
||||
valInfo.options.rules[element.name] = rules = {};
|
||||
valInfo.options.messages[element.name] = messages = {};
|
||||
|
||||
$.each(this.adapters, function () {
|
||||
var prefix = "data-val-" + this.name,
|
||||
message = $element.attr(prefix),
|
||||
paramValues = {};
|
||||
|
||||
if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
|
||||
prefix += "-";
|
||||
|
||||
$.each(this.params, function () {
|
||||
paramValues[this] = $element.attr(prefix + this);
|
||||
});
|
||||
|
||||
this.adapt({
|
||||
element: element,
|
||||
form: form,
|
||||
message: message,
|
||||
params: paramValues,
|
||||
rules: rules,
|
||||
messages: messages
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
$.extend(rules, { "__dummy__": true });
|
||||
|
||||
if (!skipAttach) {
|
||||
valInfo.attachValidation();
|
||||
}
|
||||
},
|
||||
|
||||
parse: function (selector) {
|
||||
/// <summary>
|
||||
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
|
||||
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
|
||||
/// attribute values.
|
||||
/// </summary>
|
||||
/// <param name="selector" type="String">Any valid jQuery selector.</param>
|
||||
|
||||
// $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one
|
||||
// element with data-val=true
|
||||
var $selector = $(selector),
|
||||
$forms = $selector.parents()
|
||||
.addBack()
|
||||
.filter("form")
|
||||
.add($selector.find("form"))
|
||||
.has("[data-val=true]");
|
||||
|
||||
$selector.find("[data-val=true]").each(function () {
|
||||
$jQval.unobtrusive.parseElement(this, true);
|
||||
});
|
||||
|
||||
$forms.each(function () {
|
||||
var info = validationInfo(this);
|
||||
if (info) {
|
||||
info.attachValidation();
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
adapters = $jQval.unobtrusive.adapters;
|
||||
|
||||
adapters.add = function (adapterName, params, fn) {
|
||||
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
|
||||
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
|
||||
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
|
||||
/// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
|
||||
/// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
|
||||
/// mmmm is the parameter name).</param>
|
||||
/// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
|
||||
/// attributes into jQuery Validate rules and/or messages.</param>
|
||||
/// <returns type="jQuery.validator.unobtrusive.adapters" />
|
||||
if (!fn) { // Called with no params, just a function
|
||||
fn = params;
|
||||
params = [];
|
||||
}
|
||||
this.push({ name: adapterName, params: params, adapt: fn });
|
||||
return this;
|
||||
};
|
||||
|
||||
adapters.addBool = function (adapterName, ruleName) {
|
||||
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
|
||||
/// the jQuery Validate validation rule has no parameter values.</summary>
|
||||
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
|
||||
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
|
||||
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
|
||||
/// of adapterName will be used instead.</param>
|
||||
/// <returns type="jQuery.validator.unobtrusive.adapters" />
|
||||
return this.add(adapterName, function (options) {
|
||||
setValidationValues(options, ruleName || adapterName, true);
|
||||
});
|
||||
};
|
||||
|
||||
adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
|
||||
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
|
||||
/// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
|
||||
/// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
|
||||
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
|
||||
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
|
||||
/// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
|
||||
/// have a minimum value.</param>
|
||||
/// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
|
||||
/// have a maximum value.</param>
|
||||
/// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
|
||||
/// have both a minimum and maximum value.</param>
|
||||
/// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
|
||||
/// contains the minimum value. The default is "min".</param>
|
||||
/// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
|
||||
/// contains the maximum value. The default is "max".</param>
|
||||
/// <returns type="jQuery.validator.unobtrusive.adapters" />
|
||||
return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
|
||||
var min = options.params.min,
|
||||
max = options.params.max;
|
||||
|
||||
if (min && max) {
|
||||
setValidationValues(options, minMaxRuleName, [min, max]);
|
||||
}
|
||||
else if (min) {
|
||||
setValidationValues(options, minRuleName, min);
|
||||
}
|
||||
else if (max) {
|
||||
setValidationValues(options, maxRuleName, max);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
adapters.addSingleVal = function (adapterName, attribute, ruleName) {
|
||||
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
|
||||
/// the jQuery Validate validation rule has a single value.</summary>
|
||||
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
|
||||
/// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
|
||||
/// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
|
||||
/// The default is "val".</param>
|
||||
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
|
||||
/// of adapterName will be used instead.</param>
|
||||
/// <returns type="jQuery.validator.unobtrusive.adapters" />
|
||||
return this.add(adapterName, [attribute || "val"], function (options) {
|
||||
setValidationValues(options, ruleName || adapterName, options.params[attribute]);
|
||||
});
|
||||
};
|
||||
|
||||
$jQval.addMethod("__dummy__", function (value, element, params) {
|
||||
return true;
|
||||
});
|
||||
|
||||
$jQval.addMethod("regex", function (value, element, params) {
|
||||
var match;
|
||||
if (this.optional(element)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
match = new RegExp(params).exec(value);
|
||||
return (match && (match.index === 0) && (match[0].length === value.length));
|
||||
});
|
||||
|
||||
$jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
|
||||
var match;
|
||||
if (nonalphamin) {
|
||||
match = value.match(/\W/g);
|
||||
match = match && match.length >= nonalphamin;
|
||||
}
|
||||
return match;
|
||||
});
|
||||
|
||||
if ($jQval.methods.extension) {
|
||||
adapters.addSingleVal("accept", "mimtype");
|
||||
adapters.addSingleVal("extension", "extension");
|
||||
} else {
|
||||
// for backward compatibility, when the 'extension' validation method does not exist, such as with versions
|
||||
// of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
|
||||
// validating the extension, and ignore mime-type validations as they are not supported.
|
||||
adapters.addSingleVal("extension", "extension", "accept");
|
||||
}
|
||||
|
||||
adapters.addSingleVal("regex", "pattern");
|
||||
adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
|
||||
adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
|
||||
adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
|
||||
adapters.add("equalto", ["other"], function (options) {
|
||||
var prefix = getModelPrefix(options.element.name),
|
||||
other = options.params.other,
|
||||
fullOtherName = appendModelPrefix(other, prefix),
|
||||
element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
|
||||
|
||||
setValidationValues(options, "equalTo", element);
|
||||
});
|
||||
adapters.add("required", function (options) {
|
||||
// jQuery Validate equates "required" with "mandatory" for checkbox elements
|
||||
if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
|
||||
setValidationValues(options, "required", true);
|
||||
}
|
||||
});
|
||||
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
|
||||
var value = {
|
||||
url: options.params.url,
|
||||
type: options.params.type || "GET",
|
||||
data: {}
|
||||
},
|
||||
prefix = getModelPrefix(options.element.name);
|
||||
|
||||
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
|
||||
var paramName = appendModelPrefix(fieldName, prefix);
|
||||
value.data[paramName] = function () {
|
||||
var field = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']");
|
||||
// For checkboxes and radio buttons, only pick up values from checked fields.
|
||||
if (field.is(":checkbox")) {
|
||||
return field.filter(":checked").val() || field.filter(":hidden").val() || '';
|
||||
}
|
||||
else if (field.is(":radio")) {
|
||||
return field.filter(":checked").val() || '';
|
||||
}
|
||||
return field.val();
|
||||
};
|
||||
});
|
||||
|
||||
setValidationValues(options, "remote", value);
|
||||
});
|
||||
adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
|
||||
if (options.params.min) {
|
||||
setValidationValues(options, "minlength", options.params.min);
|
||||
}
|
||||
if (options.params.nonalphamin) {
|
||||
setValidationValues(options, "nonalphamin", options.params.nonalphamin);
|
||||
}
|
||||
if (options.params.regex) {
|
||||
setValidationValues(options, "regex", options.params.regex);
|
||||
}
|
||||
});
|
||||
adapters.add("fileextensions", ["extensions"], function (options) {
|
||||
setValidationValues(options, "extension", options.params.extensions);
|
||||
});
|
||||
|
||||
$(function () {
|
||||
$jQval.unobtrusive.parse(document);
|
||||
});
|
||||
|
||||
return $jQval.unobtrusive;
|
||||
}));
|
File diff suppressed because one or more lines are too long
@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
=====================
|
||||
|
||||
Copyright Jörn Zaefferer
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
1158
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery-validation/dist/additional-methods.js
vendored
Normal file
1158
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery-validation/dist/additional-methods.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
4
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery-validation/dist/additional-methods.min.js
vendored
Normal file
4
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery-validation/dist/additional-methods.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1601
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery-validation/dist/jquery.validate.js
vendored
Normal file
1601
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery-validation/dist/jquery.validate.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
4
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery-validation/dist/jquery.validate.min.js
vendored
Normal file
4
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery-validation/dist/jquery.validate.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@ -0,0 +1,36 @@
|
||||
Copyright JS Foundation and other contributors, https://js.foundation/
|
||||
|
||||
This software consists of voluntary contributions made by many
|
||||
individuals. For exact contribution history, see the revision history
|
||||
available at https://github.com/jquery/jquery
|
||||
|
||||
The following license applies to all parts of this software except as
|
||||
documented below:
|
||||
|
||||
====
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
====
|
||||
|
||||
All files located in the node_modules and external directories are
|
||||
externally maintained libraries used by this software which have their
|
||||
own licenses; we recommend you read them, as their terms may differ from
|
||||
the terms above.
|
10364
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery/dist/jquery.js
vendored
Normal file
10364
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery/dist/jquery.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
2
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery/dist/jquery.min.js
vendored
Normal file
2
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery/dist/jquery.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery/dist/jquery.min.map
vendored
Normal file
1
ThAmCo-Products/ThAmCo.Products/wwwroot/lib/jquery/dist/jquery.min.map
vendored
Normal file
File diff suppressed because one or more lines are too long
35
ThAmCo-Products/azure-pipelines.yml
Normal file
35
ThAmCo-Products/azure-pipelines.yml
Normal file
@ -0,0 +1,35 @@
|
||||
trigger:
|
||||
- master
|
||||
- develop
|
||||
|
||||
pr:
|
||||
- master
|
||||
- develop
|
||||
|
||||
pool: Default
|
||||
|
||||
variables:
|
||||
buildConfiguration: 'Release'
|
||||
|
||||
steps:
|
||||
- script: dotnet build --configuration $(buildConfiguration)
|
||||
displayName: 'Building $(buildConfiguration)'
|
||||
- task: DotNetCoreCLI@2
|
||||
displayName: 'Testing $(buildConfiguration)'
|
||||
inputs:
|
||||
command: test
|
||||
projects: '**/*Tests/*.csproj'
|
||||
arguments: '--configuration $(buildConfiguration)'
|
||||
|
||||
- task: DotNetCoreCLI@2
|
||||
displayName: 'Publishing $(buildConfiguration)'
|
||||
inputs:
|
||||
command: publish
|
||||
publishWebProjects: True
|
||||
arguments: '--configuration $(buildConfiguration) --output "$(Build.ArtifactStagingDirectory)"'
|
||||
zipAfterPublish: True
|
||||
- task: PublishBuildArtifacts@1
|
||||
displayName: 'Storing Build Artifact'
|
||||
inputs:
|
||||
pathtoPublish: '$(Build.ArtifactStagingDirectory)'
|
||||
artifactName: 'ThAmCo-Products'
|
72
ThAmCo-Products/readme.md
Normal file
72
ThAmCo-Products/readme.md
Normal file
@ -0,0 +1,72 @@
|
||||
ThAmCo.Products
|
||||
=====
|
||||
| Master | Develop | CodeFactor
|
||||
|--|--|--|
|
||||
| [![Build Status](https://dev.azure.com/Stedoss/ThAmCo.Products/_apis/build/status/Don-t-Fail.ThAmCo-Products?branchName=master)](https://dev.azure.com/Stedoss/ThAmCo.Products/_build/latest?definitionId=2&branchName=master) | [![Build Status](https://dev.azure.com/Stedoss/ThAmCo.Products/_apis/build/status/Don-t-Fail.ThAmCo-Products?branchName=develop)](https://dev.azure.com/Stedoss/ThAmCo.Products/_build/latest?definitionId=2&branchName=develop) | [![CodeFactor](https://www.codefactor.io/repository/github/don-t-fail/thamco-products/badge)](https://www.codefactor.io/repository/github/don-t-fail/thamco-products)
|
||||
|
||||
|
||||
## Overview
|
||||
This web service handles products within the ThAmCo project. Stores product data and is the main place where products are shown to users.
|
||||
|
||||
## Branch Management
|
||||
The main branch is `Master`, and should only be committed to/pushed to when the service has been confirmed working (this includes passing tests and human testing). All pushes to `Master` will be pushed into production.
|
||||
`Develop` is where features may be added (only by means of feature branches), tests should all pass when being pushed to this branch, however some things may not work fully.
|
||||
`Feature` branches are assumed unstable, and are actively being worked on. CI does not build these branches.
|
||||
|
||||
# Assignment Checklist
|
||||
## System Architecture
|
||||
|
||||
### Peer Point Distribution
|
||||
Dylan: 7
|
||||
Steven: 6
|
||||
|
||||
## System Implementation
|
||||
### Security Topics
|
||||
Due to no central Login/Accounts for the project, please view the Accounts controller in `Controllers/AccountController.cs` as this is where authentication takes place within this service.
|
||||
|
||||
### Data Distribution
|
||||
Data Distribution within this project mainly relies on making HTTP requests. Little information is duplicated across services (particularly saved to databases) to try to make data as up to date as possible. Due to this, pages may take a little longer to load (or fail to load), however these would generally occur for Staff and Admin pages, as customer pages are optimised to display as much data as they can; loading pages without some elements (like reviews).
|
||||
|
||||
### Network Resilience
|
||||
For network resilience, `Polly` is used for creating a HTTPClient factory as a service in the project. There are two client builders defined within `Startup.cs`, these two being `StandardRequest` and `ReviewRequest`. These contain different properties, `StandardRequest` deals with most of the backend requests that aren't too reliant of customer pages. The main requests sent from the customer pages are retrieving `Reviews` and `Stock`, if these services are unable to be reached after the first try, product data will be displayed without this extra data. This allows for products to still be viewed, with only slight delays to page loading times. These HTTPFactories can be seen at `lines 43-54`, the two containing different http request rules.
|
||||
|
||||
### Tools and Frameworks
|
||||
Multiple tools and frameworks are used within this project. These are listed below.
|
||||
#### Language and Environment
|
||||
* C# with ASPNET Core version 2.2.
|
||||
* Visual Studio 2019 (with ReSharper) was used for most of the development, debugging builds were usually ran in ISS.
|
||||
* IntelliJ Rider was also used as it has a very good testing interface, along with ReSharper built in.
|
||||
* Visual Studio Code was used to write readme files, along with some tests to make sure the `dotnet test` functionality worked within the project.
|
||||
* Windows 10 - Development Environment.
|
||||
* Linux Ubuntu and Debian, including Docker.
|
||||
* MSSQL Database. (Running in Docker for production).
|
||||
* GitKraken was mainly used as the Git client for this project, however GitHub Desktop was also used for some commits.
|
||||
* CodeFactor was used just to check code quality on pull request.
|
||||
|
||||
#### Testing
|
||||
* Visual Studio Test Tools (Microsoft.VisualStudio.TestTools.UnitTesting). Testing can be run by going to the root directory of this project and using
|
||||
>dotnet test
|
||||
|
||||
* Moq is used for a HttpClient mock. This can be seen in `ThAmCo.Products.Tests/Controllers/ProductsControllerTests.cs lines 68-79`. These get given data depending on the test, as can be seen at the start of the test `GetProductIndex_AllValid_AllReturned() lines 84-104`.
|
||||
* Test doubles (test data) are available within the test cs file (`ThAmCo.Products.Tests/Controllers/ProductsControllerTests.cs`), and are inside of their own `Data` class. These are located at the start of the file, in `lines 25-66`. These were then used within the `ThAmCo.Products/Data/ProductsContext/MockProductsContext.cs` to act as the context fake.
|
||||
* ARC (Advanced REST Client) and Postman were used to test API endpoints within this project. They were useful to test endpoints within my own services, along with creating the DTOs required for retrieving data from other services.
|
||||
|
||||
#### Continuous Integration
|
||||
* Azure Pipelines running on a Windows agent. The Azure Pipelines configuration can be found in the root directory, in `azure-pipelines.yml`. A build is scheduled when a commit is pushed to the Master or Develop branch. A build is also scheduled when a pull request is made to the Develop branch, and is checked by means of a Github Status Check. This means when a pull request is made, Github requests a build from Azure Pipelines, and will now allow the branch to be merged unless the build passes.
|
||||
* AppVeyor was used for a short period as an addition to Azure Pipelines, however was removed due to compatibility issues with build images.
|
||||
|
||||
### Configuring Deployment
|
||||
* A `Dockerfile` is included within this repo as a means of deploying this service. This `Dockerfile` is configured to be used with the produced artefact from Azure Pipelines, and has not been designed to be used for debugging, building, or run directly inside of the repo. To deploy the docker image, please follow these instructions:
|
||||
>Take produced artefact from Azure Pipelines (ThAmCo-Products.zip)
|
||||
Extract to a folder called Products
|
||||
Place Dockerfile one up from the Product directory
|
||||
docker build thamco-products .
|
||||
|
||||
This should produce a docker image that can then be launched.
|
||||
`Docker-compose` would also be used when all services are available with their dockerfile. This would be the ideal way of deploying all services at once, along with their database.
|
||||
|
||||
## System Demonstration
|
||||
|
||||
### Peer Point Distribution
|
||||
Steven: 7
|
||||
Dylan: 6
|
490
ThAmCo-Stock/.gitignore
vendored
Normal file
490
ThAmCo-Stock/.gitignore
vendored
Normal file
@ -0,0 +1,490 @@
|
||||
|
||||
# Created by https://www.gitignore.io/api/dotnetcore,aspnetcore,visualstudio
|
||||
# Edit at https://www.gitignore.io/?templates=dotnetcore,aspnetcore,visualstudio
|
||||
|
||||
### ASPNETCore ###
|
||||
## 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/
|
||||
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
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# 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
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/
|
||||
|
||||
### DotnetCore ###
|
||||
# .NET Core build folders
|
||||
/bin
|
||||
/obj
|
||||
|
||||
# Common node modules locations
|
||||
/node_modules
|
||||
/wwwroot/node_modules
|
||||
|
||||
|
||||
### VisualStudio ###
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
|
||||
# NUnit
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_h.h
|
||||
*.iobj
|
||||
*.ipdb
|
||||
*_wpftmp.csproj
|
||||
|
||||
# Chutzpah Test files
|
||||
|
||||
# Visual C++ cache files
|
||||
|
||||
# Visual Studio profiler
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
|
||||
# TeamCity is a build add-in
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Visual Studio code coverage results
|
||||
|
||||
# NCrunch
|
||||
|
||||
# MightyMoose
|
||||
|
||||
# Web workbench (sass)
|
||||
|
||||
# Installshield output folder
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
|
||||
# Click-Once directory
|
||||
|
||||
# Publish Web Output
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
|
||||
# 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
|
||||
|
||||
# NuGet Packages
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
|
||||
# Windows Store app package directories and files
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
|
||||
# RIA/Silverlight projects
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
|
||||
# Visual Studio 6 build log
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
|
||||
# Paket dependency manager
|
||||
|
||||
# FAKE - F# Make
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# End of https://www.gitignore.io/api/dotnetcore,aspnetcore,visualstudio
|
5
ThAmCo-Stock/Dockerfile
Normal file
5
ThAmCo-Stock/Dockerfile
Normal file
@ -0,0 +1,5 @@
|
||||
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim
|
||||
COPY stock/ /app
|
||||
WORKDIR /app
|
||||
EXPOSE 80
|
||||
ENTRYPOINT ["dotnet", "ThAmCo.Stock.dll"]
|
@ -0,0 +1,701 @@
|
||||
using System.Collections;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ThAmCo.Stock.Controllers;
|
||||
using ThAmCo.Stock.Data;
|
||||
using ThAmCo.Stock.Data.StockContext;
|
||||
using ThAmCo.Stock.Models.Dto;
|
||||
using Moq;
|
||||
using System.Net.Http;
|
||||
using Moq.Protected;
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json;
|
||||
using System.Text;
|
||||
using ThAmCo.Stock.Models.ViewModel;
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace ThAmCo.Stock.Tests.Controllers
|
||||
{
|
||||
[TestClass]
|
||||
public class StockControllerTests
|
||||
{
|
||||
private static class Data
|
||||
{
|
||||
public static List<ProductStock> ProductStocks() => new List<ProductStock>
|
||||
{
|
||||
new ProductStock { Id = 1, Stock = 10, PriceId = 1, ProductId = 436 },
|
||||
new ProductStock { Id = 2, Stock = 0, PriceId = 3, ProductId = 326 },
|
||||
new ProductStock { Id = 3, Stock = 4, PriceId = 4, ProductId = 273 },
|
||||
new ProductStock { Id = 4, Stock = 43, PriceId = 6, ProductId = 456 },
|
||||
new ProductStock { Id = 5, Stock = 2, PriceId = 7, ProductId = 32 },
|
||||
new ProductStock { Id = 6, Stock = 14, PriceId = 8, ProductId = 33 },
|
||||
new ProductStock { Id = 7, Stock = 1, PriceId = 9, ProductId = 21 }
|
||||
};
|
||||
|
||||
public static List<Price> Prices() => new List<Price>
|
||||
{
|
||||
new Price { Id = 1, ProductStockId = 1, ProductPrice = 8.99 },
|
||||
new Price { Id = 2, ProductStockId = 2, ProductPrice = 24.99 },
|
||||
new Price { Id = 3, ProductStockId = 2, ProductPrice = 19.99 },
|
||||
new Price { Id = 4, ProductStockId = 3, ProductPrice = 54.56 },
|
||||
new Price { Id = 5, ProductStockId = 4, ProductPrice = 73.00 },
|
||||
new Price { Id = 6, ProductStockId = 4, ProductPrice = 29.99 },
|
||||
new Price { Id = 7, ProductStockId = 5, ProductPrice = 13.65 },
|
||||
new Price { Id = 8, ProductStockId = 6, ProductPrice = 3.99 },
|
||||
new Price { Id = 9, ProductStockId = 7, ProductPrice = 5.67}
|
||||
};
|
||||
|
||||
public static List<ProductStockDto> ProductStockDtos() => new List<ProductStockDto>
|
||||
{
|
||||
new ProductStockDto { ProductStock = ProductStocks()[0], Price = Prices()[0] },
|
||||
new ProductStockDto { ProductStock = ProductStocks()[1], Price = Prices()[2] },
|
||||
new ProductStockDto { ProductStock = ProductStocks()[2], Price = Prices()[3] },
|
||||
new ProductStockDto { ProductStock = ProductStocks()[3], Price = Prices()[5] },
|
||||
new ProductStockDto { ProductStock = ProductStocks()[4], Price = Prices()[6] },
|
||||
new ProductStockDto { ProductStock = ProductStocks()[5], Price = Prices()[7] },
|
||||
new ProductStockDto { ProductStock = ProductStocks()[6], Price = Prices()[8] }
|
||||
};
|
||||
|
||||
public static List<VendorProductDto> VendorProducts() => new List<VendorProductDto>
|
||||
{
|
||||
new VendorProductDto { Id = 1, Ean = "Sample Ean 1", CategoryId = 3, CategoryName = "Sample Category Name 1", BrandId = 5, BrandName = "Sample Brand Name 1", Name = "Sample Name 1", Description = "Sample Description 1", Price = 9.1, InStock = true, ExpectedRestock = null },
|
||||
new VendorProductDto { Id = 2, Ean = "Sample Ean 2", CategoryId = 4, CategoryName = "Sample Category Name 2", BrandId = 6, BrandName = "Sample Brand Name 2", Name = "Sample Name 2", Description = "Sample Description 2", Price = 8.16, InStock = true, ExpectedRestock = null },
|
||||
new VendorProductDto { Id = 3, Ean = "Sample Ean 3", CategoryId = 5, CategoryName = "Sample Category Name 3", BrandId = 7, BrandName = "Sample Brand Name 3", Name = "Sample Name 3", Description = "Sample Description 3", Price = 1.9, InStock = true, ExpectedRestock = null },
|
||||
new VendorProductDto { Id = 4, Ean = "Sample Ean 4", CategoryId = 3, CategoryName = "Sample Category Name 4", BrandId = 5, BrandName = "Sample Brand Name 4", Name = "Sample Name 4", Description = "Sample Description 4", Price = 23.21, InStock = true, ExpectedRestock = null }
|
||||
};
|
||||
}
|
||||
|
||||
private const int OutOfBoundsId = 8;
|
||||
private const int NegativeId = -1;
|
||||
|
||||
private Mock<HttpMessageHandler> CreateHttpMock(HttpResponseMessage expected)
|
||||
{
|
||||
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
|
||||
mock.Protected()
|
||||
.Setup<Task<HttpResponseMessage>>(
|
||||
"SendAsync",
|
||||
ItExpr.IsAny<HttpRequestMessage>(),
|
||||
ItExpr.IsAny<CancellationToken>())
|
||||
.ReturnsAsync(expected)
|
||||
.Verifiable();
|
||||
return mock;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetAll_AllValid_AllReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
|
||||
var result = await controller.ProductStocks();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result.Result as OkObjectResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var enumerableResult = objectResult.Value as IEnumerable<ProductStockDto>;
|
||||
Assert.IsNotNull(enumerableResult);
|
||||
var listResult = enumerableResult.ToList();
|
||||
foreach (var p in listResult)
|
||||
{
|
||||
Assert.AreEqual(p.Price.Date, Data.Prices()[p.Price.Id - 1].Date);
|
||||
Assert.AreEqual(p.Price.Id, Data.Prices()[p.Price.Id - 1].Id);
|
||||
Assert.AreEqual(p.Price.ProductPrice, Data.Prices()[p.Price.Id - 1].ProductPrice);
|
||||
Assert.AreEqual(p.Price.ProductStockId, Data.Prices()[p.Price.Id - 1].ProductStockId);
|
||||
|
||||
Assert.AreEqual(p.ProductStock.Id, Data.ProductStocks()[p.ProductStock.Id - 1].Id);
|
||||
Assert.AreEqual(p.ProductStock.Stock, Data.ProductStocks()[p.ProductStock.Id - 1].Stock);
|
||||
Assert.AreEqual(p.ProductStock.PriceId, Data.ProductStocks()[p.ProductStock.Id - 1].PriceId);
|
||||
Assert.AreEqual(p.ProductStock.ProductId, Data.ProductStocks()[p.ProductStock.Id - 1].ProductId);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetAll_EmptyModel_EmptyListReturned()
|
||||
{
|
||||
var context = new MockStockContext(new List<ProductStock>(), new List<Price>(), null);
|
||||
var controller = new StockController(context, null);
|
||||
|
||||
var result = await controller.ProductStocks();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result.Result as OkObjectResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var enumerableResult = objectResult.Value as IEnumerable<ProductStockDto>;
|
||||
Assert.IsNotNull(enumerableResult);
|
||||
var listResult = enumerableResult.ToList();
|
||||
Assert.AreEqual(listResult.Count, 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetDetails_ValidIdPassed_CorrectAndValidObjectReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = 2;
|
||||
|
||||
var result = await controller.Details(id);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result.Result as OkObjectResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var returnedResult = objectResult.Value as ProductStockDetailsDto;
|
||||
Assert.IsNotNull(returnedResult);
|
||||
|
||||
Assert.AreEqual(returnedResult.ProductID, Data.ProductStocks()[id - 1].ProductId);
|
||||
Assert.AreEqual(returnedResult.Price, Data.Prices().FirstOrDefault( p => p.Id == Data.ProductStocks()[id - 1].PriceId)?.ProductPrice);
|
||||
Assert.AreEqual(returnedResult.Stock, Data.ProductStocks()[id - 1].Stock);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetDetails_OutOfBoundsPositiveId_NotFoundReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = OutOfBoundsId;
|
||||
|
||||
var result = await controller.Details(id);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result.Result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetDetails_OutOfBoundsNegativeId_NotFoundReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = NegativeId;
|
||||
|
||||
var result = await controller.Details(id);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result.Result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task PriceHistory_ValidIdPassed_CorrectAndValidObjectReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = 1;
|
||||
|
||||
var result = await controller.PriceHistory(id);
|
||||
var validPrices = Data.Prices().Where(p => p.ProductStockId == id).ToList();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result.Result as OkObjectResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var returnedResult = objectResult.Value as ProductStockPricingHistoryDto;
|
||||
Assert.IsNotNull(returnedResult);
|
||||
|
||||
Assert.AreEqual(returnedResult.ProductID, Data.ProductStocks()[id - 1].ProductId);
|
||||
Assert.AreEqual(returnedResult.Stock, Data.ProductStocks()[id - 1].Stock);
|
||||
Assert.AreEqual(returnedResult.Prices.Count, validPrices.Count);
|
||||
foreach (var prices in returnedResult.Prices)
|
||||
{
|
||||
Assert.AreEqual(prices.Id, validPrices.FirstOrDefault(p => p.Id == prices.Id)?.Id);
|
||||
Assert.AreEqual(prices.Date, validPrices.FirstOrDefault(p => p.Id == prices.Id)?.Date);
|
||||
Assert.AreEqual(prices.ProductPrice, validPrices.FirstOrDefault(p => p.Id == prices.Id)?.ProductPrice);
|
||||
Assert.AreEqual(prices.ProductStockId, validPrices.FirstOrDefault(p => p.Id == prices.Id)?.ProductStockId);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task PriceHistory_OutOfBoundsPositiveId_NotFoundReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = OutOfBoundsId;
|
||||
|
||||
var result = await controller.PriceHistory(id);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result.Result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task PriceHistory_OutOfBoundsNegativeId_NotFoundReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = NegativeId;
|
||||
|
||||
var result = await controller.PriceHistory(id);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result.Result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Low_ValidCountPassedLowerThanDefault_CorrectAndValidObjectReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int count = 4;
|
||||
|
||||
var result = controller.Low(count);
|
||||
var expectedResult = Data.ProductStockDtos().OrderBy(ps => ps.ProductStock.Stock).Take(count).ToList();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var priceResult = result.Result as ViewResult;
|
||||
Assert.IsNotNull(priceResult);
|
||||
var objectResult = priceResult.Model as IEnumerable<ProductStockDto>;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var returnedListResult = objectResult.ToList();
|
||||
Assert.AreEqual(returnedListResult.Count, count);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
Assert.AreEqual(returnedListResult[i].Price.Date, expectedResult[i].Price.Date);
|
||||
Assert.AreEqual(returnedListResult[i].Price.Id, expectedResult[i].Price.Id);
|
||||
Assert.AreEqual(returnedListResult[i].Price.ProductPrice, expectedResult[i].Price.ProductPrice);
|
||||
Assert.AreEqual(returnedListResult[i].Price.ProductStockId, expectedResult[i].Price.ProductStockId);
|
||||
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.Id, expectedResult[i].ProductStock.Id);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.Stock, expectedResult[i].ProductStock.Stock);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.PriceId, expectedResult[i].ProductStock.PriceId);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.ProductId, expectedResult[i].ProductStock.ProductId);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Low_ValidCountPassedHigherThanDefault_CorrectAndValidObjectReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int count = 6;
|
||||
|
||||
var result = controller.Low(count);
|
||||
var expectedResult = Data.ProductStockDtos().OrderBy(ps => ps.ProductStock.Stock).Take(count).ToList();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var priceResult = result.Result as ViewResult;
|
||||
Assert.IsNotNull(priceResult);
|
||||
var objectResult = priceResult.Model as IEnumerable<ProductStockDto>;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var returnedListResult = objectResult.ToList();
|
||||
Assert.AreEqual(returnedListResult.Count, count);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
Assert.AreEqual(returnedListResult[i].Price.Date, expectedResult[i].Price.Date);
|
||||
Assert.AreEqual(returnedListResult[i].Price.Id, expectedResult[i].Price.Id);
|
||||
Assert.AreEqual(returnedListResult[i].Price.ProductPrice, expectedResult[i].Price.ProductPrice);
|
||||
Assert.AreEqual(returnedListResult[i].Price.ProductStockId, expectedResult[i].Price.ProductStockId);
|
||||
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.Id, expectedResult[i].ProductStock.Id);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.Stock, expectedResult[i].ProductStock.Stock);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.PriceId, expectedResult[i].ProductStock.PriceId);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.ProductId, expectedResult[i].ProductStock.ProductId);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Low_NullValuePassed_DefaultAmountCorrectAndValidObjectsReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int count = 5;
|
||||
|
||||
var result = controller.Low(null);
|
||||
var expectedResult = Data.ProductStockDtos().OrderBy(ps => ps.ProductStock.Stock).Take(count).ToList();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var priceResult = result.Result as ViewResult;
|
||||
Assert.IsNotNull(priceResult);
|
||||
var objectResult = priceResult.Model as IEnumerable<ProductStockDto>;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var returnedListResult = objectResult.ToList();
|
||||
Assert.AreEqual(returnedListResult.Count, count);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
Assert.AreEqual(returnedListResult[i].Price.Date, expectedResult[i].Price.Date);
|
||||
Assert.AreEqual(returnedListResult[i].Price.Id, expectedResult[i].Price.Id);
|
||||
Assert.AreEqual(returnedListResult[i].Price.ProductPrice, expectedResult[i].Price.ProductPrice);
|
||||
Assert.AreEqual(returnedListResult[i].Price.ProductStockId, expectedResult[i].Price.ProductStockId);
|
||||
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.Id, expectedResult[i].ProductStock.Id);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.Stock, expectedResult[i].ProductStock.Stock);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.PriceId, expectedResult[i].ProductStock.PriceId);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.ProductId, expectedResult[i].ProductStock.ProductId);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Low_OutOfBoundsCountPassed_AllValuesReturnedCorrectly()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int count = OutOfBoundsId;
|
||||
|
||||
var result = controller.Low(OutOfBoundsId);
|
||||
var expectedResult = Data.ProductStockDtos().OrderBy(ps => ps.ProductStock.Stock).Take(count).ToList();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var priceResult = result.Result as ViewResult;
|
||||
Assert.IsNotNull(priceResult);
|
||||
var objectResult = priceResult.Model as IEnumerable<ProductStockDto>;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var returnedListResult = objectResult.ToList();
|
||||
Assert.AreEqual(returnedListResult.Count, expectedResult.Count);
|
||||
|
||||
for (int i = 0; i < expectedResult.Count; i++)
|
||||
{
|
||||
Assert.AreEqual(returnedListResult[i].Price.Date, expectedResult[i].Price.Date);
|
||||
Assert.AreEqual(returnedListResult[i].Price.Id, expectedResult[i].Price.Id);
|
||||
Assert.AreEqual(returnedListResult[i].Price.ProductPrice, expectedResult[i].Price.ProductPrice);
|
||||
Assert.AreEqual(returnedListResult[i].Price.ProductStockId, expectedResult[i].Price.ProductStockId);
|
||||
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.Id, expectedResult[i].ProductStock.Id);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.Stock, expectedResult[i].ProductStock.Stock);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.PriceId, expectedResult[i].ProductStock.PriceId);
|
||||
Assert.AreEqual(returnedListResult[i].ProductStock.ProductId, expectedResult[i].ProductStock.ProductId);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Low_OutOfBoundsNegativePassed_NotFoundReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int count = NegativeId;
|
||||
|
||||
var result = controller.Low(count);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var priceResult = result.Result as NotFoundResult;
|
||||
Assert.IsNotNull(priceResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GETAdjustCost_ValidIdPassed_CorrectDataReturnedToView()
|
||||
{
|
||||
const int id = 2;
|
||||
var expectedHttpResponse = new ProductDto { Id = id, Name = "NameTest", Description = "DescriptionTest" };
|
||||
var expectedJson = JsonConvert.SerializeObject(expectedHttpResponse);
|
||||
var expectedResponse = new HttpResponseMessage
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.OK,
|
||||
Content = new StringContent(expectedJson,
|
||||
Encoding.UTF8,
|
||||
"application/json")
|
||||
};
|
||||
var httpClient = new HttpClient(CreateHttpMock(expectedResponse).Object);
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null) { HttpClient = httpClient };
|
||||
|
||||
var expectedResult = Data.ProductStockDtos().FirstOrDefault(psd => psd.ProductStock.Id == id);
|
||||
var result = controller.AdjustCost(id);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var adjustResult = result.Result.Result as ViewResult;
|
||||
Assert.IsNotNull(adjustResult);
|
||||
var adjustProductStock = adjustResult.Model as AdjustCostViewModel;
|
||||
Assert.IsNotNull(adjustProductStock);
|
||||
|
||||
Assert.AreEqual(expectedResult.ProductStock.Id, adjustProductStock.Id);
|
||||
Assert.AreEqual(expectedResult.Price.ProductPrice, adjustProductStock.Cost);
|
||||
Assert.AreEqual(expectedHttpResponse.Name, adjustProductStock.Name);
|
||||
Assert.AreEqual(expectedHttpResponse.Description, adjustProductStock.Description);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GETAdjustCost_InvalidIdPassed_NotFoundReturned()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
|
||||
var resultOutOfBounds = await controller.AdjustCost(OutOfBoundsId);
|
||||
var resultNegative = await controller.AdjustCost(NegativeId);
|
||||
|
||||
Assert.IsNotNull(resultOutOfBounds);
|
||||
var objectResultOutOfBounds = resultOutOfBounds.Result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResultOutOfBounds);
|
||||
|
||||
Assert.IsNotNull(resultNegative);
|
||||
var objectResultNegative = resultNegative.Result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResultNegative);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task POSTAdjustCost_ValidIdAndCostPassed_PriceAddedToDatabaseAndPricePointerChanged()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = 2;
|
||||
const double price = 4.32;
|
||||
|
||||
var previous = Data.ProductStockDtos().FirstOrDefault(ps => ps.ProductStock.Id == id);
|
||||
var expected = previous;
|
||||
expected.Price = new Price { Id = 10, ProductPrice = price, ProductStockId = expected.ProductStock.Id };
|
||||
expected.ProductStock.PriceId = 10;
|
||||
var result = await controller.AdjustCost(id, price);
|
||||
var after = await context.GetProductStockAsync(id);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var okResult = result as OkResult;
|
||||
Assert.IsNotNull(okResult);
|
||||
Assert.AreEqual(previous.ProductStock.Id, after.ProductStock.Id); //Just check Id to make sure the correct product is returned.
|
||||
Assert.AreEqual(expected.Price.Id, after.Price.Id);
|
||||
Assert.AreEqual(expected.Price.ProductPrice, after.Price.ProductPrice);
|
||||
Assert.AreEqual(expected.Price.ProductStockId, after.Price.ProductStockId);
|
||||
Assert.AreEqual(expected.ProductStock.PriceId, after.ProductStock.PriceId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task POSTAdjustCost_OutOfBoundsAndNegativeIdPassed_ReturnNotFound()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const double price = 4.32;
|
||||
|
||||
var resultOutOfBounds = await controller.AdjustCost(OutOfBoundsId, price);
|
||||
var resultNegative = await controller.AdjustCost(NegativeId, price);
|
||||
|
||||
Assert.IsNotNull(resultOutOfBounds);
|
||||
var objectResultOutOfBounds = resultOutOfBounds as NotFoundResult;
|
||||
Assert.IsNotNull(objectResultOutOfBounds);
|
||||
|
||||
Assert.IsNotNull(resultNegative);
|
||||
var objectResultNegative = resultNegative as NotFoundResult;
|
||||
Assert.IsNotNull(objectResultNegative);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task POSTAdjustCost_NegativeCostPassed_ReturnBadRequest()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = 2;
|
||||
const double price = -4.32;
|
||||
|
||||
var result = await controller.AdjustCost(id, price);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as BadRequestResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task POSTAdjustCost_ZeroCostPassed_ReturnBadRequest()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = 2;
|
||||
const double price = 0;
|
||||
|
||||
var result = await controller.AdjustCost(id, price);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as BadRequestResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task VendorProducts_ValidSupplierPassed_ReturnAllSupplierProducts()
|
||||
{
|
||||
var expectedHttpResponse = Data.VendorProducts();
|
||||
var expectedJson = JsonConvert.SerializeObject(expectedHttpResponse);
|
||||
var expectedResponse = new HttpResponseMessage
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.OK,
|
||||
Content = new StringContent(expectedJson,
|
||||
Encoding.UTF8,
|
||||
"application/json")
|
||||
};
|
||||
var httpClient = new HttpClient(CreateHttpMock(expectedResponse).Object);
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null) { HttpClient = httpClient };
|
||||
const string supplier = "undercutters";
|
||||
|
||||
var expected = Data.VendorProducts();
|
||||
var result = await controller.VendorProducts(supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as ViewResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var viewResult = objectResult.Model as VendorProductIndexModel;
|
||||
Assert.IsNotNull(viewResult);
|
||||
var productsResult = viewResult.Products.ToList();
|
||||
Assert.IsNotNull(productsResult);
|
||||
|
||||
Assert.AreEqual(expected.Count, productsResult.Count);
|
||||
for (int i = 0; i < expected.Count; i++)
|
||||
{
|
||||
Assert.AreEqual(expected[i].Id, productsResult[i].Id);
|
||||
Assert.AreEqual(expected[i].BrandId, productsResult[i].BrandId);
|
||||
Assert.AreEqual(expected[i].BrandName, productsResult[i].BrandName);
|
||||
Assert.AreEqual(expected[i].CategoryId, productsResult[i].CategoryId);
|
||||
Assert.AreEqual(expected[i].CategoryName, productsResult[i].CategoryName);
|
||||
Assert.AreEqual(expected[i].Description, productsResult[i].Description);
|
||||
Assert.AreEqual(expected[i].Ean, productsResult[i].Ean);
|
||||
Assert.AreEqual(expected[i].ExpectedRestock, productsResult[i].ExpectedRestock);
|
||||
Assert.AreEqual(expected[i].InStock, productsResult[i].InStock);
|
||||
Assert.AreEqual(expected[i].Name, productsResult[i].Name);
|
||||
Assert.AreEqual(expected[i].Price, productsResult[i].Price);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task VendorProducts_NullSupplierPassed_ReturnNotFound()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const string supplier = null;
|
||||
|
||||
var result = await controller.VendorProducts(supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task VendorProducts_EmtpySupplierPassed_ReturnNotFound()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const string supplier = "";
|
||||
|
||||
var result = await controller.VendorProducts(supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OrderRequest_ValidIdAndSupplierPassed_ReturnCorrectAndValidModel()
|
||||
{
|
||||
const int id = 2;
|
||||
const string supplier = "undercutters";
|
||||
var expectedHttpResponse = Data.VendorProducts().FirstOrDefault(vp => vp.Id == id);
|
||||
var expectedJson = JsonConvert.SerializeObject(expectedHttpResponse);
|
||||
var expectedResponse = new HttpResponseMessage
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.OK,
|
||||
Content = new StringContent(expectedJson,
|
||||
Encoding.UTF8,
|
||||
"application/json")
|
||||
};
|
||||
var httpClient = new HttpClient(CreateHttpMock(expectedResponse).Object);
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null) { HttpClient = httpClient };
|
||||
|
||||
var expected = expectedHttpResponse;
|
||||
var result = await controller.OrderRequest(id, supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as ViewResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
var viewResult = objectResult.Model as OrderRequestModel;
|
||||
Assert.IsNotNull(viewResult);
|
||||
|
||||
Assert.AreEqual(id, viewResult.Id);
|
||||
Assert.AreEqual(expected.Name, viewResult.Name);
|
||||
Assert.AreEqual(expected.Id, viewResult.Id);
|
||||
Assert.AreEqual(supplier, viewResult.Supplier);
|
||||
Assert.AreEqual(expected.Description, viewResult.Description);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OrderRequest_IncorrectProductReturned_ReturnInternalServerError()
|
||||
{
|
||||
const int id = 2;
|
||||
const string supplier = "undercutters";
|
||||
var expectedHttpResponse = Data.VendorProducts().FirstOrDefault(vp => vp.Id == id + 1);
|
||||
var expectedJson = JsonConvert.SerializeObject(expectedHttpResponse);
|
||||
var expectedResponse = new HttpResponseMessage
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.OK,
|
||||
Content = new StringContent(expectedJson,
|
||||
Encoding.UTF8,
|
||||
"application/json")
|
||||
};
|
||||
var httpClient = new HttpClient(CreateHttpMock(expectedResponse).Object);
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null) { HttpClient = httpClient };
|
||||
|
||||
var result = await controller.OrderRequest(id, supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as StatusCodeResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
Assert.AreEqual(objectResult.StatusCode, StatusCodes.Status500InternalServerError);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OrderRequest_EmtpySupplierPassed_ReturnNotFound()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = 2;
|
||||
const string supplier = "";
|
||||
|
||||
var result = await controller.OrderRequest(id, supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OrderRequest_ZeroIdPassed_ReturnNotFound()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = 0;
|
||||
const string supplier = "undercutters";
|
||||
|
||||
var result = await controller.OrderRequest(id, supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OrderRequest_NegativeIdPassed_ReturnNotFound()
|
||||
{
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null);
|
||||
const int id = NegativeId;
|
||||
const string supplier = "undercutters";
|
||||
|
||||
var result = await controller.OrderRequest(id, supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OrderRequest_OutOfBoundsIdPassed_ReturnNotFound()
|
||||
{
|
||||
const int id = 10000;
|
||||
const string supplier = "undercutters";
|
||||
var expectedResponse = new HttpResponseMessage
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound
|
||||
};
|
||||
var httpClient = new HttpClient(CreateHttpMock(expectedResponse).Object);
|
||||
var context = new MockStockContext(Data.ProductStocks(), Data.Prices(), null);
|
||||
var controller = new StockController(context, null) { HttpClient = httpClient };
|
||||
|
||||
var result = await controller.OrderRequest(id, supplier);
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
var objectResult = result as NotFoundResult;
|
||||
Assert.IsNotNull(objectResult);
|
||||
}
|
||||
}
|
||||
}
|
24
ThAmCo-Stock/ThAmCo.Stock.Tests/ThAmCo.Stock.Tests.csproj
Normal file
24
ThAmCo-Stock/ThAmCo.Stock.Tests/ThAmCo.Stock.Tests.csproj
Normal file
@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="IdentityModel" Version="4.1.1" />
|
||||
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.6" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
|
||||
<PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
|
||||
<PackageReference Include="Moq" Version="4.13.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ThAmCo.Stock\ThAmCo.Stock.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
31
ThAmCo-Stock/ThAmCo.Stock.sln
Normal file
31
ThAmCo-Stock/ThAmCo.Stock.sln
Normal file
@ -0,0 +1,31 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.29102.190
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThAmCo.Stock", "ThAmCo.Stock\ThAmCo.Stock.csproj", "{776C190D-23ED-411F-992E-856EA29F03C3}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThAmCo.Stock.Tests", "ThAmCo.Stock.Tests\ThAmCo.Stock.Tests.csproj", "{CC10B86C-AA9A-47F9-B8FD-6F9D619A9FC7}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{776C190D-23ED-411F-992E-856EA29F03C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{776C190D-23ED-411F-992E-856EA29F03C3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{776C190D-23ED-411F-992E-856EA29F03C3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{776C190D-23ED-411F-992E-856EA29F03C3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{CC10B86C-AA9A-47F9-B8FD-6F9D619A9FC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{CC10B86C-AA9A-47F9-B8FD-6F9D619A9FC7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{CC10B86C-AA9A-47F9-B8FD-6F9D619A9FC7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CC10B86C-AA9A-47F9-B8FD-6F9D619A9FC7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {945DEC89-A282-495A-8477-B670C0CE64D0}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
105
ThAmCo-Stock/ThAmCo.Stock/Controllers/AccountController.cs
Normal file
105
ThAmCo-Stock/ThAmCo.Stock/Controllers/AccountController.cs
Normal file
@ -0,0 +1,105 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using IdentityModel.Client;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ThAmCo.Stock.Models;
|
||||
|
||||
namespace ThAmCo.Stock.Controllers
|
||||
{
|
||||
public class AccountController : Controller
|
||||
{
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
|
||||
public AccountController(IHttpClientFactory clientFactory)
|
||||
{
|
||||
_clientFactory = clientFactory;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> Login()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[AllowAnonymous]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Login([FromForm] LoginModel model)
|
||||
{
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
|
||||
var disco = await client.GetDiscoveryDocumentAsync("https://localhost:43389");
|
||||
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
|
||||
{
|
||||
Address = disco.TokenEndpoint,
|
||||
ClientId = "my_web_app",
|
||||
ClientSecret = "secret",
|
||||
|
||||
UserName = model.Email,
|
||||
Password = model.Password
|
||||
});
|
||||
|
||||
if (tokenResponse.IsError)
|
||||
return View();
|
||||
|
||||
var userInfoResponse = await client.GetUserInfoAsync(new UserInfoRequest
|
||||
{
|
||||
Address = disco.UserInfoEndpoint,
|
||||
Token = tokenResponse.AccessToken
|
||||
});
|
||||
|
||||
if (userInfoResponse.IsError)
|
||||
return View();
|
||||
|
||||
var claimsIdentity = new ClaimsIdentity(userInfoResponse.Claims, "Cookies");
|
||||
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
|
||||
|
||||
var tokensToStore = new AuthenticationToken[]
|
||||
{
|
||||
new AuthenticationToken { Name = "access_token", Value = tokenResponse.AccessToken }
|
||||
};
|
||||
var authProperties = new AuthenticationProperties();
|
||||
authProperties.StoreTokens(tokensToStore);
|
||||
|
||||
await HttpContext.SignInAsync("Cookies", claimsPrincipal, authProperties);
|
||||
|
||||
return LocalRedirect("/");
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
await HttpContext.SignOutAsync("Cookies");
|
||||
return LocalRedirect("/");
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
public IActionResult Authed()
|
||||
{
|
||||
return Ok("Authed");
|
||||
}
|
||||
|
||||
[Authorize(Policy = "StaffOnly")]
|
||||
public IActionResult StaffAuthed()
|
||||
{
|
||||
return Ok("Authed");
|
||||
}
|
||||
|
||||
public IActionResult AccessDenied()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
private HttpClient GetHttpClient(string s)
|
||||
{
|
||||
return _clientFactory.CreateClient(s);
|
||||
}
|
||||
}
|
||||
}
|
31
ThAmCo-Stock/ThAmCo.Stock/Controllers/HomeController.cs
Normal file
31
ThAmCo-Stock/ThAmCo.Stock/Controllers/HomeController.cs
Normal file
@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ThAmCo.Stock.Models;
|
||||
|
||||
namespace ThAmCo.Stock.Controllers
|
||||
{
|
||||
[Authorize(Policy = "StaffOnly")]
|
||||
public class HomeController : Controller
|
||||
{
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult Privacy()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
|
||||
public IActionResult Error()
|
||||
{
|
||||
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
|
||||
}
|
||||
}
|
||||
}
|
169
ThAmCo-Stock/ThAmCo.Stock/Controllers/OldStockController.cs
Normal file
169
ThAmCo-Stock/ThAmCo.Stock/Controllers/OldStockController.cs
Normal file
@ -0,0 +1,169 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ThAmCo.Stock.Data;
|
||||
using ThAmCo.Stock.Data.StockContext;
|
||||
using ThAmCo.Stock.Models.Dto;
|
||||
using ThAmCo.Stock.Models.ViewModel;
|
||||
|
||||
namespace ThAmCo.Stock.Controllers
|
||||
{
|
||||
[Route("[controller]")]
|
||||
[Controller]
|
||||
public class OldStockController : Controller
|
||||
{
|
||||
private readonly IStockContext _context;
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
|
||||
public OldStockController(IStockContext context, IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_context = context;
|
||||
_clientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
// GET: api/Stock
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<IEnumerable<ProductStockDto>>> GetProductStock()
|
||||
{
|
||||
return Ok(await _context.GetAll());
|
||||
}
|
||||
|
||||
// GET: api/Stock/5
|
||||
[HttpGet("{id}")]
|
||||
public async Task<ActionResult<ProductStockDetailsDto>> Details(int id)
|
||||
{
|
||||
if (id < 0)
|
||||
return NotFound();
|
||||
|
||||
var productStock = await _context.GetProductStockAsync(id);
|
||||
|
||||
if (productStock == null)
|
||||
return NotFound();
|
||||
|
||||
return Ok(new ProductStockDetailsDto
|
||||
{
|
||||
ProductID = productStock.ProductStock.ProductId,
|
||||
Stock = productStock.ProductStock.Stock,
|
||||
Price = productStock.Price.ProductPrice
|
||||
});
|
||||
}
|
||||
|
||||
[HttpGet("PriceHistory/{id}")]
|
||||
public async Task<ActionResult<ProductStockPricingHistoryDto>> PriceHistory(int id)
|
||||
{
|
||||
if (id < 0)
|
||||
return NotFound();
|
||||
|
||||
var productStock = await _context.GetProductStockAsync(id);
|
||||
|
||||
if (productStock == null)
|
||||
return NotFound();
|
||||
|
||||
var productPrices = _context.GetAllPrices().Result.Where(p => p.ProductStockId == productStock.ProductStock.PriceId).ToList();
|
||||
|
||||
var productDetails = new ProductStockPricingHistoryDto
|
||||
{
|
||||
ProductID = productStock.ProductStock.ProductId,
|
||||
Stock = productStock.ProductStock.Stock,
|
||||
Prices = productPrices
|
||||
};
|
||||
|
||||
return Ok(productDetails);
|
||||
}
|
||||
|
||||
// PUT: api/Stock/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutProductStock(int id, ProductStock productStock)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
/*if (id != productStock.Id)
|
||||
return BadRequest();
|
||||
|
||||
_context.Entry(productStock).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!ProductStockExists(id))
|
||||
return NotFound();
|
||||
throw;
|
||||
}
|
||||
|
||||
return NoContent();*/
|
||||
}
|
||||
|
||||
// POST: api/Stock
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<ProductStock>> PostProductStock(ProductStock productStock)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
/*_context.ProductStocks.Add(productStock);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return CreatedAtAction("GetProductStock", new { id = productStock.Id }, productStock);*/
|
||||
}
|
||||
|
||||
// DELETE: api/Stock/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<ActionResult<ProductStock>> DeleteProductStock(int id)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
/*var productStock = await _context.ProductStocks.FindAsync(id);
|
||||
if (productStock == null)
|
||||
return NotFound();
|
||||
|
||||
_context.ProductStocks.Remove(productStock);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return productStock;*/
|
||||
}
|
||||
|
||||
[HttpGet("low/{count}")]
|
||||
public ActionResult<IEnumerable<ProductStockDto>> Low(int? count)
|
||||
{
|
||||
if (count != null && count < 0)
|
||||
return NotFound(); //0 is technically valid, since the request would want 0. below 0 would be an invalid request.
|
||||
|
||||
var listToCount = _context.GetAll().Result.OrderBy(ps => ps.ProductStock.Stock).Take(count ?? 5).ToList();
|
||||
|
||||
return View(listToCount);
|
||||
}
|
||||
|
||||
[HttpGet("AdjustCost/{id}")]
|
||||
public async Task<ActionResult<ProductStockDto>> AdjustCost(int id)
|
||||
{
|
||||
var productPrice = await _context.GetProductStockAsync(id);
|
||||
if (productPrice == null)
|
||||
return NotFound();
|
||||
return View(new AdjustCostViewModel { Id = productPrice.ProductStock.Id, Cost = productPrice.Price.ProductPrice });
|
||||
}
|
||||
|
||||
[HttpPost("AdjustCost")]
|
||||
public async Task<ActionResult> AdjustCost(int id, double cost)
|
||||
{
|
||||
var productStock = _context.GetProductStockAsync(id).Result;
|
||||
|
||||
if (productStock == null)
|
||||
return NotFound();
|
||||
|
||||
var price = _context.AddPriceAsync(new Price { ProductPrice = cost, ProductStockId = id, Date = DateTime.Now });
|
||||
|
||||
productStock.ProductStock.PriceId = price.Id;
|
||||
_context.UpdateProductStockAsync(productStock.ProductStock);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
private bool ProductStockExists(int id)
|
||||
{
|
||||
return _context.GetAll().Result.Any(e => e.ProductStock.Id == id);
|
||||
}
|
||||
}
|
||||
}
|
440
ThAmCo-Stock/ThAmCo.Stock/Controllers/StockController.cs
Normal file
440
ThAmCo-Stock/ThAmCo.Stock/Controllers/StockController.cs
Normal file
@ -0,0 +1,440 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
using ThAmCo.Stock.Data;
|
||||
using ThAmCo.Stock.Data.StockContext;
|
||||
using ThAmCo.Stock.Models.Dto;
|
||||
using ThAmCo.Stock.Models.ViewModel;
|
||||
|
||||
namespace ThAmCo.Stock.Controllers
|
||||
{
|
||||
[Authorize(Policy = "StaffOnly")]
|
||||
public class StockController : Controller
|
||||
{
|
||||
private readonly IStockContext _context;
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
|
||||
public HttpClient HttpClient { get; set; }
|
||||
|
||||
public StockController(IStockContext context, IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_context = context;
|
||||
_clientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
// GET: Stock
|
||||
public async Task<IActionResult> Index()
|
||||
{
|
||||
return View(_context.GetAll().Result.ToList());
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
// GET: Stock/Details/5
|
||||
public async Task<ActionResult<ProductStockDetailsDto>> Details(int id)
|
||||
{
|
||||
if (id < 0)
|
||||
return NotFound();
|
||||
|
||||
var productStock = await _context.GetProductStockAsync(id);
|
||||
|
||||
if (productStock == null)
|
||||
return NotFound();
|
||||
|
||||
return Ok(new ProductStockDetailsDto
|
||||
{
|
||||
ProductID = productStock.ProductStock.ProductId,
|
||||
Stock = productStock.ProductStock.Stock,
|
||||
Price = productStock.Price.ProductPrice
|
||||
});
|
||||
}
|
||||
|
||||
// GET: Stock/Create
|
||||
public IActionResult Create()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
// POST: Stock/Create
|
||||
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
|
||||
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Create([Bind("Id,ProductId,Stock,PriceId")] ProductStock productStock)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
//_context.AddProductStockAsync(productStock);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
return View(productStock);
|
||||
}
|
||||
|
||||
// GET: Stock/Edit/5
|
||||
public async Task<IActionResult> Edit(int? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var productStock = await _context.GetProductStockAsync(id ?? 1);
|
||||
if (productStock == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
return View(productStock);
|
||||
}
|
||||
|
||||
// POST: Stock/Edit/5
|
||||
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
|
||||
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Edit(int id, [Bind("Id,ProductId,Stock,PriceId")] ProductStock productStock)
|
||||
{
|
||||
if (id != productStock.Id)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
try
|
||||
{
|
||||
_context.UpdateProductStockAsync(productStock);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!ProductStockExists(productStock.Id))
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
return View(productStock);
|
||||
}
|
||||
|
||||
// GET: Stock/Delete/5
|
||||
public async Task<IActionResult> Delete(int? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var productStock = await _context.GetProductStockAsync(id ?? 1);
|
||||
if (productStock == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
return View(productStock);
|
||||
}
|
||||
|
||||
// POST: Stock/Delete/5
|
||||
[HttpPost, ActionName("Delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> DeleteConfirmed(int id)
|
||||
{
|
||||
/*var productStock = await _context.ProductStocks.FindAsync(id);
|
||||
_context.ProductStocks.Remove(productStock);
|
||||
await _context.SaveChangesAsync();*/
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
public async Task<ActionResult<IEnumerable<ProductStockDto>>> ProductStocks()
|
||||
{
|
||||
return Ok(await _context.GetAll());
|
||||
}
|
||||
|
||||
public async Task<ActionResult<ProductStockPricingHistoryDto>> PriceHistory(int id)
|
||||
{
|
||||
if (id < 0)
|
||||
return NotFound();
|
||||
|
||||
var productStock = await _context.GetProductStockAsync(id);
|
||||
|
||||
if (productStock == null)
|
||||
return NotFound();
|
||||
|
||||
var productPrices = _context.GetAllPrices().Result.Where(p => p.ProductStockId == productStock.ProductStock.PriceId).ToList();
|
||||
|
||||
var productDetails = new ProductStockPricingHistoryDto
|
||||
{
|
||||
ProductID = productStock.ProductStock.ProductId,
|
||||
Stock = productStock.ProductStock.Stock,
|
||||
Prices = productPrices
|
||||
};
|
||||
|
||||
return Ok(productDetails);
|
||||
}
|
||||
|
||||
public ActionResult<IEnumerable<ProductStockDto>> Low(int? count)
|
||||
{
|
||||
if (count != null && count < 0)
|
||||
return NotFound(); //0 is technically valid, since the request would want 0. below 0 would be an invalid request.
|
||||
|
||||
var listToCount = _context.GetAll().Result.OrderBy(ps => ps.ProductStock.Stock).Take(count ?? 5).ToList();
|
||||
|
||||
return View(listToCount);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<AdjustCostViewModel>> AdjustCost(int id)
|
||||
{
|
||||
var productPrice = await _context.GetProductStockAsync(id);
|
||||
|
||||
if (productPrice == null)
|
||||
return NotFound();
|
||||
|
||||
AdjustCostViewModel objectResponse;
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
var response = await client.GetAsync("https://localhost:44375/products/getProduct/" + id);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var objectResult = await response.Content.ReadAsAsync<ProductDto>();
|
||||
if (objectResult == null)
|
||||
return NotFound();
|
||||
objectResponse = new AdjustCostViewModel
|
||||
{
|
||||
Id = productPrice.ProductStock.Id,
|
||||
Cost = productPrice.Price.ProductPrice,
|
||||
Name = objectResult.Name,
|
||||
Description = objectResult.Description
|
||||
};
|
||||
}
|
||||
else return NotFound();
|
||||
|
||||
return View(objectResponse);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult> AdjustCost(int id, double cost)
|
||||
{
|
||||
var productStock = await _context.GetProductStockAsync(id);
|
||||
|
||||
if (productStock == null)
|
||||
return NotFound();
|
||||
if (cost <= 0)
|
||||
return BadRequest();
|
||||
|
||||
var price = _context.AddPriceAsync(new Price { ProductPrice = cost, ProductStockId = id, Date = DateTime.Now });
|
||||
|
||||
productStock.ProductStock.PriceId = price.Id;
|
||||
_context.UpdateProductStockAsync(productStock.ProductStock);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> VendorProducts(string supplier)
|
||||
{
|
||||
var vendorProducts = new VendorProductIndexModel
|
||||
{
|
||||
Vendor = supplier
|
||||
};
|
||||
|
||||
HttpResponseMessage response = null;
|
||||
|
||||
var url = GetURLForSupplier(supplier);
|
||||
if (url == null)
|
||||
return NotFound();
|
||||
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
response = await client.GetAsync(url + "product");
|
||||
|
||||
if (response?.IsSuccessStatusCode == true)
|
||||
{
|
||||
var objectResult = await response.Content.ReadAsAsync<List<VendorProductDto>>();
|
||||
if (objectResult == null)
|
||||
goto View;
|
||||
vendorProducts.Products = objectResult;
|
||||
}
|
||||
else return NotFound();
|
||||
|
||||
View:
|
||||
return View(vendorProducts);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> OrderRequest(int id, string supplier = null)
|
||||
{
|
||||
if (id <= 0)
|
||||
return NotFound();
|
||||
|
||||
var url = GetURLForSupplier(supplier);
|
||||
if (url == null)
|
||||
return NotFound();
|
||||
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
HttpResponseMessage response = null;
|
||||
response = await client.GetAsync(url + "product/" + id);
|
||||
|
||||
if (response?.IsSuccessStatusCode == true)
|
||||
{
|
||||
var objectResult = await response.Content.ReadAsAsync<VendorProductDto>();
|
||||
|
||||
if (objectResult == null)
|
||||
return NotFound();
|
||||
if (objectResult.Id != id)
|
||||
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
|
||||
|
||||
return View(new OrderRequestModel { Id = id, Name = objectResult.Name, Description = objectResult.Description, Supplier = supplier });
|
||||
}
|
||||
else return NotFound();
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult> OrderRequestSubmitted(int id, string supplier, int quantity)
|
||||
{
|
||||
var orderRequest = new OrderRequest
|
||||
{
|
||||
Quantity = quantity,
|
||||
Supplier = supplier,
|
||||
SubmittedTime = DateTime.Now,
|
||||
Approved = false,
|
||||
ApprovedTime = null,
|
||||
Deleted = false
|
||||
};
|
||||
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
var url = GetURLForSupplier(supplier);
|
||||
if (url == null)
|
||||
return NotFound();
|
||||
|
||||
HttpResponseMessage response = null;
|
||||
|
||||
response = await client.GetAsync(url + "product/" + id);
|
||||
|
||||
if (response?.IsSuccessStatusCode == true)
|
||||
{
|
||||
var objectResult = await response.Content.ReadAsAsync<VendorProductDto>();
|
||||
if (objectResult == null)
|
||||
return NotFound();
|
||||
orderRequest.ProductId = objectResult.Id;
|
||||
orderRequest.Price = objectResult.Price * quantity;
|
||||
|
||||
_context.AddOrderRequest(orderRequest);
|
||||
|
||||
return RedirectToAction(nameof(VendorProducts), new { supplier });
|
||||
}
|
||||
else return NotFound();
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> OrderRequests()
|
||||
{
|
||||
return View(_context.GetAllOrderRequests().Result.Where(or => !or.Approved).ToList());
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> OrderRequestReview(int id)
|
||||
{
|
||||
var orderRequest = _context.GetOrderRequest(id).Result;
|
||||
if (orderRequest == null)
|
||||
return NotFound();
|
||||
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
var url = GetURLForSupplier(orderRequest.Supplier);
|
||||
if (url == null)
|
||||
return NotFound();
|
||||
|
||||
HttpResponseMessage response = null;
|
||||
|
||||
response = await client.GetAsync(url + "product/" + orderRequest.ProductId);
|
||||
|
||||
if (response?.IsSuccessStatusCode == true)
|
||||
{
|
||||
var objectResult = await response.Content.ReadAsAsync<VendorProductDto>();
|
||||
if (objectResult == null)
|
||||
return NotFound();
|
||||
|
||||
//Update order details incase service changes prices.
|
||||
if (orderRequest.Price != objectResult.Price * orderRequest.Quantity)
|
||||
{
|
||||
orderRequest.Price = objectResult.Price * orderRequest.Quantity;
|
||||
_context.UpdateOrderRequest(orderRequest);
|
||||
}
|
||||
|
||||
var reviewModel = new OrderRequestReviewModel
|
||||
{
|
||||
Id = orderRequest.Id,
|
||||
Name = objectResult.Name,
|
||||
Description = objectResult.Description,
|
||||
Price = orderRequest.Price,
|
||||
Quantity = orderRequest.Quantity,
|
||||
Supplier = orderRequest.Supplier
|
||||
};
|
||||
|
||||
return View(reviewModel);
|
||||
}
|
||||
else return NotFound();
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult> OrderRequestApproved(int id)
|
||||
{
|
||||
var orderRequest = _context.GetOrderRequest(id).Result;
|
||||
if (orderRequest == null)
|
||||
return NotFound();
|
||||
var orderDto = new ProductOrderPostDto
|
||||
{
|
||||
AccountName = "sample string 1",
|
||||
CardNumber = "sample string 2",
|
||||
ProductId = orderRequest.ProductId,
|
||||
Quantity = orderRequest.Quantity
|
||||
};
|
||||
|
||||
var client = GetHttpClient("StandardRequest");
|
||||
var result = await client.PostAsJsonAsync(GetURLForSupplier(orderRequest.Supplier) + "order", orderDto);
|
||||
if (result.IsSuccessStatusCode)
|
||||
{
|
||||
_context.ApproveOrderRequest(id);
|
||||
return Ok(result.Content);
|
||||
//return RedirectToAction(nameof(OrderRequests));
|
||||
}
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
private bool ProductStockExists(int id)
|
||||
{
|
||||
return _context.GetAll().Result.Any(e => e.ProductStock.Id == id);
|
||||
}
|
||||
|
||||
private HttpClient GetHttpClient(string s)
|
||||
{
|
||||
if (_clientFactory == null && HttpClient != null) return HttpClient;
|
||||
|
||||
return _clientFactory.CreateClient(s);
|
||||
}
|
||||
|
||||
private string GetURLForSupplier(string s)
|
||||
{
|
||||
if (s == "undercutters") return "http://undercutters.azurewebsites.net/api/";
|
||||
else if (s == "dodgydealers") return "http://dodgydealers.azurewebsites.net/api/";
|
||||
else return null;
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user