main
Gerardo 2025-07-08 11:21:03 +02:00
commit 4983028361
75 changed files with 1898 additions and 0 deletions

16
.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
/mqttApi/.vs/*
/mqttApi/src/Mqtt.App.api/bin/*
/mqttApi/src/Mqtt.App.api/obj/*
/mqttApi/src/Mqtt.App.Application/bin/*
/mqttApi/src/Mqtt.App.Application/obj/*
/mqttApi/src/Mqtt.App.Common/bin/*
/mqttApi/src/Mqtt.App.Common/obj/*
/mqttLog/mqttLog/obj/*
/mqttLog/mqttLog/bin/*
/mqttLog/mqttLog/.vs/*
/mqttApi/src/Mqtt.App.Domain/obj/*
/mqttApi/src/Mqtt.App.Domain/bin/*
/mqttApi/src/Mqtt.App.External/bin/*
/mqttApi/src/Mqtt.App.External/obj/*
/mqttApi/src/Mqtt.app.Persistencia/bin/*
/mqttApi/src/Mqtt.app.Persistencia/obj/*

83
mqttApi/MqttApi.sln Normal file
View File

@ -0,0 +1,83 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34723.18
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Api", "Api", "{88D481B0-BD9D-4732-9AE0-4707AE616E01}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{609A233D-1C2C-4041-A03B-F8462D6DFB68}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infraestructure", "Infraestructure", "{E59FA921-6808-48FC-A97D-46187F256EC7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{D6311563-0AF4-4A92-9EBD-ED86D028EF6A}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{57865052-E859-4E07-B739-CFAC84B05515}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{DA87F0AE-9CB9-4453-8C43-5E7AD2B71A73}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{F0758F61-2134-49E5-A002-85A021B7B218}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EE0A9118-313B-48E4-8271-AABA50B7D7D0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mqtt.App.api", "src\Mqtt.App.api\Mqtt.App.api.csproj", "{C21AE3AC-D81E-4EEE-A341-1BF131D2EF9D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mqtt.App.Application", "src\Mqtt.App.Application\Mqtt.App.Application.csproj", "{CC2DBE75-C8B7-48AF-8C35-8C9CD8D34B30}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mqtt.App.Domain", "src\Mqtt.App.Domain\Mqtt.App.Domain.csproj", "{9ACA7C27-1ACF-42F9-9030-628888815CB7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mqtt.app.Persistencia", "src\Mqtt.app.Persistencia\Mqtt.app.Persistencia.csproj", "{F99418D0-C14F-4435-B693-FA4C860E9059}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mqtt.App.External", "src\Mqtt.App.External\Mqtt.App.External.csproj", "{00402824-39F8-4C3C-8C36-68D2464ABCA7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mqtt.App.Common", "src\Mqtt.App.Common\Mqtt.App.Common.csproj", "{7A814D68-5162-4842-9890-98DDD6C09FF4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C21AE3AC-D81E-4EEE-A341-1BF131D2EF9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C21AE3AC-D81E-4EEE-A341-1BF131D2EF9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C21AE3AC-D81E-4EEE-A341-1BF131D2EF9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C21AE3AC-D81E-4EEE-A341-1BF131D2EF9D}.Release|Any CPU.Build.0 = Release|Any CPU
{CC2DBE75-C8B7-48AF-8C35-8C9CD8D34B30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CC2DBE75-C8B7-48AF-8C35-8C9CD8D34B30}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CC2DBE75-C8B7-48AF-8C35-8C9CD8D34B30}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CC2DBE75-C8B7-48AF-8C35-8C9CD8D34B30}.Release|Any CPU.Build.0 = Release|Any CPU
{9ACA7C27-1ACF-42F9-9030-628888815CB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9ACA7C27-1ACF-42F9-9030-628888815CB7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9ACA7C27-1ACF-42F9-9030-628888815CB7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9ACA7C27-1ACF-42F9-9030-628888815CB7}.Release|Any CPU.Build.0 = Release|Any CPU
{F99418D0-C14F-4435-B693-FA4C860E9059}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F99418D0-C14F-4435-B693-FA4C860E9059}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F99418D0-C14F-4435-B693-FA4C860E9059}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F99418D0-C14F-4435-B693-FA4C860E9059}.Release|Any CPU.Build.0 = Release|Any CPU
{00402824-39F8-4C3C-8C36-68D2464ABCA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00402824-39F8-4C3C-8C36-68D2464ABCA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00402824-39F8-4C3C-8C36-68D2464ABCA7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00402824-39F8-4C3C-8C36-68D2464ABCA7}.Release|Any CPU.Build.0 = Release|Any CPU
{7A814D68-5162-4842-9890-98DDD6C09FF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7A814D68-5162-4842-9890-98DDD6C09FF4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7A814D68-5162-4842-9890-98DDD6C09FF4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7A814D68-5162-4842-9890-98DDD6C09FF4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{57865052-E859-4E07-B739-CFAC84B05515} = {88D481B0-BD9D-4732-9AE0-4707AE616E01}
{DA87F0AE-9CB9-4453-8C43-5E7AD2B71A73} = {D6311563-0AF4-4A92-9EBD-ED86D028EF6A}
{F0758F61-2134-49E5-A002-85A021B7B218} = {609A233D-1C2C-4041-A03B-F8462D6DFB68}
{EE0A9118-313B-48E4-8271-AABA50B7D7D0} = {E59FA921-6808-48FC-A97D-46187F256EC7}
{C21AE3AC-D81E-4EEE-A341-1BF131D2EF9D} = {57865052-E859-4E07-B739-CFAC84B05515}
{CC2DBE75-C8B7-48AF-8C35-8C9CD8D34B30} = {F0758F61-2134-49E5-A002-85A021B7B218}
{9ACA7C27-1ACF-42F9-9030-628888815CB7} = {F0758F61-2134-49E5-A002-85A021B7B218}
{F99418D0-C14F-4435-B693-FA4C860E9059} = {EE0A9118-313B-48E4-8271-AABA50B7D7D0}
{00402824-39F8-4C3C-8C36-68D2464ABCA7} = {EE0A9118-313B-48E4-8271-AABA50B7D7D0}
{7A814D68-5162-4842-9890-98DDD6C09FF4} = {DA87F0AE-9CB9-4453-8C43-5E7AD2B71A73}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3C4C824D-0B01-4A6C-BD15-95F92F81A8DC}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,61 @@
using AutoMapper;
using Empresa.App.Application.configuration;
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Application.Persistencia.user.commands.DeleteUser;
using Empresa.App.Application.Persistencia.user.commands.UpdateUser;
using Empresa.App.Application.Persistencia.user.Queries.GetAllUser;
using Empresa.App.Application.Persistencia.user.Queries.GetUserById;
using Empresa.App.Application.Persistencia.user.Queries.GetUserByPassAndName;
using Empresa.App.Application.Sesion.Commands.CreateSesion;
using Empresa.App.Application.Validators.Sesion;
using Empresa.App.Application.Validators.User;
using FluentValidation;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application
{
public static class DependencyInjectionService
{
public static IServiceCollection AddAplication(this IServiceCollection services)
{
var mapper = new MapperConfiguration(confg =>
{
confg.AddProfile(new MapperProfile());
}
);
#region user
services.AddTransient< IcreateUserCommand,CreateUserCommand>();
services.AddTransient<IupdateUserCommand, UpdateUserCommand>();
services.AddTransient<IDeleteUserCommand, DeleteUserCommand>();
services.AddTransient<IGetUserByIdQuery, GetUserByIdQuery>();
services.AddTransient<IGetAllUserQuery, GetAllUserQuery>();
services.AddTransient<IGetUserByPassAndNameQuery, GetUserByPassAndNameQuery>();
#endregion
#region userValidator
services.AddScoped<IValidator<CreateUserModel>,CreateUserValidator>();
services.AddScoped<IValidator<UpdateUserModel>, UpdateUserValidator>();
services.AddScoped<IValidator<(string, string)>, GetUserByPassAndNameValidator>();
services.AddScoped<IValidator<InCreateSesionModel>, InCreateSesionValidator>();
#endregion
#region Sesion
services.AddTransient<ICreateSesionCommand, CreateSesionCommand>();
#endregion
services.AddSingleton(mapper.CreateMapper());
return services;
}
}
}

View File

@ -0,0 +1,19 @@
using Empresa.App.Application.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Empresa.App.Application.Exceptions
{
//captura errores
public class ExceptionManager : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
context.Result = new ObjectResult(ResponseApiService.Response(
StatusCodes.Status500InternalServerError,context.Exception.Message
));
context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
}
}
}

View File

@ -0,0 +1,22 @@
using Empresa.App.Domain.Models;
namespace Empresa.App.Application.Features
{
public static class ResponseApiService
{
public static BaseResponseModel Response(int statusCode, object data=null, string msg=null)
{
bool success = false;
if(statusCode>=200 && statusCode<300)
success = true;
var result = new BaseResponseModel
{
StatusCode = statusCode,
Success = success,
Data = data,
Message = msg
};
return result;
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Interfaces.External
{
public interface IGetTokenJwtService
{
public string Execute(string id);
}
}

View File

@ -0,0 +1,24 @@
using Empresa.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Interfaces
{
//servicion para guardar datos
public interface IPersistenciaService
{
public Task<bool> AddUser(UserEntity user);
public Task<bool> UpdateUser(UserEntity user);
public Task<bool> DeleteUser(int idUser);
public Task<bool> UpdateNoNullUser(UserEntity user);
public Task<List<UserEntity>> GetAllUser();
public Task<UserEntity> GetUserById(int idUser);
public Task<UserEntity> GetUserByPassAndName(string pass, string name);
}
}

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="FluentValidation" Version="11.10.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Mqtt.App.Domain\Mqtt.App.Domain.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.Queries.GetAllUser
{
public class GetAllUserModel
{
public int Id { get; set; }
public string FristName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
}

View File

@ -0,0 +1,28 @@
using AutoMapper;
using Empresa.App.Application.Interfaces;
using Empresa.App.Application.Persistencia.user.commands.UpdateUser;
using Empresa.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.Queries.GetAllUser
{
public class GetAllUserQuery: IGetAllUserQuery
{
IPersistenciaService _persistenciaService;
IMapper _mapper;
public GetAllUserQuery(IPersistenciaService persistenciaService, IMapper mapper)
{
_persistenciaService = persistenciaService;
_mapper = mapper;
}
public async Task<List<GetAllUserModel>> Execute()
{
var l = await _persistenciaService.GetAllUser();
return _mapper.Map<List<GetAllUserModel>>(l);
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.Queries.GetAllUser
{
public interface IGetAllUserQuery
{
public Task<List<GetAllUserModel>> Execute();
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.Queries.GetUserById
{
public class GetUserByIdModel
{
public int Id { get; set; }
public string FristName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
}

View File

@ -0,0 +1,31 @@
using AutoMapper;
using Empresa.App.Application.Interfaces;
using Empresa.App.Application.Persistencia.user.commands.UpdateUser;
using Empresa.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.Queries.GetUserById
{
public class GetUserByIdQuery: IGetUserByIdQuery
{
IPersistenciaService _persistenciaService;
IMapper _mapper;
public GetUserByIdQuery(IPersistenciaService persistenciaService, IMapper mapper)
{
_persistenciaService = persistenciaService;
_mapper = mapper;
}
public async Task<GetUserByIdModel> Execute(int id)
{
//aqui se guarda realmente
var enty= await _persistenciaService.GetUserById(id);
return _mapper.Map<GetUserByIdModel>(enty);
}
}
}

View File

@ -0,0 +1,15 @@
using Empresa.App.Application.Persistencia.user.Queries.GetAllUser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.Queries.GetUserById
{
public interface IGetUserByIdQuery
{
public Task<GetUserByIdModel> Execute(int id);
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.Queries.GetUserByPassAndName
{
public class GetUserByPassAndNameModel
{
public int Id { get; set; }
public string FristName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using AutoMapper;
using Empresa.App.Application.Interfaces;
using Empresa.App.Application.Persistencia.user.Queries.GetUserById;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Empresa.App.Application.Persistencia.user.Queries.GetUserByPassAndName
{
public class GetUserByPassAndNameQuery: IGetUserByPassAndNameQuery
{
IPersistenciaService _persistenciaService;
IMapper _mapper;
public GetUserByPassAndNameQuery(IPersistenciaService persistenciaService, IMapper mapper)
{
_persistenciaService = persistenciaService;
_mapper = mapper;
}
public async Task<GetUserByPassAndNameModel> Execute(string pass, string name)
{
//aqui se guarda realmente
var enty = await _persistenciaService.GetUserByPassAndName(pass, name);
return _mapper.Map<GetUserByPassAndNameModel>(enty);
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.Queries.GetUserByPassAndName
{
public interface IGetUserByPassAndNameQuery
{
public Task<GetUserByPassAndNameModel> Execute(string pass, string name);
}
}

View File

@ -0,0 +1,30 @@
using AutoMapper;
using Empresa.App.Application.Interfaces;
using Empresa.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.commands.CreateUser
{
public class CreateUserCommand: IcreateUserCommand
{
private readonly IPersistenciaService _persistenciaService;
private IMapper _mapper;
public CreateUserCommand(IPersistenciaService persistenciaService, IMapper mapper)
{
_persistenciaService = persistenciaService;
_mapper = mapper;
}
public async Task<CreateUserModel>Execute(CreateUserModel model)
{
var entity = _mapper.Map<UserEntity>(model);
//aqui se guarda realmente
await _persistenciaService.AddUser(entity);
return model;
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.commands.CreateUser
{
public class CreateUserModel
{
public string FristName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.commands.CreateUser
{
public interface IcreateUserCommand
{
public Task<CreateUserModel> Execute(CreateUserModel model);
}
}

View File

@ -0,0 +1,26 @@
using AutoMapper;
using Empresa.App.Application.Interfaces;
using Empresa.App.Application.Persistencia.user.commands.UpdateUser;
using Empresa.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.commands.DeleteUser
{
public class DeleteUserCommand: IDeleteUserCommand
{
IPersistenciaService _persistenciaService;
public DeleteUserCommand(IPersistenciaService persistenciaService)
{
_persistenciaService = persistenciaService;
}
public async Task<bool> Execute(int id)
{
//aqui se guarda realmente
return await _persistenciaService.DeleteUser(id);
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.commands.DeleteUser
{
public interface IDeleteUserCommand
{
public Task<bool> Execute(int id);
}
}

View File

@ -0,0 +1,14 @@
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.commands.UpdateUser
{
public interface IupdateUserCommand
{
public Task<UpdateUserModel> Execute(UpdateUserModel UpdateUserModel);
}
}

View File

@ -0,0 +1,32 @@
using AutoMapper;
using Empresa.App.Application.Interfaces;
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.commands.UpdateUser
{
public class UpdateUserCommand : IupdateUserCommand
{
IPersistenciaService _persistenciaService;
IMapper _mapper;
public UpdateUserCommand(IPersistenciaService persistenciaService, IMapper mapper)
{
_persistenciaService = persistenciaService;
_mapper = mapper;
}
public async Task<UpdateUserModel> Execute(UpdateUserModel model)
{
var entity = _mapper.Map<UserEntity>(model);
//aqui se guarda realmente
await _persistenciaService.UpdateUser(entity);
return model;
}
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Persistencia.user.commands.UpdateUser
{
public class UpdateUserModel
{
public int Id { get; set; }
public string FristName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
}

View File

@ -0,0 +1,37 @@
using AutoMapper;
using Empresa.App.Application.Interfaces;
using Empresa.App.Application.Interfaces.External;
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Application.Persistencia.user.Queries.GetUserByPassAndName;
using Empresa.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Sesion.Commands.CreateSesion
{
public class CreateSesionCommand: ICreateSesionCommand
{
private readonly IGetTokenJwtService _jwtService;
private IGetUserByPassAndNameQuery _userService;
public CreateSesionCommand(IGetTokenJwtService jwtService, IGetUserByPassAndNameQuery userService)
{
_jwtService = jwtService;
_userService = userService;
}
public async Task<CreateSesionModel> Execute(InCreateSesionModel data)
{
var entity = await _userService.Execute(data.Password, data.UserName);
if (entity == null)
return null;
var res = new CreateSesionModel();
res.UserId = entity.Id;
res.Token = _jwtService.Execute(res.UserId.ToString());
return res;
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Sesion.Commands.CreateSesion
{
public class CreateSesionModel
{
public string Token { get; set; }
public int UserId { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Sesion.Commands.CreateSesion
{
public interface ICreateSesionCommand
{
public Task<CreateSesionModel> Execute(InCreateSesionModel data);
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Sesion.Commands.CreateSesion
{
public class InCreateSesionModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Application.Sesion.Commands.CreateSesion;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Validators.Sesion
{
public class InCreateSesionValidator : AbstractValidator<InCreateSesionModel>
{
public InCreateSesionValidator()
{
RuleFor(x => x.Password).NotNull().NotEmpty().MaximumLength(50);
RuleFor(x => x.UserName).NotNull().NotEmpty().MaximumLength(50);
}
}
}

View File

@ -0,0 +1,20 @@
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Validators.User
{
public class CreateUserValidator:AbstractValidator<CreateUserModel>
{
public CreateUserValidator() {
RuleFor(x=>x.FristName).NotNull().NotEmpty().MaximumLength(50);
RuleFor(x => x.LastName).NotNull().NotEmpty().MaximumLength(50);
RuleFor(x => x.UserName).NotNull().NotEmpty().MaximumLength(50);
RuleFor(x => x.Password).NotNull().NotEmpty().MaximumLength(10);
}
}
}

View File

@ -0,0 +1,19 @@
using Empresa.App.Application.Persistencia.user.commands.UpdateUser;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Validators.User
{
public class GetUserByPassAndNameValidator : AbstractValidator<(string, string)>
{
public GetUserByPassAndNameValidator()
{
RuleFor(x => x.Item1).NotNull().NotEmpty().MaximumLength(50);
RuleFor(x => x.Item2).NotNull().NotEmpty().MaximumLength(50);
}
}
}

View File

@ -0,0 +1,23 @@
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Application.Persistencia.user.commands.UpdateUser;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.Validators.User
{
public class UpdateUserValidator : AbstractValidator<UpdateUserModel>
{
public UpdateUserValidator()
{
RuleFor(x => x.Id).NotNull().GreaterThan(0);//que no sea nulo y mayor que 0
RuleFor(x => x.FristName).NotNull().NotEmpty().MaximumLength(50);
RuleFor(x => x.LastName).NotNull().NotEmpty().MaximumLength(50);
RuleFor(x => x.UserName).NotNull().NotEmpty().MaximumLength(50);
RuleFor(x => x.Password).NotNull().NotEmpty().MaximumLength(10);
}
}
}

View File

@ -0,0 +1,31 @@
using AutoMapper;
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Application.Persistencia.user.commands.UpdateUser;
using Empresa.App.Application.Persistencia.user.Queries.GetAllUser;
using Empresa.App.Application.Persistencia.user.Queries.GetUserById;
using Empresa.App.Application.Persistencia.user.Queries.GetUserByPassAndName;
using Empresa.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Application.configuration
{
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<UserEntity, CreateUserModel>().ReverseMap();
CreateMap<UserEntity, UpdateUserModel>().ReverseMap();
CreateMap<GetAllUserModel, UserEntity>().ReverseMap();
CreateMap<GetUserByIdModel, UserEntity>().ReverseMap();
CreateMap<GetUserByPassAndNameModel, UserEntity>().ReverseMap();
}
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Common
{
public static class DependencyInjectionService
{
public static IServiceCollection AddCommon(this IServiceCollection services)
{
return services;
}
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,24 @@
using Empresa.App.Domain.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Domain.Entities.Booking
{
public class BookingEntity
{
public int Id { get; set; }
public string Code { get; set; }
public BookingType Type { get; set; }
public int CustomerId { get; set; }
public int UserId { get; set; }
//booking-admin-01
//87698.ñaña
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Domain.Entities.Customer
{
public class CustomerEntity
{
public int Id { get; set; }
public string FullName { get; set; }
public string DocumentNumber { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Domain.Entities.User
{
public class UserEntity
{
public int Id { get; set; }
public string FristName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.Domain.Enums
{
public enum BookingType
{
Documentation,
Trasfer,
Renewal
}
}

View File

@ -0,0 +1,13 @@

namespace Empresa.App.Domain.Models
{
public class BaseResponseModel
{
public int StatusCode { get; set; }
public string Message { get; set; }
public bool Success { get; set; }
public dynamic Data { get; set; }
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

View File

@ -0,0 +1,39 @@
using Empresa.App.Application.Interfaces.External;
using Empresa.App.External.GetTokenJWT;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.External
{
public static class DependencyInjectionService
{
public static IServiceCollection AddExternal(this IServiceCollection services, IConfiguration config)
{
services.AddSingleton<IGetTokenJwtService, GetTokenJwtService>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
option.TokenValidationParameters=new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
IssuerSigningKey= new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["SecretKeyJwt"])),
ValidIssuer = config["IssuerJWT"],
ValidAudience = config["AudienceJwt"]
});
//services.AddAuthorization();
return services;
}
}
}

View File

@ -0,0 +1,46 @@
using Empresa.App.Application.Interfaces.External;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.App.External.GetTokenJWT
{
public class GetTokenJwtService: IGetTokenJwtService
{
private readonly IConfiguration _config;
public GetTokenJwtService(IConfiguration config)
{
_config= config;
}
public string Execute(string id)
{
var tokenHandler = new JwtSecurityTokenHandler();
string key = _config["SecretKeyJwt"]??"";
var singinkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject= new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, id)
}),
Expires= DateTime.UtcNow.AddDays(1),//expira en un dia
SigningCredentials=new SigningCredentials(singinkey,SecurityAlgorithms.HmacSha256Signature),
Issuer = _config["IssuerJWT"],
Audience = _config["AudienceJwt"]
};
var token= tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
}
}

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.1.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Mqtt.App.Application\Mqtt.App.Application.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>Mqtt.App.api</name>
</assembly>
<members>
</members>
</doc>

View File

@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "8.0.10",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}

View File

@ -0,0 +1,36 @@
using Empresa.App.Application.Features;
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Application.Sesion.Commands.CreateSesion;
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
//using System.Web.Http;
namespace Empresa.App.api.Controllers
{
[Authorize]
[Route("api/v1/Sesion")]
[ApiController]
public class SesionController : ControllerBase
{
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> Create(
[FromBody] InCreateSesionModel model,
[FromServices] ICreateSesionCommand createSesionCommand,
[FromServices] IValidator<InCreateSesionModel> validador
)
{
var validacion = await validador.ValidateAsync(model);
if (!validacion.IsValid)
return StatusCode(StatusCodes.Status400BadRequest, ResponseApiService.Response(StatusCodes.Status400BadRequest, validacion.Errors));
var data = await createSesionCommand.Execute(model);
//var n=int.Parse("h");
return StatusCode(StatusCodes.Status201Created, ResponseApiService.Response(StatusCodes.Status201Created, data));
}
}
}

View File

@ -0,0 +1,180 @@
using Empresa.App.Application.Exceptions;
using Empresa.App.Application.Features;
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Application.Persistencia.user.commands.DeleteUser;
using Empresa.App.Application.Persistencia.user.commands.UpdateUser;
using Empresa.App.Application.Persistencia.user.Queries.GetAllUser;
using Empresa.App.Application.Persistencia.user.Queries.GetUserById;
using Empresa.App.Application.Persistencia.user.Queries.GetUserByPassAndName;
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
//using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
//using System.Web.Http;
namespace Empresa.App.api.Controllers
{
[Authorize]
[Route("api/v1/User")]
[ApiController]
[TypeFilter(typeof(ExceptionManager))]//captura errores de todo el controller
public class UserController : ControllerBase
{
/*public UserController()
{
}*/
[AllowAnonymous]//no securizada
[HttpGet("test")]
public async Task<IActionResult> test()
{
//var n=int.Parse("h");
return StatusCode(StatusCodes.Status200OK, ResponseApiService.Response(StatusCodes.Status200OK, "{}", "Ejecucion exitosa"));
}
[HttpGet]
public async Task<IActionResult> GetAll(
[FromServices] IGetAllUserQuery service
)
{
var data = await service.Execute();
if(data==null|| data.Count<=0)
return StatusCode(StatusCodes.Status404NotFound, ResponseApiService.Response(StatusCodes.Status404NotFound, data));
return StatusCode(StatusCodes.Status200OK, ResponseApiService.Response(StatusCodes.Status200OK, data));
}
[HttpGet("{userId}")]
public async Task<IActionResult> Getuser(
int userId,
[FromServices] IGetUserByIdQuery service
)
{
if (userId <= 0)
{
return StatusCode(StatusCodes.Status400BadRequest, ResponseApiService.Response(StatusCodes.Status400BadRequest));
}
var data = await service.Execute(userId);
if (data == null)
return StatusCode(StatusCodes.Status404NotFound, ResponseApiService.Response(StatusCodes.Status404NotFound, data));
return StatusCode(StatusCodes.Status200OK, ResponseApiService.Response(StatusCodes.Status200OK, data));
}
[HttpGet("{userName}/{password}")]
public async Task<IActionResult> Getuser(
string userName,
string password,
[FromServices] IGetUserByPassAndNameQuery service,
[FromServices] IValidator<(string, string)> validador
)
{
var validacion = await validador.ValidateAsync(( userName, password));
if (!validacion.IsValid)
return StatusCode(StatusCodes.Status400BadRequest, ResponseApiService.Response(StatusCodes.Status400BadRequest, validacion.Errors));
/*
if (userName==null || userName.Length <= 0|| password == null || password.Length <= 0)
{
return StatusCode(StatusCodes.Status400BadRequest, ResponseApiService.Response(StatusCodes.Status400BadRequest));
}*/
var data = await service.Execute(password,userName);
if (data == null)
return StatusCode(StatusCodes.Status404NotFound, ResponseApiService.Response(StatusCodes.Status404NotFound, data));
return StatusCode(StatusCodes.Status200OK, ResponseApiService.Response(StatusCodes.Status200OK, data));
}
[HttpGet("login")]//se pasa parametros con ?userName=nombre&password=pass
public async Task<IActionResult> Getuser2(
[FromQuery] string userName,
[FromQuery] string password,
[FromServices] IGetUserByPassAndNameQuery service,
[FromServices] IValidator<(string, string)> validador
)
{
var validacion = await validador.ValidateAsync((userName, password));
if (!validacion.IsValid)
return StatusCode(StatusCodes.Status400BadRequest, ResponseApiService.Response(StatusCodes.Status400BadRequest, validacion.Errors));
var data = await service.Execute(password, userName);
if (data == null)
return StatusCode(StatusCodes.Status404NotFound, ResponseApiService.Response(StatusCodes.Status404NotFound, data));
return StatusCode(StatusCodes.Status200OK, ResponseApiService.Response(StatusCodes.Status200OK, data));
}
[HttpPost]
public async Task<IActionResult> Create(
[FromBody] CreateUserModel model,
[FromServices] IcreateUserCommand createUserCommand,
[FromServices] IValidator<CreateUserModel> validador
)
{
var validacion = await validador.ValidateAsync(model);
if(!validacion.IsValid)
return StatusCode(StatusCodes.Status400BadRequest, ResponseApiService.Response(StatusCodes.Status400BadRequest, validacion.Errors));
var data = await createUserCommand.Execute(model);
//var n=int.Parse("h");
return StatusCode(StatusCodes.Status201Created, ResponseApiService.Response(StatusCodes.Status201Created, data));
}
[HttpPut]
public async Task<IActionResult> Update(
[FromBody] UpdateUserModel model,
[FromServices] IupdateUserCommand updateUserCommand,
[FromServices] IValidator<UpdateUserModel> validador
)
{
var validacion = await validador.ValidateAsync(model);
if (!validacion.IsValid)
return StatusCode(StatusCodes.Status400BadRequest, ResponseApiService.Response(StatusCodes.Status400BadRequest, validacion.Errors));
var data = await updateUserCommand.Execute(model);
//var n=int.Parse("h");
return StatusCode(StatusCodes.Status200OK, ResponseApiService.Response(StatusCodes.Status200OK, data));
}
//falta hacerlo en servicio-------------------------
[HttpPatch]
public async Task<IActionResult> UpdateParcial(
[FromBody] UpdateUserModel model,
[FromServices] IupdateUserCommand updateUserCommand
)
{
var data = await updateUserCommand.Execute(model);
//var n=int.Parse("h");
return StatusCode(StatusCodes.Status200OK, ResponseApiService.Response(StatusCodes.Status200OK, data));
}
[HttpDelete("{userId}")]//parametro por url
public async Task<IActionResult> borrar(
int userId,
[FromServices] IDeleteUserCommand servicio
)
{
//validacion---------------------
if(userId<=0)
{
return StatusCode(StatusCodes.Status400BadRequest, ResponseApiService.Response(StatusCodes.Status400BadRequest));
}
var data = await servicio.Execute(userId);
if(!data)
return StatusCode(StatusCodes.Status404NotFound, ResponseApiService.Response(StatusCodes.Status404NotFound, data));
//var n=int.Parse("h");
return StatusCode(StatusCodes.Status200OK, ResponseApiService.Response(StatusCodes.Status200OK, data));
}
}
}

