Cascading DropDownList in .NET Core - sql

I am trying to use the tutorial linked below but adapting it to my SQL DB for States, Districts, Schools tables that I already have in place. I am new to .NET Core MVC and do not understand the error nor how to debug it. Any help appreciated.
Cascading DropDownList In .NET Core
Error:
Microsoft.Data.SqlClient.SqlException: 'Invalid object name 'State'.'
This exception was originally thrown at this call stack:
[External Code]
CascadingExample.Controllers.HomeController.Index() in HomeController.cs
[External Code]
using CascadingExample.Entities;
using CascadingExample.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace CascadingExample.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly MyDBContent _con;
public HomeController(ILogger<HomeController> logger, MyDBContent con)
{
_logger = logger;
_con = con;
}
public IActionResult Index()
{
ViewBag.StateList = _con.State.ToList();
return View();
}
public JsonResult GetDistrictByStateID(int statedID)
{
var data = _con.District.Where(x => x.StateID == statedID).ToList();
return Json(data);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

The error means the table named 'State' has not created or the Database you are referring has not created
I checked the dbcontext in your tutorial,and it will not create the table"State".
public class MyDBContent:DbContext
{
private IConfigurationRoot _config;
public MyDBContent(IConfigurationRoot config, DbContextOptions options) : base(options)
{
_config = config;
}
public DbSet<Category> Category { get; set; }
public DbSet<SubCategory> SubCategory { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);//connection string get by appsetting.json
}
}
You need to add these codes:
public DbSet<State> State { get; set; }

Related

How to implement Service inherit from generic repository?

