Skip to content
Open
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
137 changes: 137 additions & 0 deletions UserManagement/UserMan/UserMan.API/Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using UserMan.API.Dto;
using UserMan.DataAccess.Implementation;
using UserMan.Domain.Entities;
using UserMan.Domain.Repository;

namespace UserMan.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private IUnitOfWork _unitOfWork;
private IMapper _mapper;

public UserController(IUnitOfWork unitOfWork,IMapper mapper)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
}

[HttpGet]
[Route("GetAllUsers")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public ActionResult<ApiResponse> Get()
{
try
{
var users = _unitOfWork.User.GetAll();
if (users == null)
{
return new ApiResponse { StatusCode = HttpStatusCode.NotFound, Messages = "No User Found"};
}
return new ApiResponse { StatusCode = HttpStatusCode.OK, IsSuccess = true, Result = users };
}
catch (Exception ex)
{
return new ApiResponse { StatusCode = HttpStatusCode.InternalServerError, Messages = ex.Message,IsSuccess=false };
}
}


[HttpGet]
[Route("GetAUser")]
public ActionResult<ApiResponse> Get(int id)
{
try
{
var user = _unitOfWork.User.Get(id);
if (user == null)
{
return new ApiResponse { StatusCode = HttpStatusCode.NotFound, Messages = "No User Found" };
}
return new ApiResponse { StatusCode = HttpStatusCode.OK, IsSuccess = true, Result = user };
}
catch (Exception ex)
{
return new ApiResponse { StatusCode = HttpStatusCode.InternalServerError, Messages = ex.Message, IsSuccess = false };
}
}


[HttpPost]
public ActionResult<ApiResponse> CreateUser(UserDto user)
{
try
{
if (user == null)
{
return new ApiResponse { StatusCode = HttpStatusCode.BadRequest, Messages = "Invalid Operation" };
}
var newUser = _mapper.Map<User>(user);
_unitOfWork.User.Add(newUser);
return new ApiResponse { StatusCode = HttpStatusCode.Created, IsSuccess = true, Messages = "User Profile Created Successfully" };
}
catch (Exception ex)
{
return new ApiResponse { StatusCode = HttpStatusCode.InternalServerError, Messages = ex.Message, IsSuccess = false };
}
}

[HttpPut]
public IActionResult UpdateUser(UserDto user)
{
if (user == null)
{
return BadRequest();
}
var updatedUser = _mapper.Map<User>(user);
_unitOfWork.User.Update(updatedUser);
return Ok();
}

[HttpDelete]
public IActionResult DeleteUser(int id)
{
_unitOfWork.User.Delete(id);
return Ok();

}


[HttpGet("FindUser")]
public ActionResult<ApiResponse> FindUsers(int? age, string? gender, string? maritalStatus, string? location)
{
try
{
var users = _unitOfWork.User.Find(u =>
(!age.HasValue || u.Age == age.Value) &&
(string.IsNullOrEmpty(gender) || u.Gender.ToLower() == gender.ToLower()) &&
(string.IsNullOrEmpty(maritalStatus) || u.MaritalStatus.ToLower() == maritalStatus.ToLower()) &&
(string.IsNullOrEmpty(location) || u.Location.ToLower() == location.ToLower())).ToList();
if (users.Count == 0)
{
return new ApiResponse { StatusCode = HttpStatusCode.NotFound, Messages = "No User Found", IsSuccess = false };
}
else
{
return new ApiResponse { StatusCode = HttpStatusCode.OK, IsSuccess = true, Result = users };
}
}
catch (Exception ex)
{
return new ApiResponse { StatusCode = HttpStatusCode.InternalServerError, IsSuccess = false, Messages = ex.Message };
}
}


}
}
12 changes: 12 additions & 0 deletions UserManagement/UserMan/UserMan.API/Dto/ApiResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Net;

namespace UserMan.API.Dto
{
public class ApiResponse
{
public HttpStatusCode StatusCode { get; set; } = HttpStatusCode.OK;
public bool IsSuccess { get; set; } = false;
public string Messages { get; set; } = string.Empty;
public object Result { get; set; }
}
}
11 changes: 11 additions & 0 deletions UserManagement/UserMan/UserMan.API/Dto/UserDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace UserMan.API.Dto
{
public class UserDto
{
public string Name { get; set; } = string.Empty;
public int Age { get; set; }
public string Gender { get; set; } = string.Empty;
public string MaritalStatus { get; set; } = string.Empty;
public string Location { get; set; } = string.Empty;
}
}
14 changes: 14 additions & 0 deletions UserManagement/UserMan/UserMan.API/Helper/Automapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using AutoMapper;
using UserMan.API.Dto;
using UserMan.Domain.Entities;

namespace UserMan.API.Helper
{
public class Automapper : Profile
{
public Automapper()
{
CreateMap<User,UserDto>().ReverseMap();
}
}
}
51 changes: 51 additions & 0 deletions UserManagement/UserMan/UserMan.API/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using UserMan.DataAccess.Generator.DataGenerator;
using UserMan.DataAccess.Implementation;
using UserMan.Domain.Repository;
using UserMan.Infrastructure.Data.ApplicationDbContext;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{ options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")); });
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddScoped<DataGenerator>();


var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<ApplicationDbContext>();
var generator = services.GetRequiredService<DataGenerator>();
generator.GenerateAndInsertFakeUsers(1000);
}


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}



app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

31 changes: 31 additions & 0 deletions UserManagement/UserMan/UserMan.API/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:60853",
"sslPort": 44372
}
},
"profiles": {
"UserMan.API": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7265;http://localhost:5062",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
24 changes: 24 additions & 0 deletions UserManagement/UserMan/UserMan.API/UserMan.API.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Ulid" Version="1.2.6" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\UserMan.DataAccess\UserMan.DataAccess.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
10 changes: 10 additions & 0 deletions UserManagement/UserMan/UserMan.API/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"ConnectionStrings": { "DefaultConnection": "server=LAPTOP-C6680A7T\\SQLEXPRESS;database=UserMan;Integrated Security=true;" },
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\UserMan.Domain\UserMan.Domain.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserMan.Domain.Entities;

namespace UserMan.Infrastructure.Data.ApplicationDbContext
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{

}

public DbSet<User> Users { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Bogus;
using UserMan.Domain.Entities;
using UserMan.Infrastructure.Data.ApplicationDbContext;

namespace UserMan.DataAccess.Generator.DataGenerator
{
public class DataGenerator
{
private readonly Faker<User> _fakeUser;
private readonly ApplicationDbContext _context;

public DataGenerator(ApplicationDbContext context)
{
_context = context;

Randomizer.Seed = new Random(Seed: 123);

_fakeUser = new Faker<User>()
//.RuleFor(u => u.Id, f => f.Random.Int(min: 10, max: 1000000))
.RuleFor(u => u.Name, f => f.Name.FullName())
.RuleFor(u => u.Age, f => f.Random.Int(min: 18, max: 65))
.RuleFor(u => u.Gender, f => f.PickRandom(new[] { "Male", "Female" }))
.RuleFor(u => u.MaritalStatus, f => f.PickRandom(new[] { "Single", "Married", "Divorced", "Widowed" }))
.RuleFor(u => u.Location, f => f.Address.City());
}

public void GenerateAndInsertFakeUsers(int count)
{
var users = _fakeUser.Generate(1000);

_context.Users.UpdateRange(users);
_context.SaveChanges();
}
}
}
Loading