diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a30d25 --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.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 + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# 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 +# Note: 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 +# 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 +*.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 +*.appx +*.appxbundle +*.appxupload + +# 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 +orleans.codegen.cs + +# 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) +#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 +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/ApiDotNetCore/.vs/ApiDotNetCore/v17/.suo b/ApiDotNetCore/.vs/ApiDotNetCore/v17/.suo new file mode 100644 index 0000000..0dfe1c6 Binary files /dev/null and b/ApiDotNetCore/.vs/ApiDotNetCore/v17/.suo differ diff --git a/ApiDotNetCore/ApiDotNetCore.sln b/ApiDotNetCore/ApiDotNetCore.sln new file mode 100644 index 0000000..1b257bc --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32630.192 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiDotNetCore", "ApiDotNetCore\ApiDotNetCore.csproj", "{BB23EC7D-4FBC-4C41-BC69-9ACB857B13AF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiDotNetCoreTest", "ApiDotNetCoreTest\ApiDotNetCoreTest.csproj", "{4C55C1FC-325E-48BA-9165-895F1AD71A00}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BB23EC7D-4FBC-4C41-BC69-9ACB857B13AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BB23EC7D-4FBC-4C41-BC69-9ACB857B13AF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BB23EC7D-4FBC-4C41-BC69-9ACB857B13AF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BB23EC7D-4FBC-4C41-BC69-9ACB857B13AF}.Release|Any CPU.Build.0 = Release|Any CPU + {4C55C1FC-325E-48BA-9165-895F1AD71A00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C55C1FC-325E-48BA-9165-895F1AD71A00}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C55C1FC-325E-48BA-9165-895F1AD71A00}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C55C1FC-325E-48BA-9165-895F1AD71A00}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C02115DE-0A0B-420B-8996-41E52FD4A721} + EndGlobalSection +EndGlobal diff --git a/ApiDotNetCore/ApiDotNetCore/ApiDotNetCore.csproj b/ApiDotNetCore/ApiDotNetCore/ApiDotNetCore.csproj new file mode 100644 index 0000000..c8f7956 --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/ApiDotNetCore.csproj @@ -0,0 +1,16 @@ + + + + net6.0 + enable + enable + + + + + + + + + + diff --git a/ApiDotNetCore/ApiDotNetCore/Config/Configuration.cs b/ApiDotNetCore/ApiDotNetCore/Config/Configuration.cs new file mode 100644 index 0000000..553318c --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/Config/Configuration.cs @@ -0,0 +1,7 @@ +namespace ApiDotNetCore.Config +{ + public static class Configuration + { + public static string ConnectionString { get; set; } = "Data Source=localhost,1433;Initial Catalog=DB_DESAFIO_DOTNET_CORE;Integrated Security=False;User Id=sa;Password=1q2w3e4r@;MultipleActiveResultSets=True"; + } +} diff --git a/ApiDotNetCore/ApiDotNetCore/Controllers/ProductController.cs b/ApiDotNetCore/ApiDotNetCore/Controllers/ProductController.cs new file mode 100644 index 0000000..237c164 --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/Controllers/ProductController.cs @@ -0,0 +1,129 @@ +using ApiDotNetCore.Entities; +using ApiDotNetCore.Repositories; +using ApiDotNetCore.ViewModel; +using Microsoft.AspNetCore.Mvc; + +namespace ApiDotNetCore.Controllers +{ + [ApiController] + [Route("[controller]")] + public class ProductController : ControllerBase + { + private SqlServerRepository respository = new SqlServerRepository(); + + + [HttpGet("/api/v1/products")] + public async Task GetAsync() + { + try + { + var data = respository.GetAll(); + return Ok(new ResultViewModel(data)); + } + catch + { + return StatusCode(500, new ResultViewModel("Internal server error")); + } + } + + [HttpGet("/api/v1/products/{productId}")] + public async Task GetByIdAsync( + [FromRoute] int productId) + { + + try + { + var data = respository.GetById(productId); + if (data == null) + return NotFound(new ResultViewModel("Not Content Found")); + + return Ok(new ResultViewModel(data)); + } + catch + { + return StatusCode(500, new ResultViewModel("Internal server error")); + } + } + + [HttpPost("/api/v1/products")] + public async Task PostAsync( + [FromBody] ProductEntity product) + { + + if (!ModelState.IsValid) + return BadRequest(new ResultViewModel(ModelState)); + + try + { + var id = respository.Insert(product); + product.Id = id; + product.CreatedAt = DateTime.Now; + + return Ok(new ResultViewModel(product)); + } + catch (Exception error) + { + return StatusCode(500, new ResultViewModel("Error to create product.")); + } + catch + { + return StatusCode(500, new ResultViewModel("Internal server erro")); + } + } + + [HttpPut("/api/v1/products/{productId}")] + public async Task PutAsync( + [FromRoute] int productId, + [FromBody] ProductEntity product) + { + + try + { + var data = respository.GetById(productId); + if (data == null) return NotFound(new ResultViewModel("Not Content Found.")); + + data.Name = product.Name; + data.Brand = product.Brand; + data.Price = product.Price; + data.UpdatedAt = DateTime.Now; + respository.Update(data, productId); + return Ok(new ResultViewModel(data)); + } + catch (Exception error) + { + return StatusCode(500, new ResultViewModel("Error to update product.")); + } + catch + { + return StatusCode(500, new ResultViewModel("Internal server error")); + } + + + } + + [HttpDelete("/api/v1/products/{productId}")] + public async Task DeleteAsync( + [FromRoute] int productId) + { + + try + { + var data = respository.GetById(productId); + if (data == null) return NotFound(new ResultViewModel("Not Content Found.")); + respository.Delete(productId); + return Ok(new ResultViewModel(data)); + } + catch (Exception error) + { + return StatusCode(500, new ResultViewModel("Error to update product.")); + } + catch + { + return StatusCode(500, new ResultViewModel("Internal server error")); + } + + + + } + } +} \ No newline at end of file diff --git a/ApiDotNetCore/ApiDotNetCore/Entities/ProductEntity.cs b/ApiDotNetCore/ApiDotNetCore/Entities/ProductEntity.cs new file mode 100644 index 0000000..be2463e --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/Entities/ProductEntity.cs @@ -0,0 +1,29 @@ +using System.ComponentModel.DataAnnotations; + +namespace ApiDotNetCore.Entities +{ + public class ProductEntity + { + public int Id { get; set; } + [Required(ErrorMessage = "the field name missing.")] + public string Name { get; set; } + public string Brand { get; set; } + [Required(ErrorMessage = "the filed price missing.")] + public double Price { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime? UpdatedAt { get; set; } + + public ProductEntity() + { + + } + + public ProductEntity(string name, string brand, double price) + { + Name = name; + Brand = brand; + Price = price; + } + + } +} diff --git a/ApiDotNetCore/ApiDotNetCore/Interfaces/IRepository.cs b/ApiDotNetCore/ApiDotNetCore/Interfaces/IRepository.cs new file mode 100644 index 0000000..48ce534 --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/Interfaces/IRepository.cs @@ -0,0 +1,11 @@ +namespace ApiDotNetCore.Interfaces +{ + public interface IRepository where TEntity : class + { + List GetAll(); + TEntity GetById(TKey id); + int Insert(TEntity entity); + void Update(TEntity entity, TKey id); + void Delete(TKey id); + } +} diff --git a/ApiDotNetCore/ApiDotNetCore/Program.cs b/ApiDotNetCore/ApiDotNetCore/Program.cs new file mode 100644 index 0000000..6845b99 --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/Program.cs @@ -0,0 +1,15 @@ +var builder = WebApplication.CreateBuilder(args); +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseAuthorization(); +app.MapControllers(); +app.Run(); diff --git a/ApiDotNetCore/ApiDotNetCore/Properties/launchSettings.json b/ApiDotNetCore/ApiDotNetCore/Properties/launchSettings.json new file mode 100644 index 0000000..61d0edc --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:64140", + "sslPort": 44396 + } + }, + "profiles": { + "ApiDotNetCore": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7001;http://localhost:5001", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/ApiDotNetCore/ApiDotNetCore/Repositories/FakeRepository.cs b/ApiDotNetCore/ApiDotNetCore/Repositories/FakeRepository.cs new file mode 100644 index 0000000..28e5826 --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/Repositories/FakeRepository.cs @@ -0,0 +1,71 @@ +using ApiDotNetCore.Entities; + +namespace ApiDotNetCore.Repositories +{ + public class FakeRepository + { + public List listaProdutos; + + public FakeRepository() + { + listaProdutos = new List(); + listaProdutos.Add(new ProductEntity() { Id = 1, Name = "Product01", Brand = "Brand01", Price = 2.0 }); + listaProdutos.Add(new ProductEntity() { Id = 2, Name = "Product02", Brand = "Brand02", Price = 2.5 }); + listaProdutos.Add(new ProductEntity() { Id = 3, Name = "Product03", Brand = "Brand03", Price = 1.2 }); + listaProdutos.Add(new ProductEntity() { Id = 4, Name = "Product04", Brand = "Brand04", Price = 7.7 }); + listaProdutos.Add(new ProductEntity() { Id = 5, Name = "Product05", Brand = "Brand05", Price = 4.3 }); + listaProdutos.Add(new ProductEntity() { Id = 6, Name = "Product06", Brand = "Brand06", Price = 5.1 }); + } + + public List GetAll() + { + return listaProdutos; + } + + public ProductEntity GetById(int id) + { + return listaProdutos.FirstOrDefault(x => x.Id == id); + } + + public int Insert(ProductEntity entity) + { + var maxId = listaProdutos.Max(t => t.Id); + maxId++; + + var produto = new ProductEntity() + { + Id = maxId, + Name = entity.Name, + Brand = entity.Brand, + Price = entity.Price, + CreatedAt = DateTime.Now + }; + listaProdutos.Add(produto); + return maxId; + } + + public void Update(ProductEntity entity, int id) + { + var index = listaProdutos.FindIndex(t => t.Id == id); + + if (index != null) + { + listaProdutos[index].Name = entity.Name; + listaProdutos[index].Brand = entity.Brand; + listaProdutos[index].Price = entity.Price; + listaProdutos[index].UpdatedAt = DateTime.Now; + } + } + + public void Delete(int id) + { + var index = listaProdutos.FindIndex(t => t.Id == id); + + if (index != null) + { + listaProdutos.RemoveAt(index); + + } + } + } +} diff --git a/ApiDotNetCore/ApiDotNetCore/Repositories/SqlServerRepository.cs b/ApiDotNetCore/ApiDotNetCore/Repositories/SqlServerRepository.cs new file mode 100644 index 0000000..13fb16d --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/Repositories/SqlServerRepository.cs @@ -0,0 +1,165 @@ +using ApiDotNetCore.Config; +using ApiDotNetCore.Entities; +using ApiDotNetCore.Interfaces; +using System.Data; +using System.Data.SqlClient; + +namespace ApiDotNetCore.Repositories +{ + public class SqlServerRepository : IRepository + { + protected string stringConnection; + public SqlServerRepository() + { + stringConnection = Configuration.ConnectionString; + } + + public List GetAll() + { + using (var conn = new SqlConnection(stringConnection)) + { + List listaProdutos = new List(); + ProductEntity produto = null; + try + { + SqlCommand cmd = new SqlCommand("sp_select_products", conn); + cmd.CommandType = CommandType.StoredProcedure; + conn.Open(); + using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) + { + while (reader.Read()) + { + produto = new ProductEntity() + { + CreatedAt = (DateTime)reader["createdAt"], + Name = reader["name"].ToString(), + Price = (double)reader["price"], + Brand = reader["brand"].ToString(), + UpdatedAt = (DateTime?)reader["updatedAt"], + Id = (int)reader["id"], + }; + listaProdutos.Add(produto); + } + } + } + catch (Exception error) + { + throw error; + } + return listaProdutos; + } + } + + public ProductEntity GetById(int id) + { + using (var conn = new SqlConnection(stringConnection)) + { + ProductEntity produto = null; + try + { + SqlCommand cmd = new SqlCommand("sp_select_products", conn); + cmd.CommandType = CommandType.StoredProcedure; + conn.Open(); + cmd.Parameters.AddWithValue("@id", id); + using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) + { + while (reader.Read()) + { + produto = new ProductEntity() + { + CreatedAt = (DateTime)reader["createdAt"], + Name = reader["name"].ToString(), + Price = (double)reader["price"], + Brand = reader["brand"].ToString(), + UpdatedAt = (DateTime?)reader["updatedAt"], + Id = (int)reader["id"], + }; + } + } + } + catch (Exception error) + { + throw error; + } + return produto; + } + } + + public int Insert(ProductEntity entity) + { + using (var conn = new SqlConnection(stringConnection)) + { + try + { + var cmd = new SqlCommand("sp_insert_products", conn); + conn.Open(); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue("@name", entity.Name); + cmd.Parameters.AddWithValue("@brand", entity.Brand); + cmd.Parameters.AddWithValue("@price", entity.Price); + + SqlParameter id = new SqlParameter(); + id.ParameterName = "@id"; + id.Direction = ParameterDirection.Output; + id.SqlDbType = SqlDbType.Int; + cmd.Parameters.Add(id); + + cmd.ExecuteNonQuery(); + + return (int)id.Value; + } + catch (Exception error) + { + + throw error; + } + + } + } + + public void Update(ProductEntity entity, int id) + { + using (var conn = new SqlConnection(stringConnection)) + { + try + { + var cmd = new SqlCommand("sp_update_products", conn); + conn.Open(); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue("@id", id); + cmd.Parameters.AddWithValue("@name", entity.Name); + cmd.Parameters.AddWithValue("@brand", entity.Brand); + cmd.Parameters.AddWithValue("@price", entity.Price); + cmd.ExecuteNonQuery(); + + } + catch (Exception error) + { + throw error; + } + + } + } + + public void Delete(int id) + { + using (var conn = new SqlConnection(stringConnection)) + { + try + { + var cmd = new SqlCommand("sp_delete_products", conn); + conn.Open(); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue("@id", id); + cmd.ExecuteNonQuery(); + } + catch (Exception error) + { + throw error; + } + + } + } + + } +} diff --git a/ApiDotNetCore/ApiDotNetCore/ViewModel/ResultViewModel.cs b/ApiDotNetCore/ApiDotNetCore/ViewModel/ResultViewModel.cs new file mode 100644 index 0000000..3d8387c --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/ViewModel/ResultViewModel.cs @@ -0,0 +1,33 @@ +namespace ApiDotNetCore.ViewModel +{ + public class ResultViewModel + { + public ResultViewModel(T data, List errors) + { + Data = data; + Errors = errors; + } + + public ResultViewModel(T data) + { + Data = data; + + } + + public ResultViewModel(List errors) + { + Errors = errors; + } + + public ResultViewModel(string error) + { + Errors.Add(error); + } + + + + public T Data { get; private set; } + + public List Errors { get; private set; } = new List(); + } +} diff --git a/ApiDotNetCore/ApiDotNetCore/appsettings.Development.json b/ApiDotNetCore/ApiDotNetCore/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/ApiDotNetCore/ApiDotNetCore/appsettings.json b/ApiDotNetCore/ApiDotNetCore/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCore/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/ApiDotNetCore/ApiDotNetCoreTest/ApiDotNetCoreTest.csproj b/ApiDotNetCore/ApiDotNetCoreTest/ApiDotNetCoreTest.csproj new file mode 100644 index 0000000..5af790a --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCoreTest/ApiDotNetCoreTest.csproj @@ -0,0 +1,22 @@ + + + + net6.0 + enable + enable + + false + + + + + + + + + + + + + + diff --git a/ApiDotNetCore/ApiDotNetCoreTest/ProductTest.cs b/ApiDotNetCore/ApiDotNetCoreTest/ProductTest.cs new file mode 100644 index 0000000..2f1f41e --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCoreTest/ProductTest.cs @@ -0,0 +1,79 @@ +using ApiDotNetCore.Entities; +using ApiDotNetCore.Repositories; + +namespace ApiDotNetCoreTest +{ + [TestClass] + public class ProductTest + { + [TestMethod] + [TestCategory("Product")] + public void Should_Create_Valid_Product() + { + var product = new ProductEntity("Test", "Test", 7.5); + Assert.AreEqual(product.Name, "Test"); + Assert.AreEqual(product.Brand, "Test"); + Assert.AreEqual(product.Price, 7.5); + } + + + [TestMethod] + [TestCategory("Product")] + public void Should_Get_All_Products() + { + var repository = new FakeRepository(); + var listaProdutos = repository.GetAll(); + Assert.AreEqual(listaProdutos.Count, 6); + } + + [TestMethod] + [TestCategory("Product")] + public void Should_Get_Product_ById() + { + var repository = new FakeRepository(); + var produto = repository.GetById(2); + Assert.AreEqual(produto.Id, 2); + Assert.AreEqual(produto.Name, "Product02"); + Assert.AreEqual(produto.Brand, "Brand02"); + Assert.AreEqual(produto.Price, 2.5); + } + + + [TestMethod] + [TestCategory("Product")] + public void Should_Insert_New_Product() + { + var repository = new FakeRepository(); + var totalProducts = repository.listaProdutos.Count; + var Id = totalProducts + 1; + var product = new ProductEntity() { Name = "Product" + Id, Brand = "Brand" + Id, Price = 4.99 }; + repository.Insert(product); + Assert.IsTrue(repository.listaProdutos.Count > totalProducts); + } + + [TestMethod] + [TestCategory("Product")] + public void Should_Update_Product() + { + var repository = new FakeRepository(); + var totalProducts = repository.listaProdutos.Count; + var Id = 3; + var product = new ProductEntity() { Name = "ProductUpdated", Brand = "BrandUpdated", Price = 9.99 }; + repository.Update(product, Id); + var Index = repository.listaProdutos.FindIndex(x => x.Id == Id); + Assert.IsTrue(repository.listaProdutos[Index].Name == "ProductUpdated"); + Assert.IsTrue(repository.listaProdutos[Index].Brand == "BrandUpdated"); + Assert.IsTrue(repository.listaProdutos[Index].Price == 9.99); + } + + [TestMethod] + [TestCategory("Product")] + public void Should_Delete_Product() + { + var repository = new FakeRepository(); + var totalProducts = repository.listaProdutos.Count; + repository.Delete(2); + Assert.IsTrue(repository.listaProdutos.Count < totalProducts); + } + } +} \ No newline at end of file diff --git a/ApiDotNetCore/ApiDotNetCoreTest/Usings.cs b/ApiDotNetCore/ApiDotNetCoreTest/Usings.cs new file mode 100644 index 0000000..ab67c7e --- /dev/null +++ b/ApiDotNetCore/ApiDotNetCoreTest/Usings.cs @@ -0,0 +1 @@ +global using Microsoft.VisualStudio.TestTools.UnitTesting; \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework.Tests/ApiDotNetFramework.Tests.csproj b/ApiDotNetFramework/ApiDotNetFramework.Tests/ApiDotNetFramework.Tests.csproj new file mode 100644 index 0000000..40a0b11 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework.Tests/ApiDotNetFramework.Tests.csproj @@ -0,0 +1,69 @@ + + + + Debug + AnyCPU + {939D1ED1-8075-45EC-BA70-067AA23339DD} + Library + Properties + ApiDotNetFramework.Tests + ApiDotNetFramework.Tests + v4.5.2 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + UnitTest + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + {F9D9CCC3-632A-46A0-957B-68794F4F218A} + ApiDotNetFramework + + + + + + \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework.Tests/ProductTest.cs b/ApiDotNetFramework/ApiDotNetFramework.Tests/ProductTest.cs new file mode 100644 index 0000000..404c808 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework.Tests/ProductTest.cs @@ -0,0 +1,81 @@ +using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using ApiDotNetFramework.Entities; +using ApiDotNetFramework.Repositories; + +namespace ApiDotNetFramework.Tests +{ + [TestClass] + public class ProductTest + { + [TestMethod] + [TestCategory("Product")] + public void Should_Create_Valid_Product() + { + var product = new ProductEntity("Test", "Test", 7.5); + Assert.AreEqual(product.Name, "Test"); + Assert.AreEqual(product.Brand, "Test"); + Assert.AreEqual(product.Price, 7.5); + } + + + [TestMethod] + [TestCategory("Product")] + public void Should_Get_All_Products() + { + var repository = new FakeRepository(); + var listaProdutos = repository.GetAll(); + Assert.AreEqual(listaProdutos.Count,6); + } + + [TestMethod] + [TestCategory("Product")] + public void Should_Get_Product_ById() + { + var repository = new FakeRepository(); + var produto = repository.GetById(2); + Assert.AreEqual(produto.Id, 2); + Assert.AreEqual(produto.Name, "Product02"); + Assert.AreEqual(produto.Brand, "Brand02"); + Assert.AreEqual(produto.Price, 2.5); + } + + + [TestMethod] + [TestCategory("Product")] + public void Should_Insert_New_Product() + { + var repository = new FakeRepository(); + var totalProducts = repository.listaProdutos.Count; + var Id = totalProducts + 1; + var product = new ProductEntity() {Name = "Product" + Id, Brand = "Brand" + Id, Price = 4.99 }; + repository.Insert(product); + Assert.IsTrue(repository.listaProdutos.Count > totalProducts); + } + + [TestMethod] + [TestCategory("Product")] + public void Should_Update_Product() + { + var repository = new FakeRepository(); + var totalProducts = repository.listaProdutos.Count; + var Id = 3; + var product = new ProductEntity() { Name = "ProductUpdated", Brand = "BrandUpdated", Price = 9.99 }; + repository.Update(product, Id); + var Index = repository.listaProdutos.FindIndex(x => x.Id == Id); + Assert.IsTrue(repository.listaProdutos[Index].Name == "ProductUpdated"); + Assert.IsTrue(repository.listaProdutos[Index].Brand == "BrandUpdated"); + Assert.IsTrue(repository.listaProdutos[Index].Price == 9.99); + } + + [TestMethod] + [TestCategory("Product")] + public void Should_Delete_Product() + { + var repository = new FakeRepository(); + var totalProducts = repository.listaProdutos.Count; + repository.Delete(2); + Assert.IsTrue(repository.listaProdutos.Count < totalProducts); + } + } +} diff --git a/ApiDotNetFramework/ApiDotNetFramework.Tests/Properties/AssemblyInfo.cs b/ApiDotNetFramework/ApiDotNetFramework.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..766594d --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ApiDotNetFramework.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ApiDotNetFramework.Tests")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("939d1ed1-8075-45ec-ba70-067aa23339dd")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ApiDotNetFramework/ApiDotNetFramework.sln b/ApiDotNetFramework/ApiDotNetFramework.sln new file mode 100644 index 0000000..91d91e9 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiDotNetFramework", "ApiDotNetFramework\ApiDotNetFramework.csproj", "{F9D9CCC3-632A-46A0-957B-68794F4F218A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiDotNetFramework.Tests", "ApiDotNetFramework.Tests\ApiDotNetFramework.Tests.csproj", "{939D1ED1-8075-45EC-BA70-067AA23339DD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F9D9CCC3-632A-46A0-957B-68794F4F218A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F9D9CCC3-632A-46A0-957B-68794F4F218A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F9D9CCC3-632A-46A0-957B-68794F4F218A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F9D9CCC3-632A-46A0-957B-68794F4F218A}.Release|Any CPU.Build.0 = Release|Any CPU + {939D1ED1-8075-45EC-BA70-067AA23339DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {939D1ED1-8075-45EC-BA70-067AA23339DD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {939D1ED1-8075-45EC-BA70-067AA23339DD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {939D1ED1-8075-45EC-BA70-067AA23339DD}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/ApiDotNetFramework/ApiDotNetFramework/ApiDotNetFramework.csproj b/ApiDotNetFramework/ApiDotNetFramework/ApiDotNetFramework.csproj new file mode 100644 index 0000000..207b28e --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/ApiDotNetFramework.csproj @@ -0,0 +1,180 @@ + + + + + + + Debug + AnyCPU + + + 2.0 + {F9D9CCC3-632A-46A0-957B-68794F4F218A} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + ApiDotNetFramework + ApiDotNetFramework + v4.5.2 + true + + + + + + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + + + + ..\packages\Microsoft.ApplicationInsights.Agent.Intercept.1.2.1\lib\net45\Microsoft.AI.Agent.Intercept.dll + True + + + ..\packages\Microsoft.ApplicationInsights.DependencyCollector.2.0.0\lib\net45\Microsoft.AI.DependencyCollector.dll + True + + + ..\packages\Microsoft.ApplicationInsights.PerfCounterCollector.2.0.0\lib\net45\Microsoft.AI.PerfCounterCollector.dll + True + + + ..\packages\Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.2.0.0\lib\net45\Microsoft.AI.ServerTelemetryChannel.dll + True + + + ..\packages\Microsoft.ApplicationInsights.Web.2.0.0\lib\net45\Microsoft.AI.Web.dll + True + + + ..\packages\Microsoft.ApplicationInsights.WindowsServer.2.0.0\lib\net45\Microsoft.AI.WindowsServer.dll + True + + + ..\packages\Microsoft.ApplicationInsights.2.0.0\lib\net45\Microsoft.ApplicationInsights.dll + True + + + ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll + True + + + + + + + + + + + + + + + + + + + + + + + ..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll + + + ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + + + ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + + + ..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll + + + + + + + + + + + + Global.asax + + + + + + + + + + + PreserveNewest + + + Web.config + + + Web.config + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + True + True + 53455 + / + http://localhost:5002/ + False + False + + + False + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/App_Start/WebApiConfig.cs b/ApiDotNetFramework/ApiDotNetFramework/App_Start/WebApiConfig.cs new file mode 100644 index 0000000..592ada7 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/App_Start/WebApiConfig.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Http; + +namespace ApiDotNetFramework +{ + public static class WebApiConfig + { + public static void Register(HttpConfiguration config) + { + // Web API configuration and services + + // Web API routes + config.MapHttpAttributeRoutes(); + + config.Routes.MapHttpRoute( + name: "DefaultApi", + routeTemplate: "api/{controller}/{id}", + defaults: new { id = RouteParameter.Optional } + ); + } + } +} diff --git a/ApiDotNetFramework/ApiDotNetFramework/ApplicationInsights.config b/ApiDotNetFramework/ApiDotNetFramework/ApplicationInsights.config new file mode 100644 index 0000000..ee9ea3c --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/ApplicationInsights.config @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + System.Web.Handlers.TransferRequestHandler + Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler + System.Web.StaticFileHandler + System.Web.Handlers.AssemblyResourceLoader + System.Web.Optimization.BundleHandler + System.Web.Script.Services.ScriptHandlerFactory + System.Web.Handlers.TraceHandler + System.Web.Services.Discovery.DiscoveryRequestHandler + System.Web.HttpDebugHandler + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/Controllers/ProductController.cs b/ApiDotNetFramework/ApiDotNetFramework/Controllers/ProductController.cs new file mode 100644 index 0000000..cb1fa05 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Controllers/ProductController.cs @@ -0,0 +1,118 @@ +using ApiDotNetFramework.Entities; +using ApiDotNetFramework.Repositories; +using ApiDotNetFramework.ViewModels; +using System; +using System.Net; +using System.Net.Http; +using System.Web.Http; + +namespace ApiDotNetFramework.Controllers +{ + public class ProductController : ApiController + { + private SqlServerRepository respository = new SqlServerRepository(); + + [HttpGet] + [Route("api/v1/products")] + public HttpResponseMessage Get() + { + try + { + var data = respository.GetAll(); + return Request.CreateResponse(HttpStatusCode.OK, new ResultViewModel(data)); + } + catch + { + return Request.CreateResponse(HttpStatusCode.InternalServerError, "Internal server error"); + } + } + + [HttpGet] + [Route("api/v1/products/{productId}")] + public HttpResponseMessage GetById( + [FromUri] int productId) + { + try + { + var data = respository.GetById(productId); + return Request.CreateResponse(HttpStatusCode.OK, new ResultViewModel(data)); + } + catch + { + return Request.CreateResponse(HttpStatusCode.InternalServerError, "Internal server error"); + } + } + + + [HttpPost] + [Route("api/v1/products")] + public HttpResponseMessage Post(ProductEntity product) + { + + if (!ModelState.IsValid) + return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); + try + { + var id = respository.Insert(product); + product.Id = id; + product.CreatedAt = DateTime.Now; + return Request.CreateResponse(HttpStatusCode.Created, new ResultViewModel(product)); + } + catch (Exception) + { + return Request.CreateResponse(HttpStatusCode.InternalServerError, "Error to create product. "); + } + } + + [HttpPut] + [Route("api/v1/products/{productId}")] + public HttpResponseMessage Put( + ProductEntity product, + [FromUri] int productId) + { + + if (!ModelState.IsValid) + return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); + try + { + var data = respository.GetById(productId); + if (data == null) + return Request.CreateResponse(HttpStatusCode.NoContent, new ResultViewModel(data)); + + data.Name = product.Name; + data.Brand = product.Brand; + data.Price = product.Price; + data.UpdatedAt = DateTime.Now; + respository.Update(data, productId); + + return Request.CreateResponse(HttpStatusCode.OK, new ResultViewModel(data)); + } + catch (Exception) + { + return Request.CreateResponse(HttpStatusCode.InternalServerError, "Error to update product. "); + } + } + + + [HttpDelete] + [Route("api/v1/products/{productId}")] + public HttpResponseMessage Delete( + [FromUri] int productId) + { + try + { + var data = respository.GetById(productId); + if(data == null) + return Request.CreateResponse(HttpStatusCode.NoContent, new ResultViewModel(data)); + + respository.Delete(productId); + return Request.CreateResponse(HttpStatusCode.OK, new ResultViewModel("")); + } + catch (Exception) + { + return Request.CreateResponse(HttpStatusCode.InternalServerError, "Error to update product. "); + } + } + + } +} \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/Entities/ProductEntity.cs b/ApiDotNetFramework/ApiDotNetFramework/Entities/ProductEntity.cs new file mode 100644 index 0000000..a274bc0 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Entities/ProductEntity.cs @@ -0,0 +1,30 @@ +using System; +using System.ComponentModel.DataAnnotations; + +namespace ApiDotNetFramework.Entities +{ + public class ProductEntity + { + public int Id { get; set; } + [Required(ErrorMessage = "the field name missing.")] + public string Name { get; set; } + public string Brand { get; set; } + [Required(ErrorMessage = "the filed price missing.")] + public double Price { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime? UpdatedAt { get; set; } + + public ProductEntity() + { + + } + + public ProductEntity(string name, string brand, double price) + { + Name = name; + Brand = brand; + Price = price; + } + + } +} \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/Global.asax b/ApiDotNetFramework/ApiDotNetFramework/Global.asax new file mode 100644 index 0000000..357e9cf --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Global.asax @@ -0,0 +1 @@ +<%@ Application Codebehind="Global.asax.cs" Inherits="ApiDotNetFramework.WebApiApplication" Language="C#" %> diff --git a/ApiDotNetFramework/ApiDotNetFramework/Global.asax.cs b/ApiDotNetFramework/ApiDotNetFramework/Global.asax.cs new file mode 100644 index 0000000..71c1be1 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Global.asax.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Http; +using System.Web.Routing; + +namespace ApiDotNetFramework +{ + public class WebApiApplication : System.Web.HttpApplication + { + protected void Application_Start() + { + GlobalConfiguration.Configure(WebApiConfig.Register); + } + } +} diff --git a/ApiDotNetFramework/ApiDotNetFramework/Interfaces/IRepository.cs b/ApiDotNetFramework/ApiDotNetFramework/Interfaces/IRepository.cs new file mode 100644 index 0000000..e62650e --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Interfaces/IRepository.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace ApiDotNetFramework.Interfaces +{ + public interface IRepository where TEntity : class + { + List GetAll(); + TEntity GetById(TKey id); + int Insert(TEntity entity); + void Update(TEntity entity, TKey id); + void Delete(TKey id); + } +} diff --git a/ApiDotNetFramework/ApiDotNetFramework/Properties/AssemblyInfo.cs b/ApiDotNetFramework/ApiDotNetFramework/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..35d0180 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ApiDotNetFramework")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ApiDotNetFramework")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f9d9ccc3-632a-46a0-957b-68794f4f218a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ApiDotNetFramework/ApiDotNetFramework/Repositories/FakeRepository.cs b/ApiDotNetFramework/ApiDotNetFramework/Repositories/FakeRepository.cs new file mode 100644 index 0000000..14edcc1 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Repositories/FakeRepository.cs @@ -0,0 +1,74 @@ +using ApiDotNetFramework.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; + +namespace ApiDotNetFramework.Repositories +{ + public class FakeRepository + { + public List listaProdutos; + + public FakeRepository() + { + listaProdutos = new List(); + listaProdutos.Add(new ProductEntity() { Id = 1, Name = "Product01", Brand = "Brand01", Price = 2.0 }); + listaProdutos.Add(new ProductEntity() { Id = 2, Name = "Product02", Brand = "Brand02", Price = 2.5 }); + listaProdutos.Add(new ProductEntity() { Id = 3, Name = "Product03", Brand = "Brand03", Price = 1.2 }); + listaProdutos.Add(new ProductEntity() { Id = 4, Name = "Product04", Brand = "Brand04", Price = 7.7 }); + listaProdutos.Add(new ProductEntity() { Id = 5, Name = "Product05", Brand = "Brand05", Price = 4.3 }); + listaProdutos.Add(new ProductEntity() { Id = 6, Name = "Product06", Brand = "Brand06", Price = 5.1 }); + } + + public List GetAll() + { + return listaProdutos; + } + + public ProductEntity GetById(int id) + { + return listaProdutos.FirstOrDefault(x => x.Id == id); + } + + public int Insert(ProductEntity entity) + { + var maxId = listaProdutos.Max(t => t.Id); + maxId++; + + var produto = new ProductEntity(){ + Id = maxId, + Name = entity.Name, + Brand = entity.Brand, + Price = entity.Price, + CreatedAt = DateTime.Now + }; + listaProdutos.Add(produto); + return maxId; + } + + public void Update(ProductEntity entity, int id) + { + var index = listaProdutos.FindIndex(t => t.Id == id); + + if (index != null) + { + listaProdutos[index].Name = entity.Name; + listaProdutos[index].Brand = entity.Brand; + listaProdutos[index].Price = entity.Price; + listaProdutos[index].UpdatedAt = DateTime.Now; + } + } + + public void Delete(int id) + { + var index = listaProdutos.FindIndex(t => t.Id == id); + + if (index != null) + { + listaProdutos.RemoveAt(index); + + } + } + } +} \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/Repositories/SqlServerRepository.cs b/ApiDotNetFramework/ApiDotNetFramework/Repositories/SqlServerRepository.cs new file mode 100644 index 0000000..fe86560 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Repositories/SqlServerRepository.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using ApiDotNetFramework.Interfaces; +using System.Web.Configuration; +using ApiDotNetFramework.Entities; +using System.Data.SqlClient; +using System.Data; +using System.Configuration; + +namespace ApiDotNetFramework.Repositories +{ + public class SqlServerRepository : IRepository + { + protected string stringConnection; + public SqlServerRepository() + { + stringConnection = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString; + } + + public List GetAll() + { + using (var conn = new SqlConnection(stringConnection)) + { + List listaProdutos = new List(); + ProductEntity produto = null; + try + { + SqlCommand cmd = new SqlCommand("sp_select_products", conn); + cmd.CommandType = CommandType.StoredProcedure; + conn.Open(); + using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) + { + while (reader.Read()) + { + produto = new ProductEntity() + { + CreatedAt = (DateTime)reader["createdAt"], + Name = reader["name"].ToString(), + Price = (double)reader["price"], + Brand = reader["brand"].ToString(), + UpdatedAt = (DateTime?)reader["updatedAt"], + Id = (int)reader["id"], + }; + listaProdutos.Add(produto); + } + } + } + catch (Exception error) + { + throw error; + } + return listaProdutos; + } + } + + public ProductEntity GetById(int id) + { + using (var conn = new SqlConnection(stringConnection)) + { + ProductEntity produto = null; + try + { + SqlCommand cmd = new SqlCommand("sp_select_products", conn); + cmd.CommandType = CommandType.StoredProcedure; + conn.Open(); + cmd.Parameters.AddWithValue("@id", id); + using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) + { + while (reader.Read()) + { + produto = new ProductEntity() + { + CreatedAt = (DateTime)reader["createdAt"], + Name = reader["name"].ToString(), + Price = (double)reader["price"], + Brand = reader["brand"].ToString(), + UpdatedAt = (DateTime?)reader["updatedAt"], + Id = (int)reader["id"], + }; + } + } + } + catch (Exception error) + { + throw error; + } + return produto; + } + } + + public int Insert(ProductEntity entity) + { + using (var conn = new SqlConnection(stringConnection)) + { + try + { + var cmd = new SqlCommand("sp_insert_products", conn); + conn.Open(); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue("@name", entity.Name); + cmd.Parameters.AddWithValue("@brand", entity.Brand); + cmd.Parameters.AddWithValue("@price", entity.Price); + + SqlParameter id = new SqlParameter(); + id.ParameterName = "@id"; + id.Direction = ParameterDirection.Output; + id.SqlDbType = SqlDbType.Int; + cmd.Parameters.Add(id); + + cmd.ExecuteNonQuery(); + + return (int)id.Value; + } + catch (Exception error) + { + + throw error; + } + + } + } + + public void Update(ProductEntity entity, int id) + { + using (var conn = new SqlConnection(stringConnection)) + { + try + { + var cmd = new SqlCommand("sp_update_products", conn); + conn.Open(); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue("@id", id); + cmd.Parameters.AddWithValue("@name", entity.Name); + cmd.Parameters.AddWithValue("@brand", entity.Brand); + cmd.Parameters.AddWithValue("@price", entity.Price); + cmd.ExecuteNonQuery(); + + } + catch (Exception error) + { + throw error; + } + + } + } + + public void Delete(int id) + { + using (var conn = new SqlConnection(stringConnection)) + { + try + { + var cmd = new SqlCommand("sp_delete_products", conn); + conn.Open(); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue("@id", id); + cmd.ExecuteNonQuery(); + } + catch (Exception error) + { + throw error; + } + + } + } + + } +} \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/ViewModels/ResultViewModel.cs b/ApiDotNetFramework/ApiDotNetFramework/ViewModels/ResultViewModel.cs new file mode 100644 index 0000000..0ef764a --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/ViewModels/ResultViewModel.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; + +namespace ApiDotNetFramework.ViewModels +{ + public class ResultViewModel + { + public ResultViewModel(T data, List errors) + { + Data = data; + Errors = errors; + } + + public ResultViewModel(T data) + { + Data = data; + + } + + public ResultViewModel(List errors) + { + Errors = errors; + } + + public ResultViewModel(string error) + { + Errors.Add(error); + } + + + + public T Data { get; private set; } + + public List Errors { get; private set; } = new List(); + } +} \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/Web.Debug.config b/ApiDotNetFramework/ApiDotNetFramework/Web.Debug.config new file mode 100644 index 0000000..c19fe7c --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Web.Debug.config @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/Web.Release.config b/ApiDotNetFramework/ApiDotNetFramework/Web.Release.config new file mode 100644 index 0000000..c358444 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Web.Release.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/ApiDotNetFramework/ApiDotNetFramework/Web.config b/ApiDotNetFramework/ApiDotNetFramework/Web.config new file mode 100644 index 0000000..cd3f1d7 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/Web.config @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ApiDotNetFramework/ApiDotNetFramework/packages.config b/ApiDotNetFramework/ApiDotNetFramework/packages.config new file mode 100644 index 0000000..54dcd93 --- /dev/null +++ b/ApiDotNetFramework/ApiDotNetFramework/packages.config @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ApiDotNetGateway/ApiDotNetGateway.sln b/ApiDotNetGateway/ApiDotNetGateway.sln new file mode 100644 index 0000000..d519ead --- /dev/null +++ b/ApiDotNetGateway/ApiDotNetGateway.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32630.192 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiDotNetGateway", "ApiDotNetGateway\ApiDotNetGateway.csproj", "{599F7D03-B4E5-4570-95F9-A08225EEC39A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {599F7D03-B4E5-4570-95F9-A08225EEC39A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {599F7D03-B4E5-4570-95F9-A08225EEC39A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {599F7D03-B4E5-4570-95F9-A08225EEC39A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {599F7D03-B4E5-4570-95F9-A08225EEC39A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {83BCA4D9-86A9-45FB-B9D7-B011DAA665E4} + EndGlobalSection +EndGlobal diff --git a/ApiDotNetGateway/ApiDotNetGateway/ApiDotNetGateway.csproj b/ApiDotNetGateway/ApiDotNetGateway/ApiDotNetGateway.csproj new file mode 100644 index 0000000..3af46f9 --- /dev/null +++ b/ApiDotNetGateway/ApiDotNetGateway/ApiDotNetGateway.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/ApiDotNetGateway/ApiDotNetGateway/Properties/launchSettings.json b/ApiDotNetGateway/ApiDotNetGateway/Properties/launchSettings.json new file mode 100644 index 0000000..21be2fc --- /dev/null +++ b/ApiDotNetGateway/ApiDotNetGateway/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:23142", + "sslPort": 44333 + } + }, + "profiles": { + "ApiDotNetGateway": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7003;http://localhost:5003", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/ApiDotNetGateway/ApiDotNetGateway/appsettings.Development.json b/ApiDotNetGateway/ApiDotNetGateway/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/ApiDotNetGateway/ApiDotNetGateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/ApiDotNetGateway/ApiDotNetGateway/appsettings.json b/ApiDotNetGateway/ApiDotNetGateway/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/ApiDotNetGateway/ApiDotNetGateway/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/ApiDotNetGateway/ApiDotNetGateway/ocelot.json b/ApiDotNetGateway/ApiDotNetGateway/ocelot.json new file mode 100644 index 0000000..b72b65f --- /dev/null +++ b/ApiDotNetGateway/ApiDotNetGateway/ocelot.json @@ -0,0 +1,41 @@ +{ + "GlobalConfiguration": { + "GlobalConfiguration": { + "BaseUrl": "http://localhost:5003" + } + }, + "ReRoutes": [ + { + "DownstreamPathTemplate": "/api/{version}/{everything}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 5001 + } + ], + "UpstreamPathTemplate": "/api/{version}/c/{everything}", + "UpstreamHttpMethod": [ "POST", "PUT", "GET" ], + "AuthenticationOptions": { + "AuthenticationProviderKey": "IdentityApiKey", + "AllowedScopes": [] + } + }, + { + "DownstreamPathTemplate": "/api/{version}/{everything}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 5002 + } + ], + "UpstreamPathTemplate": "/api/{version}/c/{everything}", + "UpstreamHttpMethod": [ "POST", "PUT", "GET" ], + "AuthenticationOptions": { + "AuthenticationProviderKey": "IdentityApiKey", + "AllowedScopes": [] + } + } + ] +} \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..f6e7fe7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,12 @@ +version: '3' +services: + sqlserver: + image: mcr.microsoft.com/mssql/server + container_name: SQLSERVER + environment: + - ACCEPT_EULA=Y + - SA_PASSWORD=1q2w3e4r@ + ports: + - "1433:1433" + volumes: + - .\Database:/var/opt/mssql/data