I work on asp.net core mvc blazor application , I have issue I can't implement service inherit from generic repository .
meaning how to inherit from IRepository to get functions below on class server names service :
Insert
Update
GetById
GetList
GetListAsync
Interface generic repository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
public interface IRepository<TEntity> where TEntity : class
{
Task<int> Count(Expression<Func<TEntity, bool>> where);
TEntity GetByID(object id);
TEntity Insert(TEntity entity);
void Update(TEntity entityToUpdate);
Task<ICollection<TType>> Get<TType>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TType>> select) where TType : class;
Task<bool> Any(Expression<Func<TEntity, bool>> where);
TEntity GetFirst(Expression<Func<TEntity, bool>> where);
TEntity Single(Expression<Func<TEntity, bool>> where);
Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> where);
List<TEntity> GetList(Expression<Func<TEntity, bool>> where);
Task<bool> UpdateBasedOnCondition(Expression<Func<TEntity, bool>> where, Action<TEntity> select);
void Save();
}
class that implement interface as below :
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using UC.AppRepository.Core;
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
internal AppsRepositoryDBContext _context;
internal DbSet<TEntity> dbSet;
public BaseRepository(AppsRepositoryDBContext context)
{
_context = context;
this.dbSet = _context.Set<TEntity>();
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual TEntity Insert(TEntity entity)
{
var result = dbSet.AddAsync(entity).Result.Entity;
Save();
return result;
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
_context.Entry(entityToUpdate).State = EntityState.Modified;
}
public virtual async Task<bool> UpdateBasedOnCondition(Expression<Func<TEntity, bool>> where, Action<TEntity> select)
{
try
{
var ListOfRecord = await dbSet.Where(where).ToListAsync();
if (null != ListOfRecord && ListOfRecord.Count > 0)
{
ListOfRecord.ForEach(select);
// Save();
await _context.SaveChangesAsync();
return true;
}
return false;
}
catch (Exception ex)
{
return false;
throw;
}
}
public async Task<ICollection<TType>> Get<TType>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TType>> select) where TType : class
{
if(where == null)
{
return await dbSet.Select(select).ToListAsync();
}
return await dbSet.Where(where).Select(select).ToListAsync();
}
public async Task<int> Count(Expression<Func<TEntity, bool>> where)
{
return await dbSet.Where(where).CountAsync();
}
public async virtual Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> where)
{
// var test = dbSet.Where(where).ToList();
return await dbSet.Where(where).ToListAsync();
}
public virtual List<TEntity> GetList(Expression<Func<TEntity, bool>> where)
{
return dbSet.Where(where).ToList();
}
public async Task<bool> Any(Expression<Func<TEntity, bool>> where)
{
return await dbSet.AnyAsync(where);
}
public TEntity GetFirst(Expression<Func<TEntity, bool>> where)
{
return dbSet.FirstOrDefault(where);
}
public TEntity Single(Expression<Func<TEntity, bool>> where)
{
return dbSet.Single(where);
}
public void Save()
{
try
{
_context.SaveChanges();
}
catch (Exception ex)
{
throw;
}
}
}
so I have class ServerNameService and class interface IserverNamesService
I need to implement insert,update,selectById,selectall functions for server name models
from base repository
public class ServerNameService:IRepository
{
// what i write here
}
public interface IserverNamesService:IRepository
{
// what i write here
}
public class ServerNames
{
[Key]
public int ServerID { get; set; }
public string Server_Name{ get; set; }
public string Server_Type { get; set; }
public string Operating_System { get; set; }
public string Version { get; set; }
public bool IsActive { get; set; }
}
I have issue I can't implement service inherit from generic repository.I have class ServerNameService and class interface IserverNamesService I need to implement insert,update,selectById,selectall functions for server name models from base repository
Well, to directly answer your question, to implement your ServerNameService which derived from IRepository that would would be as following:
IserverNamesService:
public interface IserverNamesService : IRepository<ServerNames>
{
}
Note: Keep it empty because we will use of IRepository and BaseRepository in ServerNamesService class to implement its members.
ServerNamesService:
public class ServerNamesService : BaseRepository<ServerNames>, IserverNamesService
{
public ServerNamesService(ApplicationDbContext context) : base(context)
{
}
public override ServerNames GetByID(object id)
{
return _context.ServerNames.Where(sn => sn.ServerID == (int)id).FirstOrDefault();
}
}
Controller:
[Route("api/[controller]")]
[ApiController]
public class ServerNamesServiceController : ControllerBase
{
private readonly IserverNamesService _serverNamesService;
public ServerNamesServiceController(IserverNamesService namesService)
{
_serverNamesService = namesService;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(object id)
{
var item = _serverNamesService.GetByID(id);
if (item == null)
return NotFound();
return Ok(item);
}
}
Program.cs:
builder.Services.AddScoped<IserverNamesService, ServerNamesService>();
Note: Register your ServerNamesService class in your program.cs
UnitOfWork Pattern Implementation:
As long your application would continue evolving and there would be ton of service class, in that scenario, you have to introduce lot of service in your controller. But if you would like to handle those smoothly, you could use UnitOfWork pattern which would contain all of your service together.
Interface:
public interface IUnitOfWork
{
IserverNamesService ServerNamesService { get; }
Task CompleteAsync();
}
Implementation:
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly ApplicationDbContext _context;
public IserverNamesService ServerNamesService { get; private set; }
public UnitOfWork(ApplicationDbContext context)
{
_context = context;
ServerNamesService = new ServerNamesService(context);
}
public async Task CompleteAsync()
{
await _context.SaveChangesAsync();
}
public void Dispose()
{
_context.Dispose();
}
}
Controller:
[Route("api/[controller]")]
[ApiController]
public class ServerNamesServiceController : ControllerBase
{
private readonly IUnitOfWork _unitOfWork;
public ServerNamesServiceController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(object id)
{
var item = _unitOfWork.ServerNamesService.GetByID(id);
if (item == null)
return NotFound();
return Ok(item);
}
}
Output:
Note: If you would like to know more details on repository pattern you could check our official document here and working sample here.
You should pass your Entity as generic type to IRepository in IServerNamesService, and then inheritance ServerNameService from IServerNamesService.
public interface IServerNamesService:IRepository<ServerNames>
{
// your methods interface
}
public class ServerNameService:IServerNamesService{
private readonly IRepository<ServerNames> _repository;
public class ServerNameService(IRepository<ServerNames> repository)
{
_repository = repository;
}
//body of your methods
}

MassTransit skip messages

