I am a beginner developer and I have an issue in Query handler when using throw new RestException(HttpStatusCode.Unauthorized)
this is my query handler:
namespace Application.User
{
public class Login
{
public class Query : IRequest<AppUser>
{
public string Email { get; set; }
public string Password { get; set; }
}
public class QueryValidator : AbstractValidator<Query>
{
public QueryValidator()
{
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
}
}
public class Handler : IRequestHandler<Query, AppUser>
{
private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signUserManager;
public Handler(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
{
_userManager = userManager;
_signUserManager = signInManager;
}
public async Task<AppUser> Handle(Query request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null)
throw new RestException(HttpStatusCode.Unauthorized);
var result = await _signUserManager.CheckPasswordSignInAsync(user, request.Password, false);
if (result.Succeeded)
{
//TODO : generate token
return user;
}
throw new RestException(HttpStatusCode.Unauthorized);
}
}
}
}
Related
I am using asp.net core 6 web api ,entity framework code first and CQRS - Mediatr for a project which has functinalities to update database and get data from database and show it in the swaggerui but I came across with a problem when I try to create a handler for the update data by its ID in the database I get this error :
Error CS0311 The type 'EnocaChallengeV2.Commands.UpdateFirmDateCommand' cannot be used as type parameter 'TRequest' in the generic type or method 'IRequestHandler<TRequest, TResponse>'. There is no implicit reference conversion from 'EnocaChallengeV2.Commands.UpdateFirmDateCommand' to 'MediatR.IRequest<int>'.
This is my Command:
using EnocaChallengeV2.Models;
using MediatR;
namespace EnocaChallengeV2.Commands
{
public class UpdateFirmDateCommand : IRequest<Firm> {
public int Id { get; set; }
public DateTime startTime { get; set; }
public DateTime endTime { get; set; }
public UpdateFirmDateCommand(int id, DateTime StartTime, DateTime EndTime)
{
Id = id;
startTime = StartTime;
endTime = EndTime;
}
}
}
This is the Handler:
using EnocaChallengeV2.Commands;
using EnocaChallengeV2.Models;
using EnocaChallengeV2.Queries;
using EnocaChallengeV2.Repositories;
using MediatR;
namespace EnocaChallengeV2.Handlers
{
public class UpdateFirmDateHandler : IRequestHandler<UpdateFirmDateCommand, int>
{
private readonly IFirmRepository _firmRepository;
public UpdateFirmDateHandler(IFirmRepository firmRepository)
{
_firmRepository = firmRepository;
}
public async Task<int> Handle(UpdateFirmDateCommand command, CancellationToken cancellationToken)
{
var firm = await _firmRepository.GetFirmByIdAsync(command.Id);
if (firm == null)
return default;
firm.startTime = command.startTime;
firm.endTime = command.endTime;
return await _firmRepository.UpdateFirmDateAsync(firm);
}
}
}
This is the interface:
using EnocaChallengeV2.Models;
namespace EnocaChallengeV2.Repositories
{
public interface IFirmRepository
{
public Task<List<Firm>> GetFirmListAsync();
public Task<Firm> GetFirmByIdAsync(int Id);
public Task<Firm> AddFirmAsync(Firm firm);
public Task<int> UpdateFirmDateAsync(Firm firm);
public Task<int> UpdateFirmVerificationAsync(Firm firm);
}
}
This is the repository:
using EnocaChallengeV2.Data;
using EnocaChallengeV2.Models;
using Microsoft.EntityFrameworkCore;
namespace EnocaChallengeV2.Repositories
{
public class FirmRepository : IFirmRepository
{
private readonly DbContextClass _dbContext;
public FirmRepository(DbContextClass dbContext)
{
_dbContext = dbContext;
}
public async Task<Firm> AddFirmAsync(Firm firm)
{
var result = _dbContext.Firms.Add(firm);
await _dbContext.SaveChangesAsync();
return result.Entity;
}
public async Task<int> DeleteFirmAsync(int Id)
{
var filteredData = _dbContext.Firms.Where(x => x.Id == Id).FirstOrDefault();
_dbContext.Firms.Remove(filteredData);
return await _dbContext.SaveChangesAsync();
}
public async Task<Firm> GetFirmByIdAsync(int Id)
{
return await _dbContext.Firms.Where(x => x.Id == Id).FirstOrDefaultAsync();
}
public async Task<List<Firm>> GetFirmListAsync()
{
return await _dbContext.Firms.ToListAsync();
}
public async Task<int> UpdateFirmDateByIdAsync(Firm firm)
{
_dbContext.Firms.Update(firm);
return await _dbContext.SaveChangesAsync();
}
//public async Task<Firm> UpdateFirmVerificationAsync(Firm firm)
//{
// _dbContext.Firms.Update(firm);
// return await _dbContext.SaveChangesAsync();
//}
}
}
I tried to change the Task<> to Firm and then to int but didn't seem to work.
You command needs to define a return type of 'int':
namespace EnocaChallengeV2.Commands
{
public class UpdateFirmDateCommand : IRequest<int> {
public int Id { get; set; }
public DateTime startTime { get; set; }
public DateTime endTime { get; set; }
public UpdateFirmDateCommand(int id, DateTime StartTime, DateTime EndTime)
{
Id = id;
startTime = StartTime;
endTime = EndTime;
}
}
}
Note the change:
IRequest<int>
I created a webapi by looking at the ms basic documentation.
ms Doc
it was work
todoitems
Besides todoitems I
Because I wanted to use it in the form of Avatar Chart
Insert the model Avatarchart, create Avatarchartcontext, and make the controller as a scaffold.
solution view
However, when I tried to receive data as a post, the data always came in null.
error
null
this is code
[Route("api/AvatarCharts")]
[ApiController]
public class AvatarChartsController : ControllerBase
{
private readonly AvatarChartContext _context;
public AvatarChartsController(AvatarChartContext context)
{
_context = context;
}
// GET: api/AvatarCharts
[HttpGet]
public async Task<ActionResult<IEnumerable<AvatarChart>>> GetAvatarCharts()
{
return await _context.AvatarCharts.ToListAsync();
}
// GET: api/AvatarCharts/5
[HttpGet("{modelId}")]
public async Task<ActionResult<AvatarChart>> GetAvatarChart(long modelId)
{
var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
if (avatarChart == null)
{
return NotFound();
}
return avatarChart;
}
// PUT: api/AvatarCharts/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{modelId}")]
public async Task<IActionResult> PutAvatarChart(long modelId, AvatarChart avatarChart)
{
if (modelId != avatarChart.modelId)
{
return BadRequest();
}
_context.Entry(avatarChart).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AvatarChartExists(modelId))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/AvatarCharts
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<AvatarChart>> PostAvatarChart( AvatarChart avatarChart)
{
_context.AvatarCharts.Add(avatarChart);
await _context.SaveChangesAsync();
return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
}
// DELETE: api/AvatarCharts/5
[HttpDelete("{modelId}")]
public async Task<IActionResult> DeleteAvatarChart(long modelId)
{
var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
if (avatarChart == null)
{
return NotFound();
}
_context.AvatarCharts.Remove(avatarChart);
await _context.SaveChangesAsync();
return NoContent();
}
private bool AvatarChartExists(long modelId)
{
return _context.AvatarCharts.Any(e => e.modelId == modelId);
}
}
public class AvatarChartContext :DbContext
{
public AvatarChartContext(DbContextOptions<AvatarChartContext> options) : base(options)
{
}
public DbSet<AvatarChart> AvatarCharts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AvatarChart>().HasKey(c => c.modelId);
}
}
public class AvatarChart
{
[Key]
public long modelId;
public string colorCode;
public long dateTime; //ex 20210101130000
public string name;
public string diagnose;
}
swagger
add postgressql dbenter image description here
Update:
You missed the {get; set;}.
public class AvatarChart
{
[Key]
public long modelId {get; set;}
public string colorCode {get; set;}
public long dateTime {get; set;} //ex 20210101130000
public string name {get; set;}
public string diagnose {get; set;}
}
Can you make these changes and tell me what value is being returned on the variable result. Also, can you validate your ModelState first?
[HttpPost]
public async Task<ActionResult> PostAvatarChart( AvatarChart avatarChart)
{
await _context.AvatarCharts.AddAsync(avatarChart);
var result = await _context.SaveChangesAsync() > 0;
return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
}
Trying to do simple chat and sending user to the userTracker when he/she is connected
public override async Task OnConnectedAsync()
{
var user = Helper.GetUserInformationFromContext(Context);
await this.userTracker.AddUserAsync(Context.Connection, user);
await Clients.All.SendAsync("UsersJoined", new UserInformation[] { user });
await Clients.All.SendAsync("SetUsersOnline", await GetOnlineUsersAsync());
await base.OnConnectedAsync();
}
but in the old versions HubCallerContext is like this :
public HubCallerContext(HubConnectionContext connection);
public HubConnectionContext Connection { get; }
public ClaimsPrincipal User { get; }
public string ConnectionId { get; }
the version I am using ( 2.3.0 ) is like
protected HubCallerContext();
public abstract string ConnectionId { get; }
public abstract string UserIdentifier { get; }
public abstract ClaimsPrincipal User { get; }
public abstract IFeatureCollection Features { get; }
public abstract CancellationToken ConnectionAborted { get; }
public abstract void Abort();
So how can I get the missing Connection ?
You simple have to inject it where you use it
Sample:
public class YourClassWhereYouNeedHubContext
{
// Inject into constructor
public YourClassWhereYouNeedHubContext (IHubContext<VarDesignHub> hubcontext)
{
HubContext = hubcontext;
...
}
private IHubContext<VarDesignHub> HubContext
{
get;
set;
}
}
Then you can also call
await this.HubContext.Clients.All.InvokeAsync("Completed", id);
Please read also:
Call SignalR Core Hub method from Controller
I've used ASP.NET Identity 2 for creating a registration user logic, and I have an exception at HttpContext.GetOwinContext().GetUserManager().
What could be a problem? Thank you for any advise.
There is registration controller
public class AccountController : Controller
{
private ApplicationUserManager UserManager
{
get
{
return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Register(RegisterUserModel model)
{
if (ModelState.IsValid)
{
AppUser user = new AppUser { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
return RedirectToAction("Login", "Account");
}
else
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
return View(model);
}
}
ApplicationUserManager logic
public class ApplicationUserManager : UserManager<AppUser>
{
public ApplicationUserManager(IUserStore<AppUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
IdentificationContext db = context.Get<IdentificationContext>();
ApplicationUserManager manager = new ApplicationUserManager(new UserStore<AppUser>(db));
return manager;
}
}
Registration model
public class RegisterUserModel
{
[Required]
[StringLength(255)]
[RegularExpression(#"[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(255, MinimumLength = 5)]
public string Password { get; set; }
[Required]
[System.ComponentModel.DataAnnotations.Compare("Password")]
[DataType(DataType.Password)]
public string PasswordConfirm { get; set; }
}
Model that inherit from IdentitiyUSer model
public class AppUser : IdentityUser
{
public AppUser() { }
}
Startup class
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<IdentificationContext>(IdentificationContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
});
}
There is an output of exception
enter image description here
You need to add setting (owin:AutomaticAppStartup) in web.config
<add key="owin:AutomaticAppStartup" value="true"/>
If it still doesn't work, add below setting specifying your startup class. This is because the default convention for the Startup class is [AssemblyName].Startup. If you're no longer following that convention you'll need to specify the full name of your Startup class in the Web.Config.
<add key="owin:AppStartup" value="[Namespace].Startup, [AssemblyName]" />
Hope it helps.
I am new in Fluent NHibernet and i am using Fluent NHibernet in my asp.net application
this is my Poco class
public virtual int CategoryId { get; set; }
public virtual string CategoryName { get; set; }
public virtual bool IsActive { get; set; }
public virtual bool IsDeleted { get; set; }
My Mapping Class
public class clsCategoryMap : ClassMap<clsCategory>
{
public clsCategoryMap()
{
Id(x => x.CategoryId).Column("CategoryId").GeneratedBy.Assigned().Not.Nullable();
Map(x => x.CategoryName).Column("CategoryName").Not.Nullable();
Map(x => x.IsActive).Column("IsActive").Not.Nullable();
Map(x => x.IsDeleted).Column("IsDeleted").Not.Nullable();
Table("tblCategory");
}
}
Poco class and Mapping class both saprated in class Liberar like: DAL for Poco class and BLL For Mapping class.
And i create helper class it's below:
public class FNHelper
{
private static ISessionFactory _sessionfactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionfactory == null) { InitializationSessionFactory(); }
return _sessionfactory;
}
}
private static void InitializationSessionFactory()
{
_sessionfactory = Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2008
.ConnectionString(#"Server=test\SQLEXPRESS;Database=TestDB;User ID=sa;Password=root;")
.DefaultSchema("dbo")
.ShowSql()
)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<clsCategory>())
.ExposeConfiguration((cfg => new SchemaUpdate(cfg).Execute(true, true)))
.BuildSessionFactory();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
private static void BuildSchema(NHibernate.Cfg.Configuration configuration)
{
String SqliteRefFileName = #"D:\Projects\MeshpsDB.sql";
if (File.Exists(SqliteRefFileName))
File.Delete(SqliteRefFileName);
new SchemaExport(configuration)
.Create(true, true);
}
}
And finally i am doing in my form it's below:
protected void btnSave_Click(object sender, EventArgs e)
{
using (var session = FNHelper.OpenSession())
{
using (var tranction = session.Transaction)
{
var objCategory = new clsCategory
{
CategoryId = 0,
CategoryName = txtName.Text.Trim(),
IsActive = true,
IsDeleted = false
};
session.Save(objCategory);
tranction.Commit();
}
}
}
when i click on button then i am getting
so every one please tell me how can i solve this issue.
change m.FluentMappings.AddFromAssemblyOf<clsCategory>() to m.FluentMappings.AddFromAssemblyOf<clsCategoryMap>() because its the mappingss you want to add and these reside in another assembly.