View File

@ -0,0 +1,51 @@
using Microsoft.OpenApi.Models;
using System.Reflection;
namespace Empresa.App.api
{
//clase de inyeccion de depèndencias
public static class DependencyInjectionService
{
public static IServiceCollection AddWebApi(this IServiceCollection services)
{
services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Empresa.App.api",
Description = "Plantilla generica para apis"
});
//parametros de seguridad-----------------------------------
option.AddSecurityDefinition("Beare", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description="Ingrese un tokenVálido",
Name="Authorization",
Type=SecuritySchemeType.Http,
BearerFormat="JWT",
Scheme="Bearer"
});
option.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference=new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{ }
}
});
//-----------------------------------------------------------
var fileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, fileName));
});
return services;
}
}
}

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<DocumentationFile>F:\desa\v2022\MqttApps\mqttApi\src\Mqtt.App.api.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.8.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.8.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Mqtt.App.Application\Mqtt.App.Application.csproj" />
<ProjectReference Include="..\Mqtt.App.Common\Mqtt.App.Common.csproj" />
<ProjectReference Include="..\Mqtt.App.Domain\Mqtt.App.Domain.csproj" />
<ProjectReference Include="..\Mqtt.App.External\Mqtt.App.External.csproj" />
<ProjectReference Include="..\Mqtt.app.Persistencia\Mqtt.app.Persistencia.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<NameOfLastUsedPublishProfile>F:\desa\v2022\PlantillaApiNet8\Empresa.app\src\Empresa.App.api\Properties\PublishProfiles\ParaDocker.pubxml</NameOfLastUsedPublishProfile>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,6 @@
@Empresa.App.api_HostAddress = http://localhost:5181
GET {{Empresa.App.api_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -0,0 +1,67 @@
using Empresa.App.api;
using Empresa.App.Application.Interfaces;
using Empresa.App.Common;
using Empresa.app.Persistencia;
using Empresa.App.External;
using Empresa.App.Application.Persistencia.user.commands.CreateUser;
using Empresa.App.Application;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
//añadir dependencias por inyeccion---------------------------
//añadri cadena de conexion esto te obliga a añadir dependencias a entity
//builder.Services.addDbContext
//inyeccion de dependencias te obliga a linckar persistencia y a externo¿?
//builder.Services.AddScoped<IPersistenciaService, PersistenciaService>();
builder.Services.AddControllers();
builder.Services.AddWebApi()
.AddCommon()
.AddAplication()
.AddExternal(builder.Configuration)
.AddPersistencia(builder.Configuration);
//
var app = builder.Build();
//poner swagger
app.UseSwagger();
app.UseSwaggerUI( options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.RoutePrefix = string.Empty;
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
//prueba de servicios-------------------------------------------
/*
app.MapGet("/test", async (IcreateUserCommand service) =>
{
var e = new CreateUserModel();
e.UserName = "test";
e.FristName = "FristName";
e.LastName = "LastName";
e.Password = "Password";
return await service.Execute(e);
});
*/
//--------------------------------------------------------------
// Configure the HTTP request pipeline.
app.Run();

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>false</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net8.0</TargetFramework>
<ProjectGuid>c21ae3ac-d81e-4eee-a341-1bf131d2ef9d</ProjectGuid>
<SelfContained>false</SelfContained>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<_PublishTargetUrl>F:\desa\v2022\PlantillaApiNet8\Empresa.app\src\Empresa.App.api\bin\Release\net8.0\publish\</_PublishTargetUrl>
<History>True|2024-10-13T22:20:08.1409506Z||;False|2024-10-12T00:55:43.7868486+02:00||;False|2024-10-12T00:54:55.4206586+02:00||;False|2024-10-12T00:53:16.4986422+02:00||;False|2024-10-12T00:48:55.1444606+02:00||;False|2024-10-12T00:41:42.3670744+02:00||;True|2024-10-12T00:38:00.0676000+02:00||;False|2024-10-12T00:37:27.3435243+02:00||;False|2024-10-12T00:36:59.2954575+02:00||;False|2024-10-11T23:05:11.9327090+02:00||;False|2024-10-11T22:57:40.4911279+02:00||;False|2024-10-11T22:49:51.2207122+02:00||;False|2024-10-11T22:46:38.3566597+02:00||;False|2024-10-11T22:44:26.6288883+02:00||;False|2024-10-11T22:42:50.5880241+02:00||;False|2024-10-11T22:14:27.4878309+02:00||;True|2024-10-11T21:59:36.3243372+02:00||;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>

View File

@ -0,0 +1,30 @@
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5181"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:18396",
"sslPort": 0
}
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,17 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"SqlConnectionString": "server=192.168.56.1,1433;user id=sa;password=pass1234.4321@#;initial catalog=AppPrueba; Trust Server Certificate=True",
"SecretKeyJwt": "NFAJJSAK3523dgsdf.dasfas.dsnfansnvDSFaskin908348",
"IssuerJWT": "EmpresaApp.com",
"AudienceJwt": "EmpresaApp.com",
"MasterKey": "bdasbvña78678,.p``´dshnihfp"
}

View File

@ -0,0 +1,26 @@
using Empresa.App.Domain.Entities.User;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.app.Persistencia.Configurations
{
public class UserConfiguration
{
public UserConfiguration( EntityTypeBuilder<UserEntity> entityBuilder) {
entityBuilder.ToTable("UserEntity");
entityBuilder.HasKey(x => x.Id);
entityBuilder.Property(x => x.UserName).IsRequired();
entityBuilder.Property(x => x.LastName).IsRequired();
entityBuilder.Property(x => x.FristName).IsRequired();
entityBuilder.Property(x => x.Password).IsRequired();
}
}
}

View File

@ -0,0 +1,39 @@
using Empresa.app.Persistencia.Services;
using Empresa.App.Application.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.SqlClient;
namespace Empresa.app.Persistencia
{
public static class DependencyInjectionService
{
public static IServiceCollection AddPersistencia(this IServiceCollection services, IConfiguration config)
{
services.AddDbContext<PersistenciaService>( options =>
options.UseSqlServer(config["SqlConnectionString"]));
services.AddScoped<IPersistenciaService, PersistenciaService>();
//para cifrado de bbdd
/*
* Falta investigar como hacer un probaider de certificados
* * /
SqlConnection.RegisterColumnEncryptionKeyStoreProviders(new Dictionary<string,
SqlColumnEncryptionCertificateStoreProvider>(1)//, StringComparer.OrdinalIgnoreCase)
{
{ SqlColumnEncryptionCertificateStoreProvider.ProviderName,provaider_certificados }
});
*/
return services;
}
}
}

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider" Version="5.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.8" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Mqtt.App.Application\Mqtt.App.Application.csproj" />
<ProjectReference Include="..\Mqtt.App.Domain\Mqtt.App.Domain.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,93 @@
using Empresa.app.Persistencia.Configurations;
using Empresa.App.Application.Interfaces;
using Empresa.App.Domain.Entities.User;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.app.Persistencia.Services
{
public class PersistenciaService : DbContext, IPersistenciaService
{
public PersistenciaService(DbContextOptions options): base(options)
{
}
public DbSet<UserEntity> User { get; set; }
public async Task<bool> AddUser(UserEntity user)
{
User.Add(user);
return await BoolAsync();
}
public async Task<bool> UpdateUser(UserEntity user)
{
User.Update(user);
return await BoolAsync();
}
public async Task<bool> DeleteUser(int idUser)
{
var enty= await User.FirstOrDefaultAsync(x => x.Id == idUser);
if (enty == null)
return false;
User.Remove(enty);
return await BoolAsync();
}
public async Task<bool> UpdateNoNullUser(UserEntity user)
{
var enty = await User.FirstOrDefaultAsync(x => x.Id == user.Id);
if (enty == null)
return false;
if(user.Password!=null)
enty.Password= user.Password;
if (user.LastName != null)
enty.LastName = user.LastName;
if (user.UserName != null)
enty.UserName = user.UserName;
if (user.FristName != null)
enty.FristName = user.FristName;
return await BoolAsync();
}
public async Task<List<UserEntity>> GetAllUser()
{
return await User.ToListAsync();
}
public async Task<UserEntity> GetUserById(int idUser)
{
var enty = await User.FirstOrDefaultAsync(x => x.Id == idUser);
return enty;
}
public async Task<UserEntity> GetUserByPassAndName(string pass, string name)
{
var enty = await User.FirstOrDefaultAsync(x => (x.Password == pass) && (x.UserName==name));
return enty;
}
private async Task<bool> BoolAsync()
{
return await SaveChangesAsync()>0;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
EntityConfigration(modelBuilder);
}
private void EntityConfigration(ModelBuilder model)
{
//configuras entidades relaccionadas con bbdd
new UserConfiguration(model.Entity<UserEntity>());
}
}
}

View File

@ -0,0 +1,15 @@
using mqttLog;
using log4net;
using log4net.Config;
using System.Reflection;
var builder = Host.CreateApplicationBuilder(args);
// Configurar log4net
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
builder.Services.AddHostedService<Worker>();
var host = builder.Build();
host.Run();

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>bin\Release\net8.0\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
<TargetFramework>net8.0</TargetFramework>
<SelfContained>false</SelfContained>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<History>True|2025-02-27T22:11:36.3713958Z||;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>

View File

@ -0,0 +1,12 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"mqttLog": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}