i am building a project with microservices and i am using MassTransit, i have 2 separate project which one is the publisher and the other the consumer , but i can't consume the message , whatever i try always the messages go to skip queue.
Namespaces are the same about the message, i already also try to make a nuget package and use it but same issue.
PLEASE HELP ME
using MassTransit;
namespace RabbitMq.Models;
[EntityName("Reservation_reminder")]
public class ReservationMessage
{
public Guid? ReservationId { get; set; }
public int UserId { get; set; }
public DateTime From { get; set; }
public DateTime To { get; set; }
public int ShopId { get; set; }
public int CategoryId { get; set; }
public decimal Price { get; set; }
}
var rabbitMQSettings = _configuration.GetSection("RabbitMQ").Get<RabbitMQSettings>();
_services.AddMassTransit(x =>
{
//x.AddConsumer<ReservationsReminderConsumer>();
x.UsingRabbitMq((ctx, cfg) =>
{
cfg.Host(rabbitMQSettings.HostAddress);
cfg.ReceiveEndpoint(RabbitMQConstant.RabbitMQ_Reservation_Reminder_Queue,c=>
{
//c.ConfigureConsumer<ReservationsReminderConsumer>(ctx);
c.Bind("Reservation_reminder", x =>
{
x.Durable = true;
x.ExchangeType = "topic";
});
});
});
x.AddConsumers(typeof(ReservationsReminderConsumer).Assembly);
});
using MassTransit;
using Microsoft.Extensions.Logging;
using RabbitMq.Models;
namespace ReservationReminder.Infrastracture.RabbitMQ.Consumers
{
public class ReservationsReminderConsumer : IConsumer
{
private readonly ILogger _logger;
public ReservationsReminderConsumer(ILogger<ReservationsReminderConsumer> logger)
{
_logger = logger;
}
public async Task Consume(ConsumeContext<ReservationMessage> context)
{
_logger.LogInformation($"Message Received {context.Message}");
}
}
}
using AutoMapper;
using MassTransit;
using Microsoft.Extensions.Logging;
using RabbitMq.Models;
using ScheduleReservation.Domain.Models;
using System.ComponentModel;
namespace ScheduleReservation.Infrastracture.NotificationPublisher
{
public class NotificationPublisher
{
private readonly IPublishEndpoint _publishEndpoint;
private readonly IMapper _mapper;
private readonly ILogger _logger;
public NotificationPublisher(IPublishEndpoint publishEndpoint, IMapper mapper, ILogger<NotificationPublisher> logger)
{
_publishEndpoint = publishEndpoint;
_mapper = mapper;
_logger = logger;
}
[DisplayName("Send notification to UserId: {1} & ReservationId: {2}")]
public void Publish(ReservationModel reservationModel, int userId, Guid? reservationId)
{
try
{
var message = _mapper.Map<ReservationMessage>(reservationModel);
var messagee = new ReservationMessage()
{
CategoryId = reservationModel.CategoryId,
From = reservationModel.From,
To = reservationModel.To,
Price = reservationModel.Price,
ReservationId = reservationId,
ShopId = reservationModel.ShopId,
UserId = userId,
};
_publishEndpoint.Publish(messagee);
_logger.LogInformation($"The reservation {reservationModel.ReservationId} published to RabbitMQ broker");
}
catch (Exception ex)
{
_logger.LogInformation($"The reservation {reservationModel.ReservationId} wasn't publish to RabbitMQ broker, because an error occured with message: {ex.Message}");
}
}
}

How to download file from wwwroot folder in dot core api using Mediatr pattern?

I am trying to download wwwroot file where file is saved i want to download file by filename only which i am sending from my angular code.
in controller my code is like this
[HttpPost("DownloadMPWorthyFile")]
public async Task<ActionResult<bool>> DownloadMPWorthyFile(DownloadMPWorthyFileCommand command)
{
return await Mediator.Send(command);
}
in DownloadMPWorthyFileCommand command i have added
using AutoMapper;
using Kaizen.Common.Interfaces;
using Kaizen.Common.Logger;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Kaizen.Domain.Entities;
using Kaizen.Application.Common.Services.EmailService;
using EmailActions = Kaizen.Domain.Enums.EmailActions.Actions;
using Kaizen.Common.Models;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Hosting;
namespace Kaizen.Application.Kaizen.Command
{
public class DownloadMPWorthyFileCommand : IRequest<bool>
{
public string FileName { get; set; }
public string PageName { get; set; }
public string IdeaNumber { get; set; }
}
public class GetKaizenDownloadfileResponse
{
public int StatusCode { get; set; }
public string Message { get; set; }
public string ErrorMessage { get; set; }
public List<getdata> Data { get; set; }
}
public class getdata
{
public string FileName { get; set; }
public string Method { get; set; }
public string PageName { get; set; }
}
public class DownloadMPWorthyFileCommandHandle : IRequestHandler<DownloadMPWorthyFileCommand, bool>
{
private readonly IKaizenDBContext _context;
private readonly IMapper _mapper;
private readonly ILogger<kaizenUploadFile> _logger;
private readonly IEmailService _emailService;
private IHostingEnvironment Environment;
public DownloadMPWorthyFileCommandHandle(IKaizenDBContext context, IMapper mapper, ILogger<SendMailForMPWorthyCommandHandler> logger, IEmailService emailService, IOptions<AppSettings> appSettings, IHostingEnvironment _environment)
{
_context = context;
_mapper = mapper;
//_logger = logger;
_emailService = emailService;
Environment = _environment;
// _appSettings = appSettings.Value;
}
public async Task<bool> Handle(DownloadMPWorthyFileCommand request, CancellationToken cancellationToken)
{
bool retval = false;
var MPWorthyFile = _context.DocumentUploaded.Where(e => e.IdeaNumber == request.IdeaNumber && e.PageName==request.PageName);
if (MPWorthyFile != null)
{
string wwwPath1 = this.Environment.WebRootPath;
string imgnm1 = "/document/" + request.FileName;
string filePath1 = wwwPath1 + imgnm1;
string imageName1 = filePath1;
var net1 = new System.Net.WebClient();
var path1 = wwwPath1 + filePath1;
var data1 = net1.DownloadData(filePath1);
var content1 = new System.IO.MemoryStream(data1);
retval= true;
}
else
{
retval = false;
}
return retval;
}
}
}
i have done code in this way but its not working in return type i keep getting error,is anyone know correct way to download the file from wwwroot?
You should check the IHostingEvironment, there is an WebRootFileProvider with which you check for file and open stream on those.
var file = _environment.WebRootFileProvider.GetFileInfo("...");
if (file.Exists)
{
var stream = file.CreateReadStream();
// Go on from here...
}

I cannot retrieve connection string in DbContext class in .NET Core 2.2 Razor Pages

In Startup.cs Configure Services this works:
var connection = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<MyDbContext>(
options => { options.UseSqlServer(connection); });
In my MyDbContext.cs class this doesn't work:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using OESAC.Models;
namespace OESAC.Models
{
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{ }
public DbSet<Courses> Courses { get; set; }
public DbSet<Sponsors> Sponsors{ get; set; }
public IConfiguration Configuration { get; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connection = Configuration["ConnectionStrings:DefaultConnection"];
optionsBuilder.UseSqlServer(connection);
;
}
}
}
I can hardcode the connection string but I want it to dynamically change based on my appSettings.Development.json and appSettngs.json (production). I can't believe the time I've spent trying to figure this out. It has cost me way over what I am being paid.
You need to inject IConfiguration in constructor to have an access to configuration.
public class MyDbContext : DbContext
{
private readonly IConfiguration _configuration;
public MyDbContext(IConfiguration configuration)
{
_configuration = configuration
}
public DbSet<Courses> Courses { get; set; }
public DbSet<Sponsors> Sponsors{ get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connection = _configuration["ConnectionStrings:DefaultConnection"];
optionsBuilder.UseSqlServer(connection);
}
}
Startup.cs:
services.AddDbContext<ApplicationDbContext>();

IUrlHelper not being resolved in RC2

While migrating from ASP.NET Core RC1 to RC2 my TagHelpers do not resolve the injected IUrlHelpers.
[HtmlTargetElement("usermenulink", Attributes = "controller-name, action-name, menu-text, menu-item, active-item")]
public class UserMenuItemTagHelper : TagHelper
{
public IUrlHelper _UrlHelper { get; set; }
public UserMenuItemTagHelper(IUrlHelper urlHelper)
{
_UrlHelper = urlHelper;
}
//... abbreviated
}
Instead I get an exception:
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' while attempting to activate '...TagHelpers.UserMenuItemTagHelper'.
Any ideas?
I found out myself that with RC2 you have to (or can) inject an IUrlHelperFactory and get an UrlHelper instance of this.
public class UserMenuLinkTagHelper : TagHelper
{
[ViewContext]
public ViewContext ViewContext { get; set; }
public IUrlHelperFactory _urlHelperFactory { get; set; }
public UserMenuLinkTagHelper(IUrlHelperFactory urlHelperFactory)
{
_urlHelperFactory = urlHelperFactory;
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext);
string menuUrl = urlHelper.Action(ActionName, ControllerName);
//...
}
}
Here is the example of the current implementation of the Mvc team:
https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.TagHelpers/ImageTagHelper.cs