Skip to content

create and update product functionality added #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,9 @@
*.log
node_modules/
.env
*.dll
*.json
secrets.json
*.pdb
*.cache
*.exe
11 changes: 11 additions & 0 deletions DotNetProductPOC.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ VisualStudioVersion = 17.10.34916.146
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProductPOC", "ProductPOC\ProductPOC.csproj", "{496C8E95-4055-4607-9054-00D38CA996E7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProductTest", "ProductTest\ProductTest.csproj", "{27D1FB12-2F27-4ADB-862E-34858D9F6682}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{06687533-3FE8-4964-842B-0BC5BD787A94}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +22,10 @@ Global
{496C8E95-4055-4607-9054-00D38CA996E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{496C8E95-4055-4607-9054-00D38CA996E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{496C8E95-4055-4607-9054-00D38CA996E7}.Release|Any CPU.Build.0 = Release|Any CPU
{27D1FB12-2F27-4ADB-862E-34858D9F6682}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{27D1FB12-2F27-4ADB-862E-34858D9F6682}.Debug|Any CPU.Build.0 = Debug|Any CPU
{27D1FB12-2F27-4ADB-862E-34858D9F6682}.Release|Any CPU.ActiveCfg = Release|Any CPU
{27D1FB12-2F27-4ADB-862E-34858D9F6682}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
67 changes: 67 additions & 0 deletions ProductPOC/Controllers/ProductController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using ProductPOC.Dto;
using ProductPOC.Models;
using ProductPOC.Service;

namespace ProductPOC.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
private readonly IProductService _productService;
private readonly IMapper _mapper;
public ProductController(IProductService productService, IMapper mapper)
{
_productService = productService;
_mapper = mapper;
}

[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<IEnumerable<ProductDto>>> GetProducts()
{
var products = await _productService.GetAllProductsAsync();
var productDtos= _mapper.Map<IEnumerable<ProductDto>>(products);
return Ok(productDtos);
}

[HttpGet]
[Route("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<IEnumerable<ProductDto>>> GetByIdProduct([FromRoute] Guid id)
{
var product = await _productService.GetByIdProductAsync(id);
var productDtos = _mapper.Map<ProductDto>(product);
return Ok(productDtos);
}

[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
public async Task<IActionResult> CreateProduct([FromBody] CreateProductDto createProductDto)
{
var product= _mapper.Map<Product>(createProductDto);
product= await _productService.CreateProductAsync(product);
var productDto= _mapper.Map<ProductDto>(product);
return CreatedAtAction(nameof(GetByIdProduct), new { id = productDto.Id }, productDto);
}

[HttpPut]
[Route("{id}")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateProduct([FromRoute] Guid id, [FromBody] UpdateProductDto updateProductDto)
{
var product = _mapper.Map<Product>(updateProductDto);
product = await _productService.UpdateProductAsync(id, product);
if (product == null)
{
return NotFound();
}
var productDto = _mapper.Map<ProductDto>(product);
return AcceptedAtAction(nameof(GetByIdProduct), new { id = productDto.Id }, productDto);
}
}
}
10 changes: 10 additions & 0 deletions ProductPOC/DbContext/IProductDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using MongoDB.Driver;
using ProductPOC.Models;

namespace ProductPOC.DbContext
{
public interface IProductDbContext
{
IMongoCollection<Product> Products { get; }
}
}
29 changes: 29 additions & 0 deletions ProductPOC/DbContext/ProductDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using ProductPOC.Models;

namespace ProductPOC.DbContext
{
public class ProductDbContext:IProductDbContext
{
private readonly IMongoDatabase _database;
private readonly string _productsCollectionName;

public ProductDbContext()
{

}
public ProductDbContext(IConfiguration configuration)
{
var connectionString = configuration["ConnectionStrings:MongoDb"];
var databaseName = configuration["ConnectionStrings:DatabaseName"];
_productsCollectionName = configuration["ConnectionStrings:ProductsCollectionName"];
var client = new MongoClient(connectionString);
_database = client.GetDatabase(databaseName);

}


public virtual IMongoCollection<Product> Products => _database.GetCollection<Product>(_productsCollectionName);
}
}
9 changes: 9 additions & 0 deletions ProductPOC/Dto/CreateProductDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace ProductPOC.Dto
{
public class CreateProductDto
{
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
10 changes: 10 additions & 0 deletions ProductPOC/Dto/ProductDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace ProductPOC.Dto
{
public class ProductDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
9 changes: 9 additions & 0 deletions ProductPOC/Dto/UpdateProductDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace ProductPOC.Dto
{
public class UpdateProductDto
{
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
16 changes: 16 additions & 0 deletions ProductPOC/Mappings/AutoMapperProfiles.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using AutoMapper;
using ProductPOC.Dto;
using ProductPOC.Models;
namespace ProductPOC.Mappings
{
public class AutoMapperProfiles:Profile
{
public AutoMapperProfiles()
{
CreateMap<Product,ProductDto>().ReverseMap();
CreateMap<Product,CreateProductDto>().ReverseMap();
CreateMap<Product,UpdateProductDto>().ReverseMap();
}

}
}
21 changes: 21 additions & 0 deletions ProductPOC/Models/Product.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;

namespace ProductPOC.Models
{
public class Product
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public Guid Id { get; set; }

[BsonElement("name")]
public string Name { get; set; }

[BsonElement("description")]
public string Description { get; set; }

[BsonElement("price")]
public decimal Price { get; set; }
}
}
9 changes: 4 additions & 5 deletions ProductPOC/ProductPOC.csproj
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>e8774c96-ba4d-4773-b837-687e85197ffd</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="MongoDB.Driver" Version="2.25.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

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

</Project>
2 changes: 2 additions & 0 deletions ProductPOC/ProductPOC.csproj.user
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
</Project>
12 changes: 12 additions & 0 deletions ProductPOC/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using ProductPOC.DbContext;
using ProductPOC.Mappings;
using ProductPOC.Repository;
using ProductPOC.Service;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
Expand All @@ -6,6 +12,12 @@
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ProductDbContext>();

// Dependency injection for repositories and services
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddAutoMapper(typeof(AutoMapperProfiles));

var app = builder.Build();

Expand Down
12 changes: 12 additions & 0 deletions ProductPOC/Repository/IProductRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using ProductPOC.Models;

namespace ProductPOC.Repository
{
public interface IProductRepository
{
Task<IEnumerable<Product>> GetAllAsync();
Task<Product> GetByIdAsync(Guid id);
Task<Product> CreateAsync(Product product);
Task<Product> UpdateAsync(Guid id,Product product);
}
}
44 changes: 44 additions & 0 deletions ProductPOC/Repository/ProductRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using MongoDB.Driver;
using ProductPOC.DbContext;
using ProductPOC.Models;

namespace ProductPOC.Repository
{
public class ProductRepository : IProductRepository
{
private readonly IMongoCollection<Product> _products;
public ProductRepository(ProductDbContext context)
{
_products = context.Products;
}

public async Task<Product> CreateAsync(Product product)
{
await _products.InsertOneAsync(product);
return product;
}

public async Task<IEnumerable<Product>> GetAllAsync() =>
await _products.Find(p => true).ToListAsync();

public async Task<Product> GetByIdAsync(Guid id)
{
return await _products.Find(x=>x.Id==id).FirstOrDefaultAsync();
}

public async Task<Product> UpdateAsync(Guid id, Product product)
{
var existingProduct = await _products.Find(x => x.Id == id).FirstOrDefaultAsync();
if (existingProduct == null)
{
return null;
}
existingProduct.Name = product.Name;
existingProduct.Description = product.Description;
existingProduct.Price = product.Price;
var result = await _products.ReplaceOneAsync(x => x.Id == id, existingProduct);
return existingProduct;
}

}
}
12 changes: 12 additions & 0 deletions ProductPOC/Service/IProductService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using ProductPOC.Models;

namespace ProductPOC.Service
{
public interface IProductService
{
Task<IEnumerable<Product>> GetAllProductsAsync();
Task<Product> GetByIdProductAsync(Guid id);
Task<Product> CreateProductAsync(Product product);
Task<Product> UpdateProductAsync(Guid id,Product product);
}
}
39 changes: 39 additions & 0 deletions ProductPOC/Service/ProductService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using ProductPOC.Models;
using ProductPOC.Repository;

namespace ProductPOC.Service
{
public class ProductService : IProductService
{
private readonly IProductRepository _productRepository;

public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}

public async Task<Product> CreateProductAsync(Product product)
{
if(product.Id == Guid.Empty)
{
product.Id = Guid.NewGuid();
}
return await _productRepository.CreateAsync(product);
}

public async Task<IEnumerable<Product>> GetAllProductsAsync()
{
return await _productRepository.GetAllAsync();
}

public async Task<Product> GetByIdProductAsync(Guid id)
{
return await _productRepository.GetByIdAsync(id);
}

public async Task<Product> UpdateProductAsync(Guid id, Product product)
{
return await _productRepository.UpdateAsync(id, product);
}
}
}
Binary file added ProductPOC/bin/Debug/net8.0/AWSSDK.Core.dll
Binary file not shown.
Binary file not shown.
Binary file added ProductPOC/bin/Debug/net8.0/AutoMapper.dll
Binary file not shown.
Binary file added ProductPOC/bin/Debug/net8.0/DnsClient.dll
Binary file not shown.
Binary file not shown.
Binary file added ProductPOC/bin/Debug/net8.0/MongoDB.Bson.dll
Binary file not shown.
Binary file not shown.
Binary file added ProductPOC/bin/Debug/net8.0/MongoDB.Driver.dll
Binary file not shown.
Binary file not shown.
Loading