80
mqttLog/mqttLog/Worker.cs Normal file
View File

@ -0,0 +1,80 @@
namespace mqttLog
{
using log4net;
using Microsoft.Extensions.Logging;
//using log4net.Config;
using MQTTnet;
using System.Buffers;
using System.Text;
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private static readonly ILog log = LogManager.GetLogger("MQTTlOG");
IMqttClient mqttClient;
string server, idClient;
string topic;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
server = "192.168.2.50";
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
log.Info("INICIO-------------------------------------");
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
var mqttFactory = new MqttClientFactory();
using (var mqttClient = mqttFactory.CreateMqttClient())
{
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer(server).Build();
// Setup message handling before connecting so that queued messages
// are also handled properly. When there is no event handler attached all
// received messages get lost.
mqttClient.ApplicationMessageReceivedAsync += e =>
{
onReceived(e);
return Task.CompletedTask;
};
var conect= await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
if(conect.ResultCode== MqttClientConnectResultCode.Success)
{
var topicFilter = new MqttTopicFilterBuilder().WithTopic("casa/#").Build();
var subscribeOptions = new MqttClientSubscribeOptionsBuilder().WithTopicFilter(topicFilter).Build();
//var susb = await mqttClient.SubscribeAsync("casa");
var susb = await mqttClient.SubscribeAsync(subscribeOptions);
}
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
}
await mqttClient.DisconnectAsync();
}
log.Info("FINAL FELIZ-------------------------------------");
}
public void onReceived(MqttApplicationMessageReceivedEventArgs e)
{
StringBuilder sb = new StringBuilder();
SequenceReader<byte> reader = new SequenceReader<byte>(e.ApplicationMessage.Payload);
while (!reader.End)
{
sb.Append(Encoding.UTF8.GetString(reader.UnreadSpan));
reader.Advance(reader.UnreadSpan.Length);
}
string result = sb.ToString();
_logger.LogInformation(e.ApplicationMessage.Topic + " --> " + result);
log.Info(e.ApplicationMessage.Topic +" --> " + result);
}
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs/mqttLog_" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd'.log'" />
<staticLogFileName value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-mqttLog-65c1334a-2d38-4022-b4ac-5d8253990180</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="log4net" Version="3.0.3" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
<PackageReference Include="MQTTnet" Version="5.0.1.1416" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<_LastSelectedProfileId>F:\desa\v2022\mqttLog\mqttLog\Properties\PublishProfiles\FolderProfile.pubxml</_LastSelectedProfileId>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35521.163 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mqttLog", "mqttLog.csproj", "{F2CC350F-B94D-4F87-ACF9-525920FD5359}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F2CC350F-B94D-4F87-ACF9-525920FD5359}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F2CC350F-B94D-4F87-ACF9-525920FD5359}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F2CC350F-B94D-4F87-ACF9-525920FD5359}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F2CC350F-B94D-4F87-ACF9-525920FD5359}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal