Dynamic connection to Database ASP.NET - asp.net-core

I want write autorization system in asp.net - user of Postgres (which created throws CREATE ROLE...) entering login and password and working with own tables. Problem is i working in ASP.NET core and connecting throws Dapper.
appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"DBInfo": {
"Name": "coresample",
"ConnectionString": "User ID=username;Password=userpassword;Host=localhost;Port=5432;Database=Documents;Pooling=true;"
}
}
DocumentsRepository
public class DocumentsRepository : IRepository<Documents>
{
private string connectionString;
public DocumentsRepository(IConfiguration configuration, string login, string password)
{
connectionString = configuration.GetValue<string>("DBInfo:ConnectionString");
connectionString = connectionString.Replace("username", login);
connectionString = connectionString.Replace("userpassword", password);
}
internal IDbConnection Connection
{
get
{
return new NpgsqlConnection(connectionString);
}
}
public void Add(Documents item)
{
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open();
dbConnection.Execute("SELECT addrecuserdocuments(#DocumentName,#Contents,#DocumentIntroNumber)", item);
}
}
public IEnumerable<Documents> FindAll()
{
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open();
return dbConnection.Query<Documents>("SELECT * FROM selectdata()");
}
}
DocumentController
public class DocumentsController : Controller
{
private readonly DocumentsRepository dRepository;
public DocumentsController(IConfiguration configuration)
{
dRepository = new DocumentsRepository(configuration);
}
public IActionResult Index()
{
return View(dRepository.FindAll());
}
public IActionResult Create()
{
return View();
}
// POST: Documents/Create
[HttpPost]
public IActionResult Create(DocumentViewModel dvm)
{
Documents docs = new Documents { DocumentName = dvm.DocumentName, DocumentIntroNumber = dvm.DocumentIntroNumber };
if (ModelState.IsValid)
{
if (dvm.Contents != null)
{
byte[] imageData = null;
using (var binaryReader = new BinaryReader(dvm.Contents.OpenReadStream()))
{
imageData = binaryReader.ReadBytes((int)dvm.Contents.Length);
}
docs.Contents = imageData;
}
dRepository.Add(docs);
return RedirectToAction("Index");
}
return View(docs);
}
In Startup.cs i connection throws
services.AddSingleton(Configuration);
Please, help me understand, how i can call connection string and transfering login and password of user? And where? And is it possible?
Please, i realy need help with this!

Related

SignalR: Websocket closed with error: InternalServerError

On the front side when the user adds a new mp3. In addition to writing this to the database, I also need to transfer that mp3 to the client side. But my client side is Worker Service. I need to transfer this mp3 to that Worker Service via SignalR.
My SignalR server project codes :
Startup hub endpoint :
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}");
endpoints.MapHub<TrackHub>("/hubs/track");
});
Hub :
public class TrackHub : Hub
{
public static Dictionary<int, string> ActiveUsers = new Dictionary<int, string>();
public TrackHub()
{
}
public async Task SendMessage(string message)
{
var connectionId = Context.ConnectionId;
await Clients.Others.SendAsync("ReceiveMessage", message + connectionId);
}
public override async Task OnConnectedAsync()
{
await Clients.All.SendAsync("ActiveUsers");
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await Clients.All.SendAsync("ActiveUsers");
}
}
HubContext
public class TrackBusiness
{
private readonly IHubContext<TrackHub> _hubContext;
public TrackBusiness(IHubContext<TrackHub> hubContext)
{
_hubContext = hubContext;
}
public Task SendMessage()
{
return _hubContext.Clients.All.SendAsync("Receive");
}
}
And my client side - worker service project :
public class SocketService : ISocketService
{
private HubConnection? _connection;
private readonly IConfiguration _configuration;
private readonly ILogger<SocketService> _logger;
public event OnNewTrackAddedEventHandler NewTrackAdded;
public event OnDeviceDeletedEventHandler DeviceDeleted;
public SocketService(IConfiguration configuration, ILogger<SocketService> logger)
{
_configuration = configuration;
_logger = logger;
}
public async Task Start()
{
_connection = new HubConnectionBuilder()
.WithUrl(_configuration.GetValue<string>("SocketUrl"))
.WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(10) })
.Build();
_connection.Reconnected += connectionId =>
{
if (_connection.State == HubConnectionState.Connected)
{
_logger.LogInformation("Socket reconnected");
}
if (_connection.State == HubConnectionState.Reconnecting)
{
_logger.LogInformation("Socket try to reconnect");
}
return Task.CompletedTask;
};
_connection.On<string, byte[]>("SendMessage", (imei, track) =>
{
NewTrackAdded.Invoke(imei, track);
});
_connection.On<string>("DeviceDeleted", (imei) =>
{
DeviceDeleted.Invoke(imei);
});
try
{
await _connection.StartAsync();
_logger.LogInformation("Socket started");
}
catch (Exception e)
{
_logger.LogWarning("Socket can't connect : {0}", e.Message);
}
}
}
My appSettings :
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ApiUrl": "localhost",
"SocketUrl": "http://localhost:29082/hubs/track"
}
But I run into this error when I start the project. Can you help with the problem?

Dependency Injection Quartz.Net Scheduler

I'm currently trying to use a repository to update some data in the DB using quartz.net.
Keep in mind that I'm using ASP.Net Core 3.1
The problem that I'm currently having is that when I'm injecting my IUserProjectRepository in the constructor of the IJob the job wont get executed and I also get an error in the Quartz DB implementation:
So, this is how my startup.cs looks like:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<UserProjectStatusJob>();
services.AddTransient(provider => GetScheduler().Result);
}
....
private async Task<IScheduler> GetScheduler()
{
NameValueCollection properties = new NameValueCollection
{
{ "quartz.scheduler.instanceName", "Cliche" },
{ "quartz.scheduler.instanceId", "Cliche" },
{ "quartz.jobStore.type", "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" },
{ "quartz.jobStore.useProperties", "true" },
{ "quartz.jobStore.dataSource", "default" },
{ "quartz.jobStore.tablePrefix", "QRTZ_" },
{
"quartz.dataSource.default.connectionString",
"connectionstring"
},
{ "quartz.dataSource.default.provider", "SqlServer" },
{ "quartz.threadPool.threadCount", "1" },
{ "quartz.serializer.type", "json" },
};
var schedulerFactory = new StdSchedulerFactory(properties);
var scheduler = await schedulerFactory.GetScheduler();
await scheduler.Start();
return scheduler;
}
This is how my Job (UserProjectStatusJob) Looks like:
public class UserProjectStatusJob : IJob
{
private IUserProjectRepository _userProjectRepository;
public UserProjectStatusJob(IUserProjectRepository userProjectRepository)
{
this._userProjectRepository = userProjectRepository;
}
public Task Execute(IJobExecutionContext context)
{
try
{
JobDataMap dataMap = context.JobDetail.JobDataMap;
string userProjectId = dataMap.GetString("userProjectId");
string userProjectProjectId = dataMap.GetString("userProjectProjectId");
_userProjectRepository.CloseUserProject(userProjectProjectId, userProjectId);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return Task.FromResult(0);
}
}
I create my job in the same UserProjectRepository:
public class UserProjectRepository : IUserProjectRepository
{
private readonly ApplicationDbContext _dbContext;
private readonly IFileService _fileService;
private readonly INotificationRepository _notificationRepository;
private readonly IScheduler _scheduler;
public UserProjectRepository(ApplicationDbContext dbContext,
IFileService fileService,
INotificationRepository notificationRepository,
IScheduler scheduler)
{
this._scheduler = scheduler;
this._notificationRepository = notificationRepository;
this._fileService = fileService;
this._dbContext = dbContext;
}
public async Task CreateCronJobForUserProject(UserProject userProject)
{
// Add Later in to startAt
TimeSpan timeToTrigger = userProject.Project.Assignment.DeadLine - DateTime.Now;
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity($"Check Availability-{DateTime.Now}")
.StartAt(DateTime.Now.AddSeconds(15))
.WithPriority(1)
.Build();
IDictionary<string, object> map = new Dictionary<string, object>()
{
{"userProjectId", $"{userProject.Id}" },
{"userProjectProjectId", $"{userProject.ProjectId}" },
};
IJobDetail job = JobBuilder.Create<UserProjectStatusJob>()
.WithIdentity($"Check Availability-{DateTime.Now}")
.SetJobData(new JobDataMap(map))
.Build();
await this._scheduler.ScheduleJob(job, trigger);
}
}
EDIT:
Error:
After taking a closer look I did found this:
[14:46:50 ERR] An error occurred instantiating job to be executed. job= 'DEFAULT.Check Availability-10/28/2020 14:46:35'
Quartz.SchedulerException: Problem instantiating class 'IKL.Data.Services.UserProjectStatusJob: Cannot instantiate type which has no empty constructor (Parameter 'UserProjectStatusJob')'
---> System.ArgumentException: Cannot instantiate type which has no empty constructor (Parameter 'UserProjectStatusJob')

How to create an API with severals DB connections

I need to create an API in .NET to connect and verify some data in several database engines (MySQl, PostgreSQL, SQL Server).
I can make one connection, but I don't understand how to make more than one.
Here's my code:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
#region MSSqlServer
var connection = Configuration.GetConnectionString("SQLSRV");
services
.AddDbContext<SQLSRVDBContext>
(options => options.UseSqlServer(connection));
services
.AddTransient<IService, Service>();
#endregion
services.AddMvc();
}
appsettings.json
"ConnectionStrings": {
"SQLSRV": "Server=localhost;Database= dbName;User Id=dbUser;Password=dbPassword;MultipleActiveResultSets=true",
},
Interface
namespace VerificaUsuarios.Interfaces
{
public interface IService
{
bool GetUsuarioSG(string userName, string password);
}
}
Implementation
namespace VerificaUsuarios.Services
{
using VerificaUsuarios.Interfaces;
using VerificaUsuarios.Models;
using VerificaUsuarios.Persistence;
using System.Linq;
using global::ADWS;
public class Service : IService
{
private readonly SQLSRVDBContext _sQLSRVDBContext;
public Service(SQLSRVDBContext sQLSRVDBContext)
{
_sQLSRVDBContext = sQLSRVDBContext;
}
public bool GetUsuarioSG(string userName, string password)
{
var result = new UsuariosSG();
var activeDirectory = new AD_WSClient();
try
{
bool isUsuario = activeDirectory.LoginAsync(userName, password).Result;
if(isUsuario)
{
try
{
result = _sQLSRVDBContext
.Usuarios
.Where(u => u.UsrLogin.Trim() == userName.Trim())
.First();
}
catch (System.Exception ex)
{
return false;
}
return true;
}
else
{
return false;
}
}
catch(System.Exception excep)
{
return false;
}
}
}
}
And the db context
namespace VerificaUsuarios.Persistence
{
using Microsoft.EntityFrameworkCore;
using VerificaUsuarios.Models;
public partial class SQLSRVDBContext : DbContext
{
public SQLSRVDBContext()
{
}
public virtual DbSet<UsuariosSG> Usuarios{ get; set; }
public SQLSRVDBContext(DbContextOptions<SQLSRVDBContext> options)
: base(options)
{ }
}
}
example of connection to different motors with validation against active directory
1) install the different EF Core Database Providers in VS
Entity Framework Core uses a provider model to access many different databases. EF Core includes providers as NuGet packages which you need to install.
The following lists database providers and NuGet packages for EF Core (NuGet package).
SQL Server Microsoft.EntityFrameworkCore.SqlServer
MySQL MySql.Data.EntityFrameworkCore
PostgreSQL Npgsql.EntityFrameworkCore.PostgreSQL
2)Perform the Scaffold-DbContext to the bd and tables that you want to use in the different engines.
PostgreSQL
Scaffold-DbContext "Host=myserver;Database=mydatabase;Username=myuser;Password=mypassword" Npgsql.EntityFrameworkCore.PostgreSQL -o Models -Table MyTablePSQL
MySql
Scaffold-DbContext "server=myserver;port=3306;user=myuser;password=mypass;database=mydb" MySql.Data.EntityFrameworkCore -OutputDir Models -f -Table MyTableMySQL
SqlServer
Scaffold-DbContext "Server=myserver;Database=mydb;User Id=myuser;Password=mypassword;MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Table MyTableSQL
3)add the different connection string in the appsettings.json
"ConnectionStrings": {
"SQLSRV": "Server=myserver;Database= mydb;User Id=myuser;Password=myPassword;MultipleActiveResultSets=true",
"MySql": "server=myserver;user id=myuser;password=mypassword;port=3306;database=mydb;",
"PSQL": "Host=myserver;Database=mydb;Username=myuser;Password=mypassword"
},
4) modify the DbContext generated by the Scaffold-DbContext
SQLSRVDBContext
namespace MyProject.Persistence
{
using Microsoft.EntityFrameworkCore;
using MyProject.Models;
public partial class SQLSRVDBContext : DbContext
{
public SQLSRVDBContext()
{
}
public virtual DbSet<MyTableSQL> Users{ get; set; }
public SQLSRVDBContext(DbContextOptions<SQLSRVDBContext> options)
: base(options)
{ }
}
}
MySQLDBContext
namespace MyProject.Persistence
{
using Microsoft.EntityFrameworkCore;
using MyProject.Models;
public partial class MySQLDBContext : DbContext
{
public MySQLDBContext()
{
}
public virtual DbSet<MyTableMySQL> Users { get; set; }
public MySQLDBContext(DbContextOptions<MySQLDBContext> options)
: base(options)
{ }
}
}
PostgreSQL
namespace MyProject.Models
{
using Microsoft.EntityFrameworkCore;
public partial class PostgreSQLDBContext : DbContext
{
public PostgreSQLDBContext()
{
}
public virtual DbSet<MyTablePSQL> Users { get; set; }
public PostgreSQLDBContext(DbContextOptions<PostgreSQLDBContext> options)
: base(options)
{
}
}
}
5)create Interfaces
SQLSRV
namespace MyProject.Interfaces
{
public interface IService
{
bool GetUserSQLSRV(string userName, string password);
}
}
MySQL
namespace MyProject.Interfaces
{
public interface IServiceMySQL
{
bool GetUserMySQL(string userName, string password);
}
}
PostgreSQL
namespace MyProject.Interfaces
{
public interface IServicePSQL
{
bool GetUserPSQL(string userName, string password);
}
}
6)create the Services
SQLSRV(SQLSRVDBContext)
namespace MyProject.Services
{
using MyProject.Interfaces;
using MyProject.Models;
using MyProject.Persistence;
using System.Linq;
using global::ADWS;
public class Service : IService
{
private readonly SQLSRVDBContext _sQLSRVDBContext;
public Service(SQLSRVDBContext sQLSRVDBContext)
{
_sQLSRVDBContext = sQLSRVDBContext;
}
public bool GetUserSQLSRV(string userName, string password)
{
var result = new MyTableSQL();
var activeDirectory = new AD_WSClient();
try
{
bool isUser = activeDirectory.LoginAsync(userName, password).Result;
if(isUser)
{
try
{
result = _sQLSRVDBContext
.Users
.Where(u => u.UsrLogin.Trim() == userName.Trim())
.First();
}
catch (System.Exception ex)
{
return false;
}
return true;
}
else
{
return false;
}
}
catch(System.Exception excep)
{
return false;
}
}
}
}
MySQL(MySQLDBContext)
namespace MyProject.Services
{
using MyProject.Interfaces;
using MyProject.Models;
using MyProject.Persistence;
using System.Linq;
using global::ADWS;
public class ServiceMySQL : IServiceMySQL
{
private readonly MySQLDBContext _mySQLDBContext;
public ServiceMySQL(MySQLDBContext mySQLDBContext)
{
_mySQLDBContext = mySQLDBContext;
}
public bool GetUserMySQL(string userName, string password)
{
var result = new MyTableMySQL();
var activeDirectory = new AD_WSClient();
try
{
bool isUser = activeDirectory.LoginAsync(userName, password).Result;
if(isUser)
{
try
{
result = _mySQLDBContext
.Users
.Where(u => u.UsrLogin.Trim() == userName.Trim())
.First();
}
catch (System.Exception ex)
{
return false;
}
return true;
}
else
{
return false;
}
}
catch(System.Exception excep)
{
return false;
}
}
}
}
PostgreSQL(PostgreSQLDBContext)
namespace MyProject.Services
{
using MyProject.Interfaces;
using MyProject.Models;
using MyProject.Persistence;
using System.Linq;
using global::ADWS;
public class ServicePSQL : IServicePSQL
{
private readonly PostgreSQLDBContext _postgreSQLDBContext;
public ServicePSQL(PostgreSQLDBContext postgreSQLDBContext)
{
_postgreSQLDBContext = postgreSQLDBContext;
}
public bool GetUserPSQL(string userName, string password)
{
var result = new MyTablePSQL();
var activeDirectory = new AD_WSClient();
try
{
bool isUser = activeDirectory.LoginAsync(userName, password).Result;
if(isUser)
{
try
{
result = _postgreSQLDBContext
.Users
.Where(u => u.UsrLogin.Trim() == userName.Trim())
.First();
}
catch (System.Exception ex)
{
return false;
}
return true;
}
else
{
return false;
}
}
catch(System.Exception excep)
{
return false;
}
}
}
}
7) configure the different services in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
#region SQLSRV
var connection = Configuration.GetConnectionString("SQLSRV");
services
.AddDbContext<SQLSRVDBContext>
(options => options.UseSqlServer(connection));
services
.AddTransient<IService, Service>();
#endregion
#region MySql
var connectionMySql = Configuration.GetConnectionString("MySQL");
services
.AddDbContext<MySQLDBContext>
(options => options.UseMySQL(connectionMySql));
services
.AddTransient<IServiceMySQL, ServiceMySQL>();
#endregion
#region PostgreSQL
var connectionPSQL = Configuration.GetConnectionString("PSQL");
services
.AddDbContext<PostgreSQLDBContext>
(options => options.UseNpgsql(connectionPSQL));
services.AddTransient<IServicePSQL, ServicePSQL>();
#endregion
services.AddMvc();
}
8)creation of the different Controller
SQLSRV
namespace MyProject.Controllers
{
using Microsoft.AspNetCore.Mvc;
using MyProject.Interfaces;
[Route("api/GET/[controller]")]
public class UserSQLSRVController : Controller
{
private readonly IService _userSQLSRVService;
public UserSQLSRVController(IService userSQLSRVService)
{
_userSQLSRVService = userSQLSRVService;
}
[HttpGet]
public IActionResult GetUserSQLSRV(string userName, string password)
{
return Ok(
_userSQLSRVService.GetUserSQLSRV(userName, password));
}
}
}
MySQL
namespace MyProject.Controllers
{
using Microsoft.AspNetCore.Mvc;
using MyProject.Interfaces;
[Route("api/GET/[controller]")]
public class UserMySqlController : Controller
{
private readonly IServiceMySQL _userMySqlService;
public UserMySqlController(IServiceMySQL userMySqlService)
{
_userMySqlService = userMySqlService;
}
[HttpGet]
public IActionResult GetUserMySQL(string userName, string password)
{
return Ok(
_userMySqlService.GetUserMySQL(userName, password));
}
}
}
PSQL
namespace MyProject.Controllers
{
using Microsoft.AspNetCore.Mvc;
using MyProject.Interfaces;
[Route("api/GET/[controller]")]
public class UserPSQLController : Controller
{
private readonly IServicePSQL _userPSQLService;
public UserPSQLController(IServicePSQL userPSQLService)
{
_userPSQLService = userPSQLService;
}
[HttpGet]
public IActionResult GetUserPSQL(string userName, string password)
{
return Ok(
_userPSQLService.GetUserPSQL(userName, password));
}
}
}

User or Role authorization using AuthorizeAttribute in .Net Core

I'm using below code working fine in ASP.Net MVC. I need this code is convert to Dot net Core. But here httpcontextbase is not get as parameter and RedirectToRouteResult, RouteValueDictionary are throw an error. Please give the solution for MVC to .Net core. Thanks In Advance.
public class RoleAuthorizeAttribute : AuthorizeAttribute
{
private readonly string[] permissionRoles;
private users user = null;
private string currentRole = null;
public RoleAuthorizeAttribute(params string[] roles)
{
this.permissionRoles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
user = userHandler.GetLoginUserRecord();
currentRole = userHandler.GetLoginUserRole();
bool authorize = false;
if (user != null)
authorize = permissionRoles.Contains(currentRole);
return authorize;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext actionContext)
{
if (user == null)
{
actionContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Login" }, { "controller", "Account" } });
}
else if (permissionRoles.Contains(currentRole) == false)
{
actionContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Logout" }, { "controller", "Account" } });
}
}
}

How could i manage multiple database in linq2db

I want to manage multiple database connection in my application.I am using ASP.NET Core & linq2db. For my first database connection i have create below configuration and its working fine.
public class DatabaseXSettings : ILinqToDBSettings
{
public IEnumerable<IDataProviderSettings> DataProviders
{
get { yield break; }
}
public string DefaultConfiguration => "Oracle.Managed";
public string DefaultDataProvider => "Oracle.Managed";
public string ConnectionString { get; set; }
public DatabaseXSettings(string connectionString)
{
ConnectionString = connectionString;
}
public IEnumerable<IConnectionStringSettings> ConnectionStrings
{
get
{
yield return
new ConnectionStringSettings
{
Name = "DatabaseX",
ProviderName = "Oracle.Managed",
ConnectionString = ConnectionString
};
}
}
}
public static class DatabaseXStartup
{
private static bool _started;
public static void Init(string connectionString)
{
if (!_started)
{
DataConnection.DefaultSettings = new DatabaseXSettings(connectionString);
_started = true;
}
}
}
public class DatabaseX : DataConnection
{
public DatabaseX() : base("DatabaseX") { }
}
For My Second Database
For my second database connection i create a similar configuration like this. But this not working.
public class DatabaseYSettings : ILinqToDBSettings
{
.......
}
public static class DatabaseYStartup
{
.......
}
public class DatabaseY : DataConnection
{
public DatabaseY() : base("DatabaseY") { }
}
My appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DatabaseX": "Data Source=..........",
"DatabaseY": "Data Source=.........."
}
}
LinqToDB.LinqToDBException: 'Configuration 'DatabaseY' is not defined.'
Is there any other way to do that.
Edit: added example
You don't need two ILinqToDBSettings instances. You should move second database settings to first settings class, so ConnectionStrings will return both connection strings.
public class DatabaseSettings : ILinqToDBSettings
{
public IEnumerable<IDataProviderSettings> DataProviders
{
get { yield break; }
}
public string DefaultConfiguration => "Oracle.Managed";
public string DefaultDataProvider => "Oracle.Managed";
private readonly IConnectionStringSettings[] _connectionStrings;
public DatabaseSettings(IConnectionStringSettings[] connectionStrings)
{
_connectionStrings = connectionStrings;
}
public IEnumerable<IConnectionStringSettings> ConnectionStrings => _connectionStrings;
}
public static class DatabaseSetup
{
// just call it on application startup
public static void Init()
{
// create connectionStrings collection with both connection strings from appsettings.json
DataConnection.DefaultSettings = new DatabaseSettings(connectionStrings);
}
}