School Commit Init

This commit is contained in:
2024-08-31 12:07:21 +03:00
commit 0b130ee18c
2801 changed files with 4720552 additions and 0 deletions
@@ -0,0 +1,43 @@
*.swp
*.*~
project.lock.json
.DS_Store
*.pyc
nupkg/
# Visual Studio Code
.vscode/
# Rider
.idea/
# Visual Studio
.vs/
# Fleet
.fleet/
# Code Rush
.cr/
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
msbuild.log
msbuild.err
msbuild.wrn
@@ -0,0 +1,120 @@
// using AutoMapper;
// using Silk_Road_Api.Models;
// using Silk_Road_Api.Profiles;
// using Silk_Road_Api.Repositories;
// using Silk_Road_Api.Services;
// using Silk_Road_Api.ViewModels;
// namespace Silk_Road_Api_Test;
// public class DrugServiceTest
// {
// [Fact]
// public async void GetDrug_ValidId_ReturnsADrug()
// {
// // Arrange
// IDrugService drugService = new DrugService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<DrugProfile>())));
// // Act
// var drug = await drugService.GetDrug(1);
// // Assert
// Assert.NotNull(drug);
// Assert.Equal(1, drug.id);
// }
// [Fact]
// public async void GetDrug_InvalidId_ThrowsError()
// {
// // Arrange
// IDrugService drugService = new DrugService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<DrugProfile>())));
// // Act
// var act = async () => await drugService.GetDrug(100);
// // Assert
// await Assert.ThrowsAsync<Exception>(act);
// }
// [Fact]
// public async void GetDrugs_WithPageSize10andPage1_Returns10Drugs()
// {
// // Arrange
// IDrugService drugService = new DrugService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<DrugProfile>())));
// SearchInput searchInput = new SearchInput
// {
// PageSize = 10,
// Page = 1
// };
// // Act
// var drugs = await drugService.GetDrugs(searchInput);
// // Assert
// Assert.NotNull(drugs);
// Assert.Equal(16, drugs.Total);
// Assert.Equal(10, drugs.Items.Count);
// }
// [Fact]
// public async void AddDrugs_Succesful()
// {
// // Arrange
// IDrugService drugService = new DrugService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<DrugProfile>())));
// DrugViewModel drug = new DrugViewModel
// {
// name = "Test Drug",
// description = "Test Description",
// price = 100,
// stock = 10,
// manufacturer = "Pfizer"
// };
// // Act
// var result = await drugService.AddDrug(drug);
// // Assert
// Assert.True(result);
// }
// [Fact]
// public async void UpdateDrugs_Succesful()
// {
// // Arrange
// IDrugService drugService = new DrugService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<DrugProfile>())));
// DrugViewModel drug = new DrugViewModel
// {
// id = 1,
// name = "Test Drug",
// description = "Test Description",
// price = 100,
// stock = 10,
// manufacturer = "Pfizer"
// };
// // Act
// var result = await drugService.UpdateDrug(drug);
// // Assert
// Assert.True(result);
// }
// [Fact]
// public async void DeleteDrugs_Succesful()
// {
// // Arrange
// IDrugService drugService = new DrugService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<DrugProfile>())));
// // Act
// var result = await drugService.DeleteDrug(1);
// // Assert
// Assert.True(result);
// }
// [Fact]
// public async void DeleteDrugs_InvalidId_ReturnsFalse()
// {
// // Arrange
// IDrugService drugService = new DrugService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<DrugProfile>())));
// // Act
// var result = await drugService.DeleteDrug(100);
// // Assert
// Assert.False(result);
// }
// }
@@ -0,0 +1 @@
global using Xunit;
@@ -0,0 +1,113 @@
// using AutoMapper;
// using Silk_Road_Api;
// using Silk_Road_Api.Models;
// using Silk_Road_Api.Repositories;
// using Silk_Road_Api.Services;
// using Silk_Road_Api.ViewModels;
// namespace Silk_Road_Api_Test;
// public class ManufacturerServiceTest
// {
// [Fact]
// public async void GetManufacturer_ValidId_ReturnsAManufacturer()
// {
// // Arrange
// IManufacturerService manufacturerService = new ManufacturerService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<ManufacturerProfile>())));
// // Act
// var drug = await manufacturerService.GetManufacturer(1);
// // Assert
// Assert.NotNull(drug);
// Assert.Equal(1, drug.id);
// }
// [Fact]
// public async void GetManufacturer_InvalidId_ThrowsError()
// {
// // Arrange
// IManufacturerService manufacturerService = new ManufacturerService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<ManufacturerProfile>())));
// // Act
// var act = async () => await manufacturerService.GetManufacturer(100);
// // Assert
// await Assert.ThrowsAsync<Exception>(act);
// }
// [Fact]
// public async void GetManufacturers_WithPageSize1andPage1_Returns1Drugs()
// {
// // Arrange
// IManufacturerService manufacturerService = new ManufacturerService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<ManufacturerProfile>())));
// SearchInput searchInput = new SearchInput
// {
// PageSize = 1,
// Page = 1
// };
// // Act
// var manufacturers = await manufacturerService.GetManufacturers(searchInput);
// // Assert
// Assert.NotNull(manufacturers);
// Assert.Equal(1, manufacturers.Total);
// Assert.Equal(1, manufacturers.Items.Count);
// }
// [Fact]
// public async void AddDrugs_Succesful()
// {
// // Arrange
// IManufacturerService manufacturerService = new ManufacturerService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<ManufacturerProfile>())));
// ManufacturerViewModel manufacturer = new ManufacturerViewModel
// {
// name = "Azteca",
// contact = "mail@azteca.com",
// address = "test",
// };
// // Act
// var result = await manufacturerService.AddManufacturer(manufacturer);
// // Assert
// Assert.True(result);
// }
// [Fact]
// public async void UpdateDrugs_Succesful()
// {
// // Arrange
// IManufacturerService manufacturerService = new ManufacturerService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<ManufacturerProfile>())));
// ManufacturerViewModel manufacturer = new ManufacturerViewModel
// {
// id = 1,
// name = "Azteca",
// contact = "mail@azteca.com",
// address = "test",
// };
// // Act
// var result = await manufacturerService.UpdateManufacturer(manufacturer);
// // Assert
// Assert.True(result);
// }
// [Fact]
// public async void DeleteDrugs_Succesful()
// {
// // Arrange
// IManufacturerService manufacturerService = new ManufacturerService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<ManufacturerProfile>())));
// // Act
// var result = await manufacturerService.DeleteManufacturer(1);
// // Assert
// Assert.True(result);
// }
// [Fact]
// public async void DeleteDrugs_InvalidId_ReturnsFalse()
// {
// // Arrange
// IManufacturerService manufacturerService = new ManufacturerService(new MemoryRepository(), new MemoryManufacturerRepository(), new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<ManufacturerProfile>())));
// // Act
// var result = await manufacturerService.DeleteManufacturer(100);
// // Assert
// Assert.False(result);
// }
// }
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>Silk_Road_Api_Test</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Silk Road Api\Silk Road Api.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,28 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Silk Road Api", "Silk Road Api\Silk Road Api.csproj", "{424EB0D7-2D26-458F-B242-330792AC9265}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Silk Road Api Test", "Silk Road Api Test\Silk Road Api Test.csproj", "{D14A6B3E-FD52-42CF-9468-5782E269FCBD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{424EB0D7-2D26-458F-B242-330792AC9265}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{424EB0D7-2D26-458F-B242-330792AC9265}.Debug|Any CPU.Build.0 = Debug|Any CPU
{424EB0D7-2D26-458F-B242-330792AC9265}.Release|Any CPU.ActiveCfg = Release|Any CPU
{424EB0D7-2D26-458F-B242-330792AC9265}.Release|Any CPU.Build.0 = Release|Any CPU
{D14A6B3E-FD52-42CF-9468-5782E269FCBD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D14A6B3E-FD52-42CF-9468-5782E269FCBD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D14A6B3E-FD52-42CF-9468-5782E269FCBD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D14A6B3E-FD52-42CF-9468-5782E269FCBD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
@@ -0,0 +1,115 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Silk_Road_Api.Models;
using Silk_Road_Api.Repositories;
using Silk_Road_Api.Services;
using Timer = System.Timers.Timer;
using System.Net.WebSockets;
using System.Text;
using Microsoft.AspNetCore.Http.HttpResults;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Controllers;
[ApiController]
[Route("[controller]")]
public class DrugController : ControllerBase
{
private readonly IDrugService _drugService;
public DrugController(IDrugService drugService)
{
_drugService = drugService;
}
[HttpGet("get-drugs", Name = "GetDrugs")]
public async Task<IActionResult> GetDrugs([FromQuery] SearchInput searchInput)
{
var drugs = await _drugService.GetDrugs(this, searchInput);
return Ok(drugs);
}
[HttpGet("get-drug/{id}", Name = "GetDrug")]
public async Task<IActionResult> GetDrug(int id)
{
var drug = await _drugService.GetDrug(this,id);
if (drug == null)
{
return NotFound();
}
return Ok(drug);
}
[HttpPost("add-drug", Name = "AddDrug")]
public async Task<IActionResult> AddDrug([FromBody] DrugViewModel drug)
{
if (await _drugService.AddDrug(this,drug))
return Ok();
return BadRequest();
}
[HttpPut("update-drug", Name = "UpdateDrug")]
public async Task<IActionResult> UpdateDrug([FromBody] DrugViewModel drug)
{
if (await _drugService.UpdateDrug(this, drug))
return Ok();
return BadRequest();
}
[HttpDelete("delete-drug/{id}", Name = "DeleteDrug")]
public async Task<IActionResult> DeleteDrug(int id)
{
if (await _drugService.DeleteDrug(this, id))
return Ok();
return BadRequest();
}
[Route("/ws")]
[ApiExplorerSettings(IgnoreApi = true)]
public async Task Get()
{
if (HttpContext.WebSockets.IsWebSocketRequest)
{
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
var timer = new Timer(5000);
timer.Elapsed += async (sender, e) =>
{
await SendMessage(webSocket, timer);
};
timer.Start();
while (webSocket.State == WebSocketState.Open)
{
await Task.Delay(1000);
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(new byte[1024]), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
timer.Stop();
}
}
}
else
{
HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}
}
[HttpGet("get-chart-data", Name = "GetChartData")]
public async Task<IActionResult> GetChartData()
{
var chartData = await _drugService.GetChartData();
return Ok(chartData);
}
private async Task SendMessage(WebSocket webSocket, Timer timer)
{
_drugService.GenerateDrugs();
if (webSocket.State == WebSocketState.Open)
{
var buffer = Encoding.UTF8.GetBytes("Drugs generated");
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
@@ -0,0 +1,62 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Silk_Road_Api.Extensions;
using Silk_Road_Api.Models;
using Silk_Road_Api.Services;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Controllers;
[ApiController]
[Route("[controller]")]
public class ManufacturerController : ControllerBase
{
private readonly IManufacturerService _manufacturerService;
public ManufacturerController(IManufacturerService manufacturerService)
{
_manufacturerService = manufacturerService;
}
[HttpGet("get-manufacturer", Name = "GetManufacturers")]
public async Task<IActionResult> GetManufacturers([FromQuery] SearchInput searchInput)
{
var manufacturers = await _manufacturerService.GetManufacturers(this, searchInput);
return Ok(manufacturers);
}
[HttpGet("get-manufacturer/{id}", Name = "GetManufacturer")]
public async Task<IActionResult> GetManufacturer(int id)
{
var manufacturer = await _manufacturerService.GetManufacturer(this, id);
if (manufacturer == null)
{
return NotFound();
}
return Ok(manufacturer);
}
[HttpPost("add-manufacturer", Name = "AddManufacturer")]
public async Task<IActionResult> AddManufacturer([FromBody] ManufacturerViewModel manufacturer)
{
if (await _manufacturerService.AddManufacturer(this, manufacturer))
return Ok();
return BadRequest();
}
[HttpPut("update-manufacturer", Name = "UpdateManufacturer")]
public async Task<IActionResult> UpdateManufacturer([FromBody] ManufacturerViewModel manufacturer)
{
if (await _manufacturerService.UpdateManufacturer(this, manufacturer))
return Ok();
return BadRequest();
}
[HttpDelete("delete-manufacturer/{id}", Name = "DeleteManufacturer")]
public async Task<IActionResult> DeleteManufacturer(int id)
{
if (await _manufacturerService.DeleteManufacturer(this, id))
return Ok();
return BadRequest();
}
}
@@ -0,0 +1,49 @@
using Microsoft.AspNetCore.Mvc;
using Silk_Road_Api.Extensions;
using Silk_Road_Api.Models;
using Silk_Road_Api.Services;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Controllers
{
[ApiController]
[Route("user")]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[HttpPost("register-user", Name ="RegisterUser")]
public async Task<IActionResult> RegisterUserAsync([FromBody] RegistrationViewModel user)
{
try
{
await _userService.RegisterUser(user);
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("login-user", Name = "LoginUser")]
public IActionResult LoginUser([FromBody] LoginViewModel loginViewModel)
{
try
{
var user = _userService.LoginUser(loginViewModel.username, loginViewModel.password);
HttpContext.Session.Set<User>("user", user);
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore;
using Silk_Road_Api.Models;
namespace Silk_Road_Api.DatabaseContext;
public class SilkRoadApiContext : DbContext
{
public SilkRoadApiContext(DbContextOptions options) : base(options)
{
this.Options = options;
}
internal DbContextOptions Options { get; }
public DbSet<Drug> Drugs { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Manufacturer> Manufacturers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Drug>().ToTable("Drugs");
modelBuilder.Entity<Manufacturer>().ToTable("Manufacturers");
modelBuilder.Entity<User>().ToTable("Users");
}
}
@@ -0,0 +1,18 @@
using System.Text.Json;
namespace Silk_Road_Api.Extensions
{
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonSerializer.Serialize(value));
}
public static T? Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default : JsonSerializer.Deserialize<T>(value);
}
}
}
@@ -0,0 +1,7 @@
namespace Silk_Road_Api.Models;
public class ChartModel
{
public int ManufacturerId { get; set; }
public int Count { get; set; }
}
@@ -0,0 +1,24 @@
using System.ComponentModel.DataAnnotations;
namespace Silk_Road_Api.Models;
public class Drug
{
public int id { get; set; } = 0;
public string name { get; set; }
public decimal price { get; set; }
public int stock { get; set; }
public string description { get; set; }
public int manufacturerId { get; set; }
public string sideEffects { get; set; }
public string interactions { get; set; }
public string dosage { get; set; }
public string contraindications { get; set; }
public string warnings { get; set; }
public string storage { get; set; }
public string pregnancy { get; set; }
public string breastfeeding { get; set; }
public string overdose { get; set; }
}
@@ -0,0 +1,10 @@
namespace Silk_Road_Api;
public class Manufacturer
{
public int id { get; set; }
public string name { get; set; }
public string address { get; set; }
public string contact { get; set; }
}
@@ -0,0 +1,8 @@
namespace Silk_Road_Api.Models;
public class SearchInput
{
public int Page { get; set; }
public int PageSize { get; set; }
public string? Sorting { get; set; }
}
@@ -0,0 +1,10 @@
namespace Silk_Road_Api;
public class SearchOutput<T>
{
public int Page { get; set; }
public int PageSize { get; set; }
public int Total { get; set; }
public List<T> Items { get; set; }
}
@@ -0,0 +1,15 @@
namespace Silk_Road_Api.Models
{
public class User
{
public int id { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public string username { get; set; }
public string email { get; set; }
public string password { get; set; }
public int companyid { get; set; }
}
}
@@ -0,0 +1,14 @@
using AutoMapper;
using Silk_Road_Api.Models;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Profiles;
public class DrugProfile : Profile
{
public DrugProfile()
{
CreateMap<Drug, DrugViewModel>();
CreateMap<DrugViewModel, Drug>();
}
}
@@ -0,0 +1,14 @@
using AutoMapper;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api;
public class ManufacturerProfile : Profile
{
public ManufacturerProfile()
{
CreateMap<Manufacturer, ManufacturerViewModel>();
CreateMap<ManufacturerViewModel, Manufacturer>();
CreateMap<RegistrationViewModel, Manufacturer>();
}
}
@@ -0,0 +1,14 @@
using AutoMapper;
using Silk_Road_Api.Models;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Profiles
{
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<RegistrationViewModel, User>();
}
}
}
@@ -0,0 +1,63 @@
using Silk_Road_Api.Repositories;
using Silk_Road_Api.Services;
using Microsoft.AspNetCore.Builder;
using Silk_Road_Api.DatabaseContext;
using Microsoft.EntityFrameworkCore;
namespace Silk_Road_Api;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<SilkRoadApiContext>(
options => options.UseSqlServer(builder.Configuration.GetConnectionString("SilkRoadApiContext"))
);
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IDrugRepository, DrugRepository>();
builder.Services.AddScoped<IManufacturerRepository, ManufacturerRepository>();
builder.Services.AddScoped<IDrugService, DrugService>();
builder.Services.AddScoped<IManufacturerService, ManufacturerService>();
builder.Services.AddAutoMapper(typeof(Program));
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.Cookie.Name = "SessionId";
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
app.UseSwagger();
app.UseSwaggerUI();
//}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromSeconds(1),
});
app.MapControllers();
app.UseSession();
app.Run();
}
}
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:25677",
"sslPort": 44376
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5176",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7260;http://localhost:5176",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
@@ -0,0 +1,71 @@
using System.Linq.Expressions;
using Bogus;
using Microsoft.EntityFrameworkCore;
using Silk_Road_Api.DatabaseContext;
using Silk_Road_Api.Models;
namespace Silk_Road_Api.Repositories;
public class DrugRepository : Repository, IDrugRepository
{
private static readonly List<string> prefixes = ["Neuro", "Bio", "Cyber", "Synth", "Nano", "Micro", "Hyper", "Psycho"];
private static readonly List<string> roots = ["zym", "plex", "morp", "cyto", "gen", "nerv", "neuro", "bio", "pharm", "morph"];
private static readonly List<string> suffixes = ["x", "z", "on", "ex", "ol", "ine", "ium", "ane", "ide", "os"];
public DrugRepository(SilkRoadApiContext context) : base(context)
{
//GenerateDrugs(10);
}
public IQueryable<Drug> GetDrugs()
{
return AsQueryable<Drug>();
}
public async Task<Drug> GetDrug(int id)
{
return await GetAsync<Drug>(id);
}
public async Task<int> ExecuteCount(IQueryable<Drug> query)
{
Expression<Func<IQueryable<Drug>>> expression = () => query;
return await _context.FromExpression(expression)
.AsNoTracking()
.Select(x => 1)
.CountAsync()
.ConfigureAwait(false);
}
public void GenerateDrugs(int n)
{
var drugs = new Faker<Drug>()
.RuleFor(d => d.name, f => f.PickRandom(prefixes) + f.PickRandom(roots) + f.PickRandom(suffixes))
.RuleFor(d => d.price, f => f.Random.Number(5, 100))
.RuleFor(d => d.stock, f => f.Random.Number(1, 100))
.RuleFor(d => d.manufacturerId, f => f.Random.Number(1, 10))
.RuleFor(d => d.description, f => f.Lorem.Letter(30))
.RuleFor(d => d.sideEffects, f => f.Lorem.Letter(30))
.RuleFor(d => d.interactions, f => f.Lorem.Letter(30))
.RuleFor(d => d.dosage, f => f.Lorem.Letter(30))
.RuleFor(d => d.contraindications, f => f.Lorem.Letter(30))
.RuleFor(d => d.warnings, f => f.Lorem.Letter(30))
.RuleFor(d => d.storage, f => f.Lorem.Letter(30))
.RuleFor(d => d.pregnancy, f => f.Lorem.Letter(30))
.RuleFor(d => d.breastfeeding, f => f.Lorem.Letter(30))
.RuleFor(d => d.overdose, f => f.Lorem.Letter(30))
.Generate(n);
_context.AddRange(drugs);
_context.SaveChanges();
}
public async Task<IQueryable<ChartModel>> GetChartData()
{
var chartData = GetDrugs().GroupBy(d => d.manufacturerId)
.Select(g => new ChartModel
{
ManufacturerId = g.Key,
Count = g.Count()
});
return chartData;
}
}
@@ -0,0 +1,13 @@
using Silk_Road_Api.Models;
namespace Silk_Road_Api.Repositories;
public interface IDrugRepository : IRepository
{
public IQueryable<Drug> GetDrugs();
public Task<Drug> GetDrug(int id);
public Task<int> ExecuteCount(IQueryable<Drug> query);
public void GenerateDrugs(int n = 5);
public Task<IQueryable<ChartModel>> GetChartData();
}
@@ -0,0 +1,10 @@
namespace Silk_Road_Api.Repositories;
public interface IManufacturerRepository : IRepository
{
public IQueryable<Manufacturer> GetManufacturers();
public Task<Manufacturer> GetManufacturer(int id);
public Task<int> GetManufacturerByName(string name);
public Task<int> ExecuteCount(IQueryable<Manufacturer> query);
public void GenerateManufacturers(int n = 5);
}
@@ -0,0 +1,12 @@
namespace Silk_Road_Api.Repositories;
public interface IRepository
{
public Task AddAsync<T>(T entity);
public void Update<T>(T entity) where T : class;
public void UpdateRange<T>(List<T> entities) where T : class;
public Task<bool> SaveChangesAsync();
Task<T> GetAsync<T>(params object[] ids) where T : class;
IQueryable<T> AsQueryable<T>() where T : class;
public void Delete<T>(T entity) where T : class;
}
@@ -0,0 +1,7 @@
namespace Silk_Road_Api;
public interface IRepositoryBase
{
public Task<T> GetAsync<T>(params object[] ids) where T : class;
public IQueryable<T> AsQueryable<T>() where T : class;
}
@@ -0,0 +1,12 @@
using Silk_Road_Api.Models;
using Silk_Road_Api.Repositories;
namespace Silk_Road_Api.Repositories
{
public interface IUserRepository : IRepository
{
public User? GetUserByUsernameAndPassword(string username, string password);
public User? GetUserByUsername(string username);
}
}
@@ -0,0 +1,50 @@
using System.Linq.Expressions;
using Bogus;
using Microsoft.EntityFrameworkCore;
using Silk_Road_Api.DatabaseContext;
namespace Silk_Road_Api.Repositories;
public class ManufacturerRepository : Repository, IManufacturerRepository
{
public ManufacturerRepository(SilkRoadApiContext context) : base(context)
{
//GenerateManufacturers(10);
}
public IQueryable<Manufacturer> GetManufacturers()
{
return AsQueryable<Manufacturer>();
}
public async Task<Manufacturer> GetManufacturer(int id)
{
return await GetAsync<Manufacturer>(id);
}
public async Task<int> GetManufacturerByName(string name)
{
return await AsQueryable<Manufacturer>().Where(x => x.name == name).Select(x => x.id).FirstOrDefaultAsync();
}
public void GenerateManufacturers(int n)
{
var manufacturers = new Faker<Manufacturer>()
.RuleFor(m => m.name, f => f.Company.CompanyName())
.RuleFor(m => m.address, f => f.Address.FullAddress())
.RuleFor(m => m.contact, f => f.Internet.Email())
.Generate(n);
_context.AddRange(manufacturers);
_context.SaveChanges();
}
public async Task<int> ExecuteCount(IQueryable<Manufacturer> query)
{
Expression<Func<IQueryable<Manufacturer>>> expression = () => query;
return await _context.FromExpression(expression)
.AsNoTracking()
.Select(x => 1)
.CountAsync()
.ConfigureAwait(false);
}
}
@@ -0,0 +1,93 @@
using Silk_Road_Api.Models;
namespace Silk_Road_Api.Repositories;
public class MemoryManufacturerRepository : IRepository, IManufacturerRepository
{
private readonly List<Manufacturer> _manufacturers = new List<Manufacturer>{
new Manufacturer { id = 1, name = "Pfizer", address = "New York", contact ="contact@Pfizer.com"},
new Manufacturer { id = 2, name = "Moderna", address = "New Jersey", contact ="contact@Moderna.com"}
};
public MemoryManufacturerRepository()
{
}
public new async Task AddAsync<T>(T entity)
{
(entity as Manufacturer).id = _manufacturers.Max(d => d.id) + 1;
_manufacturers.Add(entity as Manufacturer);
}
public new void Update<T>(T entity) where T : class
{
var manufacturerId = (entity as Manufacturer).id;
var manufacturer = _manufacturers.FirstOrDefault(d => d.id == manufacturerId);
if (manufacturer == null)
throw new Exception("Manufacturer not found");
manufacturer.name = (entity as Manufacturer).name;
manufacturer.address = (entity as Manufacturer).address;
manufacturer.contact = (entity as Manufacturer).contact;
}
public new void UpdateRange<T>(List<T> entities) where T : class
{
foreach (var entity in entities)
{
Update(entity);
}
}
public new async Task<bool> SaveChangesAsync()
{
return true;
}
public new async Task<Manufacturer> GetAsync<T>(params object[] ids) where T : class
{
return _manufacturers.FirstOrDefault(d => d.id == (int)ids.FirstOrDefault());
}
public new IQueryable<T> AsQueryable<T>() where T : class
{
return _manufacturers.AsQueryable() as IQueryable<T>;
}
public new void Delete<T>(T entity) where T : class
{
if (!_manufacturers.Remove(entity as Manufacturer))
throw new Exception("Failed to delete drug");
}
public IQueryable<Manufacturer> GetManufacturers()
{
return _manufacturers.AsQueryable();
}
public Task<Manufacturer> GetManufacturer(int id)
{
return Task.FromResult(_manufacturers.Where(d => d.id == id).FirstOrDefault());
}
public Task<int> GetManufacturerByName(string name)
{
return Task.FromResult(_manufacturers.Where(d => d.name == name).Select(d => d.id).FirstOrDefault());
}
public void GenerateManufacturers(int n = 5)
{
throw new NotImplementedException();
}
Task<T> IRepository.GetAsync<T>(params object[] ids)
{
throw new NotImplementedException();
}
public async Task<int> ExecuteCount(IQueryable<Manufacturer> query)
{
return query.Count();
}
}
@@ -0,0 +1,404 @@
using Bogus;
using Bogus.Healthcare;
using Silk_Road_Api.DatabaseContext;
using Silk_Road_Api.Models;
namespace Silk_Road_Api.Repositories;
public class MemoryRepository : IDrugRepository
{
private static readonly List<Drug> _drugs = new List<Drug>{
new Drug{
id =1,
name= "Paracetamol",
price= 5,
stock= 100,
manufacturerId=1,
description= "Paracetamol is a painkiller and can be used to relieve mild to moderate pain. It can also reduce high temperatures (fever).",
sideEffects= "Paracetamol is a very safe medicine when used correctly. Side effects are rare if you take it at the right dosage.",
interactions= "Paracetamol can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose of paracetamol is one or two 500mg tablets at a time. Do not take more than 4 doses in 24 hours.",
contraindications= "Do not take paracetamol if you are allergic to it.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep paracetamol in a cool, dry place. Do not store it above 25C.",
pregnancy= "Paracetamol is safe to take in pregnancy and while breastfeeding, at recommended doses.",
breastfeeding= "Paracetamol is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of paracetamol can cause serious harm. The maximum amount of paracetamol for adults is 1 gram (1000 mg) per dose and 4 grams (4000 mg) per day."
},
new Drug{
id= 2,
name= "Ibuprofen",
price= 10,
stock= 50,
manufacturerId=1,
description= "Ibuprofen is a painkiller available over the counter without a prescription. It\"s one of a group of painkillers called non-steroidal anti-inflammatory drugs (NSAIDs) and can be used to ease mild to moderate pain, such as period pain, toothache, and migraines.",
sideEffects= "The most common side effects of ibuprofen are headaches, dizziness, and drowsiness.",
interactions= "Ibuprofen can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 200mg tablets 3 times a day. Do not take more than 6 tablets (1200mg) in 24 hours.",
contraindications= "Do not take ibuprofen if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep ibuprofen in a cool, dry place. Do not store it above 25C.",
pregnancy= "Ibuprofen is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Ibuprofen is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of ibuprofen can cause serious harm. The maximum amount of ibuprofen for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 3,
name= "Aspirin",
price= 15,
stock= 25,
manufacturerId=1,
description= "Aspirin is a painkiller and anti-inflammatory medicine. It can be used to relieve pain and inflammation caused by many conditions such as headaches, toothache, period pain, and joint pain.",
sideEffects= "The most common side effects of aspirin are indigestion and stomach irritation.",
interactions= "Aspirin can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 300mg tablets 3 or 4 times a day. Do not take more than 12 tablets (3600mg) in 24 hours.",
contraindications= "Do not take aspirin if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep aspirin in a cool, dry place. Do not store it above 25C.",
pregnancy= "Aspirin is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Aspirin is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of aspirin can cause serious harm. The maximum amount of aspirin for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 4,
name= "Codeine",
price= 20,
stock= 10,
manufacturerId=1,
description= "Codeine is a strong painkiller and is part of a group of medicines called opioids. Opioids are derived from the poppy plant, and are known for their pain-relieving properties.",
sideEffects= "The most common side effects of codeine are constipation, feeling sick, and drowsiness.",
interactions= "Codeine can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 30mg tablets 3 or 4 times a day. Do not take more than 12 tablets (360mg) in 24 hours.",
contraindications= "Do not take codeine if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep codeine in a cool, dry place. Do not store it above 25C.",
pregnancy= "Codeine is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Codeine is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of codeine can cause serious harm. The maximum amount of codeine for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 5,
name= "Morphine",
price= 25,
stock= 5,
manufacturerId=1,
description= "Morphine is a strong painkiller and is part of a group of medicines called opioids. Opioids are derived from the poppy plant, and are known for their pain-relieving properties.",
sideEffects= "The most common side effects of morphine are constipation, feeling sick, and drowsiness.",
interactions= "Morphine can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 10mg tablets 3 or 4 times a day. Do not take more than 12 tablets (120mg) in 24 hours.",
contraindications= "Do not take morphine if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep morphine in a cool, dry place. Do not store it above 25C.",
pregnancy= "Morphine is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Morphine is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of morphine can cause serious harm. The maximum amount of morphine for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 6,
name= "Tramadol",
price= 30,
stock= 2,
manufacturerId=1,
description= "Tramadol is a strong painkiller and is part of a group of medicines called opioids. Opioids are derived from the poppy plant, and are known for their pain-relieving properties.",
sideEffects= "The most common side effects of tramadol are constipation, feeling sick, and drowsiness.",
interactions= "Tramadol can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 50mg tablets 3 or 4 times a day. Do not take more than 12 tablets (600mg) in 24 hours.",
contraindications= "Do not take tramadol if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep tramadol in a cool, dry place. Do not store it above 25C.",
pregnancy= "Tramadol is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Tramadol is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of tramadol can cause serious harm. The maximum amount of tramadol for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 7,
name= "Cocodamol",
price= 35,
stock= 1,
manufacturerId=1,
description= "Cocodamol is a strong painkiller and is part of a group of medicines called opioids. Opioids are derived from the poppy plant, and are known for their pain-relieving properties.",
sideEffects= "The most common side effects of cocodamol are constipation, feeling sick, and drowsiness.",
interactions= "Cocodamol can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 30mg tablets 3 or 4 times a day. Do not take more than 12 tablets (360mg) in 24 hours.",
contraindications= "Do not take cocodamol if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep cocodamol in a cool, dry place. Do not store it above 25C.",
pregnancy= "Cocodamol is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Cocodamol is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of cocodamol can cause serious harm. The maximum amount of cocodamol for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 8,
name= "Diclofenac",
price= 40,
stock= 1,
manufacturerId=1,
description= "Diclofenac is a painkiller available over the counter without a prescription. It\"s one of a group of painkillers called non-steroidal anti-inflammatory drugs (NSAIDs) and can be used to ease mild to moderate pain, such as period pain, toothache, and migraines.",
sideEffects= "The most common side effects of diclofenac are headaches, dizziness, and drowsiness.",
interactions= "Diclofenac can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 50mg tablets 3 times a day. Do not take more than 6 tablets (300mg) in 24 hours.",
contraindications= "Do not take diclofenac if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep diclofenac in a cool, dry place. Do not store it above 25C.",
pregnancy= "Diclofenac is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Diclofenac is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of diclofenac can cause serious harm. The maximum amount of diclofenac for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 9,
name= "Naproxen",
price= 45,
stock= 1,
manufacturerId=1,
description= "Naproxen is a painkiller available over the counter without a prescription. It\"s one of a group of painkillers called non-steroidal anti-inflammatory drugs (NSAIDs) and can be used to ease mild to moderate pain, such as period pain, toothache, and migraines.",
sideEffects= "The most common side effects of naproxen are headaches, dizziness, and drowsiness.",
interactions= "Naproxen can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 250mg tablets 3 times a day. Do not take more than 6 tablets (1500mg) in 24 hours.",
contraindications= "Do not take naproxen if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep naproxen in a cool, dry place. Do not store it above 25C.",
pregnancy= "Naproxen is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Naproxen is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of naproxen can cause serious harm. The maximum amount of naproxen for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 10,
name= "Mefenamic Acid",
price= 50,
stock= 1,
manufacturerId=1,
description= "Mefenamic Acid is a painkiller available over the counter without a prescription. It\"s one of a group of painkillers called non-steroidal anti-inflammatory drugs (NSAIDs) and can be used to ease mild to moderate pain, such as period pain, toothache, and migraines.",
sideEffects= "The most common side effects of mefenamic acid are headaches, dizziness, and drowsiness.",
interactions= "Mefenamic acid can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 250mg tablets 3 times a day. Do not take more than 6 tablets (1500mg) in 24 hours.",
contraindications= "Do not take mefenamic acid if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep mefenamic acid in a cool, dry place. Do not store it above 25C.",
pregnancy= "Mefenamic acid is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Mefenamic acid is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of mefenamic acid can cause serious harm. The maximum amount of mefenamic acid for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 11,
name= "Gabapentin",
price= 55,
stock= 1,
manufacturerId=1,
description= "Gabapentin is a medicine used to treat nerve pain, such as epilepsy, and can also be used to treat anxiety.",
sideEffects= "The most common side effects of gabapentin are headaches, dizziness, and drowsiness.",
interactions= "Gabapentin can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 300mg tablets 3 times a day. Do not take more than 6 tablets (1800mg) in 24 hours.",
contraindications= "Do not take gabapentin if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep gabapentin in a cool, dry place. Do not store it above 25C.",
pregnancy= "Gabapentin is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Gabapentin is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of gabapentin can cause serious harm. The maximum amount of gabapentin for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 12,
name= "Pregabalin",
price= 60,
stock= 1,
manufacturerId=1,
description= "Pregabalin is a medicine used to treat nerve pain, such as epilepsy, and can also be used to treat anxiety.",
sideEffects= "The most common side effects of pregabalin are headaches, dizziness, and drowsiness.",
interactions= "Pregabalin can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 300mg tablets 3 times a day. Do not take more than 6 tablets (1800mg) in 24 hours.",
contraindications= "Do not take pregabalin if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep pregabalin in a cool, dry place. Do not store it above 25C.",
pregnancy= "Pregabalin is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Pregabalin is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of pregabalin can cause serious harm. The maximum amount of pregabalin for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 13,
name= "Amitriptyline",
price= 65,
stock= 1,
manufacturerId=1,
description= "Amitriptyline is a medicine used to treat nerve pain, such as epilepsy, and can also be used to treat anxiety.",
sideEffects= "The most common side effects of amitriptyline are headaches, dizziness, and drowsiness.",
interactions= "Amitriptyline can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 300mg tablets 3 times a day. Do not take more than 6 tablets (1800mg) in 24 hours.",
contraindications= "Do not take amitriptyline if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep amitriptyline in a cool, dry place. Do not store it above 25C.",
pregnancy= "Amitriptyline is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Amitriptyline is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of amitriptyline can cause serious harm. The maximum amount of amitriptyline for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 14,
name= "Duloxetine",
price= 70,
stock= 1,
manufacturerId=1,
description= "Duloxetine is a medicine used to treat nerve pain, such as epilepsy, and can also be used to treat anxiety.",
sideEffects= "The most common side effects of duloxetine are headaches, dizziness, and drowsiness.",
interactions= "Duloxetine can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 300mg tablets 3 times a day. Do not take more than 6 tablets (1800mg) in 24 hours.",
contraindications= "Do not take duloxetine if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep duloxetine in a cool, dry place. Do not store it above 25C.",
pregnancy= "Duloxetine is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Duloxetine is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of duloxetine can cause serious harm. The maximum amount of duloxetine for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 15,
name= "Venlafaxine",
price= 75,
stock= 1,
manufacturerId=1,
description= "Venlafaxine is a medicine used to treat nerve pain, such as epilepsy, and can also be used to treat anxiety.",
sideEffects= "The most common side effects of venlafaxine are headaches, dizziness, and drowsiness.",
interactions= "Venlafaxine can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 300mg tablets 3 times a day. Do not take more than 6 tablets (1800mg) in 24 hours.",
contraindications= "Do not take venlafaxine if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep venlafaxine in a cool, dry place. Do not store it above 25C.",
pregnancy= "Venlafaxine is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Venlafaxine is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of venlafaxine can cause serious harm. The maximum amount of venlafaxine for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
new Drug{
id= 16,
name= "Sertraline",
price= 80,
stock= 1,
manufacturerId= 1,
description= "Sertraline is a medicine used to treat nerve pain, such as epilepsy, and can also be used to treat anxiety.",
sideEffects= "The most common side effects of sertraline are headaches, dizziness, and drowsiness.",
interactions= "Sertraline can be taken with other medicines, including prescription medicines such as antibiotics.",
dosage= "The usual dose for adults is one or two 300mg tablets 3 times a day. Do not take more than 6 tablets (1800mg) in 24 hours.",
contraindications= "Do not take sertraline if you have a stomach ulcer, or have had one in the past.",
warnings= "Do not take more than the recommended dose.",
storage= "Keep sertraline in a cool, dry place. Do not store it above 25C.",
pregnancy= "Sertraline is not recommended in pregnancy, especially in the third trimester.",
breastfeeding= "Sertraline is safe to take while breastfeeding, at recommended doses.",
overdose= "An overdose of sertraline can cause serious harm. The maximum amount of sertraline for adults is 1 gram (1000 mg) per dose and 3 grams (3000 mg) per day."
},
};
private static readonly List<string> prefixes = ["Neuro", "Bio", "Cyber", "Synth", "Nano", "Micro", "Hyper", "Psycho"];
private static readonly List<string> roots = ["zym", "plex", "morp", "cyto", "gen", "nerv", "neuro", "bio", "pharm", "morph"];
private static readonly List<string> suffixes = ["x", "z", "on", "ex", "ol", "ine", "ium", "ane", "ide", "os"];
public MemoryRepository()
{
// _drugs.Clear();
// GenerateDrugs();
}
public new async Task AddAsync<T>(T entity)
{
(entity as Drug).id = _drugs.Max(d => d.id) + 1;
_drugs.Add(entity as Drug);
}
public new void Update<T>(T entity) where T : class
{
var drug = entity as Drug;
var existingDrug = _drugs.FirstOrDefault(d => d.id == drug.id);
if (existingDrug != null)
{
existingDrug.name = drug.name;
existingDrug.price = drug.price;
existingDrug.stock = drug.stock;
existingDrug.description = drug.description;
existingDrug.manufacturerId = drug.manufacturerId;
existingDrug.sideEffects = drug.sideEffects;
existingDrug.interactions = drug.interactions;
existingDrug.dosage = drug.dosage;
existingDrug.contraindications = drug.contraindications;
existingDrug.warnings = drug.warnings;
existingDrug.storage = drug.storage;
existingDrug.pregnancy = drug.pregnancy;
existingDrug.breastfeeding = drug.breastfeeding;
existingDrug.overdose = drug.overdose;
return;
}
throw new Exception("Failed to update drug");
}
public new void UpdateRange<T>(List<T> entities) where T : class
{
foreach (var entity in entities)
{
Update(entity);
}
}
public new async Task<bool> SaveChangesAsync()
{
return true;
}
public new async Task<Drug> GetAsync<T>(params object[] ids) where T : class
{
return _drugs.FirstOrDefault(d => d.id == (int)ids.FirstOrDefault());
}
public new IQueryable<T> AsQueryable<T>() where T : class
{
return _drugs.AsQueryable() as IQueryable<T>;
}
public new void Delete<T>(T entity) where T : class
{
if (!_drugs.Remove(entity as Drug))
throw new Exception("Failed to delete drug");
}
public IQueryable<Drug> GetDrugs()
{
return _drugs.AsQueryable();
}
public async Task<Drug> GetDrug(int id)
{
return _drugs.FirstOrDefault(d => d.id == id);
}
public async Task<int> ExecuteCount(IQueryable<Drug> query)
{
return query.Count();
}
Task<T> IRepository.GetAsync<T>(params object[] ids)
{
throw new NotImplementedException();
}
public void GenerateDrugs(int n = 5)
{
var drugs = new Faker<Drug>()
.RuleFor(d => d.id, f => _drugs.Count > 0 ? _drugs.Max(d => d.id) + f.IndexFaker + 1 : f.IndexFaker + 1)
.RuleFor(d => d.name, f => f.PickRandom(prefixes) + f.PickRandom(roots) + f.PickRandom(suffixes))
.RuleFor(d => d.price, f => f.Random.Number(5, 100))
.RuleFor(d => d.stock, f => f.Random.Number(1, 100))
.RuleFor(d => d.manufacturerId, f => f.Random.Number(1, 10))
.RuleFor(d => d.description, f => f.Lorem.Paragraph())
.RuleFor(d => d.sideEffects, f => f.Lorem.Paragraph())
.RuleFor(d => d.interactions, f => f.Lorem.Paragraph())
.RuleFor(d => d.dosage, f => f.Lorem.Paragraph())
.RuleFor(d => d.contraindications, f => f.Lorem.Paragraph())
.RuleFor(d => d.warnings, f => f.Lorem.Paragraph())
.RuleFor(d => d.storage, f => f.Lorem.Paragraph())
.RuleFor(d => d.pregnancy, f => f.Lorem.Paragraph())
.RuleFor(d => d.breastfeeding, f => f.Lorem.Paragraph())
.RuleFor(d => d.overdose, f => f.Lorem.Paragraph())
.Generate(n);
_drugs.AddRange(drugs);
}
public async Task<IQueryable<ChartModel>> GetChartData()
{
return _drugs.GroupBy(d => d.manufacturerId)
.Select(g => new ChartModel
{
ManufacturerId = g.Key,
Count = g.Count()
}).AsQueryable();
}
}
@@ -0,0 +1,58 @@
using Microsoft.EntityFrameworkCore;
using Silk_Road_Api.DatabaseContext;
namespace Silk_Road_Api.Repositories;
public class Repository : RepositoryBase, IRepository
{
public Repository(SilkRoadApiContext context) : base(context)
{
}
public async Task AddAsync<T>(T entity)
{
await _context.AddAsync(entity);
}
public void Update<T>(T entity) where T : class
{
var trackedEntity = _context.Entry(entity);
trackedEntity.State = EntityState.Modified;
_context.Update(entity);
}
public void UpdateRange<T>(List<T> entities) where T : class
{
_context.UpdateRange(entities);
}
public async Task<bool> SaveChangesAsync()
{
var saved = false;
int numberOfRetries = 0;
do
{
try
{
await _context.SaveChangesAsync();
saved = true;
}
catch (DbUpdateConcurrencyException ex)
{
foreach (var entry in ex.Entries)
{
await entry.ReloadAsync();
}
numberOfRetries++;
}
}
while (!saved && numberOfRetries < 3);
return saved;
}
public void Delete<T>(T entity) where T : class
{
_context.Remove(entity);
}
}
@@ -0,0 +1,23 @@
using Silk_Road_Api.DatabaseContext;
namespace Silk_Road_Api.Repositories;
public class RepositoryBase : IRepositoryBase
{
protected readonly SilkRoadApiContext _context;
public RepositoryBase(SilkRoadApiContext context)
{
_context = context;
}
public async Task<T> GetAsync<T>(params object[] ids) where T : class
{
return await _context.FindAsync<T>(ids);
}
public IQueryable<T> AsQueryable<T>() where T : class
{
return _context.Set<T>().AsQueryable();
}
}
@@ -0,0 +1,20 @@
using Silk_Road_Api.DatabaseContext;
using Silk_Road_Api.Models;
namespace Silk_Road_Api.Repositories
{
public class UserRepository : Repository, IUserRepository
{
public UserRepository(SilkRoadApiContext context) : base(context) { }
public User? GetUserByUsername(string username)
{
return _context.Users.Where(u => u.username.Equals(username)).FirstOrDefault();
}
public User? GetUserByUsernameAndPassword(string username, string password)
{
return _context.Users.Where(u => u.username.Equals(username) && u.password.Equals(password)).FirstOrDefault(); }
}
}
@@ -0,0 +1,183 @@
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Tls;
using Silk_Road_Api.Extensions;
using Silk_Road_Api.Models;
using Silk_Road_Api.Repositories;
using Silk_Road_Api.Utils;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Services;
public class DrugService : IDrugService
{
private readonly IDrugRepository _drugRepository;
private readonly IManufacturerRepository _manufacturerRepository;
private readonly IMapper _mapper;
public DrugService(IDrugRepository drugRepository, IManufacturerRepository manufacturerRepository, IMapper mapper)
{
_drugRepository = drugRepository;
_manufacturerRepository = manufacturerRepository;
_mapper = mapper;
}
public async Task<DrugViewModel> GetDrug(ControllerBase controller, int id)
{
var user = controller.HttpContext.Session.Get<User>("user");
if(user == null)
{
throw new Exception("User not logged in");
}
var drug = await _drugRepository.GetDrug(id);
if (drug == null)
throw new Exception("Drug not found");
if (user.id != Constants.Admin && drug.manufacturerId != user.companyid)
throw new Exception("Drug does not belong to user");
var manufacturer = await _manufacturerRepository.GetManufacturer(drug.manufacturerId);
if (manufacturer == null)
throw new Exception("Manufacturer not found");
var viewModel = _mapper.Map<DrugViewModel>(drug);
viewModel.manufacturer = manufacturer.name;
return viewModel;
}
public async Task<SearchOutput<DrugViewModel>> GetDrugs(ControllerBase controller, SearchInput input)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null)
{
throw new Exception("User not logged in");
}
var output = new SearchOutput<DrugViewModel>
{
Page = input.Page,
PageSize = input.PageSize
};
var manufacturer = _manufacturerRepository.GetManufacturers();
if (user.id != Constants.Admin)
{
manufacturer = manufacturer.Where(m => m.id == user.companyid);
}
var drugs = _drugRepository.GetDrugs();
var drugViewModels = drugs.Join(manufacturer, d => d.manufacturerId, m => m.id, (d, m) => new DrugViewModel
{
id = d.id,
name = d.name,
price = d.price,
stock = d.stock,
manufacturer = m.name,
description = d.description,
sideEffects = d.sideEffects,
interactions = d.interactions,
dosage = d.dosage,
contraindications = d.contraindications,
warnings = d.warnings,
storage = d.storage,
pregnancy = d.pregnancy,
breastfeeding = d.breastfeeding,
overdose = d.overdose
});
output.Total = await _drugRepository.ExecuteCount(drugs);
drugViewModels = input.Sorting switch
{
"name" => drugViewModels.OrderBy(d => d.name),
"price" => drugViewModels.OrderBy(d => d.price),
"manufacturer" => drugViewModels.OrderBy(d => d.manufacturer),
"name_desc" => drugViewModels.OrderByDescending(d => d.name),
"price_desc" => drugViewModels.OrderByDescending(d => d.price),
"manufacturer_desc" => drugViewModels.OrderByDescending(d => d.manufacturer),
_ => drugViewModels.OrderBy(d => d.id),
};
drugViewModels = drugViewModels.Skip(input.PageSize * (input.Page - 1)).Take(input.PageSize);
output.Items = drugViewModels.ToList();
return output;
}
public async Task<bool> AddDrug(ControllerBase controller, DrugViewModel drugViewModel)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null)
{
return false;
}
try
{
var manufacturerId = await _manufacturerRepository.GetManufacturerByName(drugViewModel.manufacturer);
if (manufacturerId == 0)
throw new Exception("Manufacturer not found");
if (user.id != Constants.Admin && user.companyid != manufacturerId)
throw new Exception("Illegal operation");
var drug = _mapper.Map<Drug>(drugViewModel);
drug.manufacturerId = manufacturerId;
await _drugRepository.AddAsync(drug);
return await _drugRepository.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
}
public async Task<bool> UpdateDrug(ControllerBase controller, DrugViewModel drugViewModel)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null)
{
return false;
}
try
{
var manufacturerId = await _manufacturerRepository.GetManufacturerByName(drugViewModel.manufacturer);
if (manufacturerId == 0)
throw new Exception("Manufacturer not found");
if (user.id != Constants.Admin && user.companyid != manufacturerId)
throw new Exception("Illegal operation");
var drug = _mapper.Map<Drug>(drugViewModel);
drug.manufacturerId = manufacturerId;
_drugRepository.Update(drug);
return await _drugRepository.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
}
public async Task<bool> DeleteDrug(ControllerBase controller, int id)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null)
{
return false;
}
try
{
var drug = await _drugRepository.GetDrug(id);
if (user.id != Constants.Admin && user.companyid != drug.manufacturerId)
throw new Exception("Illegal operation");
_drugRepository.Delete(drug);
return await _drugRepository.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
}
public void GenerateDrugs()
{
_drugRepository.GenerateDrugs();
}
public async Task<List<ChartViewModel>> GetChartData()
{
return (await _drugRepository.GetChartData()).Join(_manufacturerRepository.GetManufacturers(), d => d.ManufacturerId, m => m.id, (d, m) => new ChartViewModel
{
Manufacturer = m.name,
Count = d.Count
}).ToList();
}
}
@@ -0,0 +1,17 @@
using Microsoft.AspNetCore.Mvc;
using Silk_Road_Api.Models;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Services;
public interface IDrugService
{
public Task<DrugViewModel> GetDrug(ControllerBase controller, int id);
public Task<SearchOutput<DrugViewModel>> GetDrugs(ControllerBase controller, SearchInput input);
public Task<bool> AddDrug(ControllerBase controller, DrugViewModel drugViewModel);
public Task<bool> UpdateDrug(ControllerBase controller, DrugViewModel drugViewModel);
public Task<bool> DeleteDrug(ControllerBase controller, int id);
public void GenerateDrugs();
public Task<List<ChartViewModel>> GetChartData();
}
@@ -0,0 +1,16 @@
using Microsoft.AspNetCore.Mvc;
using Silk_Road_Api.Models;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Services;
public interface IManufacturerService
{
public Task<ManufacturerViewModel> GetManufacturer(ControllerBase controller, int id);
public Task<SearchOutput<ManufacturerViewModel>> GetManufacturers(ControllerBase controller, SearchInput input);
public Task<bool> AddManufacturer(ControllerBase controller, ManufacturerViewModel manufacturerViewModel);
public Task<bool> UpdateManufacturer(ControllerBase controller, ManufacturerViewModel manufacturerViewModel);
public Task<bool> DeleteManufacturer(ControllerBase controller, int id);
public void GenerateManufacturer();
}
@@ -0,0 +1,11 @@
using Silk_Road_Api.Models;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Services
{
public interface IUserService
{
public Task RegisterUser(RegistrationViewModel user);
public User LoginUser(string username, string password);
}
}
@@ -0,0 +1,133 @@
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Silk_Road_Api.Extensions;
using Silk_Road_Api.Models;
using Silk_Road_Api.Repositories;
using Silk_Road_Api.Utils;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Services;
public class ManufacturerService : IManufacturerService
{
private readonly IManufacturerRepository _manufacturerRepository;
private readonly IDrugRepository _drugRepository;
private readonly IMapper _mapper;
public ManufacturerService(IDrugRepository drugRepository, IManufacturerRepository manufacturerRepository, IMapper mapper)
{
_drugRepository = drugRepository;
_manufacturerRepository = manufacturerRepository;
_mapper = mapper;
}
public async Task<bool> AddManufacturer(ControllerBase controller, ManufacturerViewModel manufacturerViewModel)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null || user.id != Constants.Admin)
{
throw new Exception("Unauthorized");
}
try
{
var manufacturer = _mapper.Map<Manufacturer>(manufacturerViewModel);
await _manufacturerRepository.AddAsync(manufacturer);
return await _manufacturerRepository.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
}
public async Task<bool> DeleteManufacturer(ControllerBase controller, int id)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null || user.id != Constants.Admin)
{
throw new Exception("Unauthorized");
}
try
{
var manufacturer = await _manufacturerRepository.GetManufacturer(id);
_manufacturerRepository.Delete(manufacturer);
return await _manufacturerRepository.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
}
public void GenerateManufacturer()
{
_manufacturerRepository.GenerateManufacturers();
}
public async Task<ManufacturerViewModel> GetManufacturer(ControllerBase controller, int id)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null || user.id != Constants.Admin)
{
throw new Exception("Unauthorized");
}
var manufacturer = await _manufacturerRepository.GetManufacturer(id);
if (manufacturer == null)
throw new Exception("Manufacturer not found");
var viewModel = _mapper.Map<ManufacturerViewModel>(manufacturer);
viewModel.totalCount = _drugRepository.GetDrugs().Where(d => d.manufacturerId == id)?.Count() ?? 0;
return viewModel;
}
public async Task<SearchOutput<ManufacturerViewModel>> GetManufacturers(ControllerBase controller, SearchInput input)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null || user.id != Constants.Admin)
{
throw new Exception("Unauthorized");
}
var output = new SearchOutput<ManufacturerViewModel>
{
Page = input.Page,
PageSize = input.PageSize
};
var drugs = _drugRepository.GetDrugs();
var viewModel = _manufacturerRepository.GetManufacturers().GroupJoin(drugs, m => m.id, d => d.manufacturerId, (m, d) => new
{
manufacturer = m,
drugs = d.Count()
}).Select(
x => new ManufacturerViewModel
{
id = x.manufacturer.id,
name = x.manufacturer.name,
address = x.manufacturer.address,
contact = x.manufacturer.contact,
totalCount = x.drugs
}
);
output.Total = viewModel.Count();
viewModel = viewModel.Skip(input.PageSize * (input.Page - 1)).Take(input.PageSize);
output.Items = viewModel.ToList();
return output;
}
public async Task<bool> UpdateManufacturer(ControllerBase controller, ManufacturerViewModel manufacturerViewModel)
{
var user = controller.HttpContext.Session.Get<User>("user");
if (user == null || user.id != Constants.Admin)
{
throw new Exception("Unauthorized");
}
try
{
var manufacturer = _mapper.Map<Manufacturer>(manufacturerViewModel);
_manufacturerRepository.Update(manufacturer);
return await _manufacturerRepository.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
}
}
@@ -0,0 +1,51 @@
using AutoMapper;
using Silk_Road_Api.Models;
using Silk_Road_Api.Repositories;
using Silk_Road_Api.Repositories;
using Silk_Road_Api.ViewModels;
namespace Silk_Road_Api.Services
{
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
private readonly IManufacturerRepository _manufacturerRepository;
private readonly IMapper _mapper;
public UserService(IUserRepository userRepository, IManufacturerRepository manufacturerRepository, IMapper mapper) {
_userRepository = userRepository;
_manufacturerRepository = manufacturerRepository;
_mapper = mapper;
}
public User? LoginUser(string username, string password)
{
var user = _userRepository.GetUserByUsernameAndPassword(username, password);
if (user == null)
{
throw new Exception("Username and password don't match");
}
return user;
}
public async Task RegisterUser(RegistrationViewModel user)
{
var dbUser = _userRepository.GetUserByUsername(user.username);
if (dbUser != null)
{
throw new Exception("Username already taken");
}
var company = await _manufacturerRepository.GetManufacturerByName(user.name);
if (company != 0)
{
throw new Exception("Company already has an account associated, please contact support");
}
var userToBeAdded = _mapper.Map<User>(user);
var companyToBeAdded = _mapper.Map<Manufacturer>(user);
await _manufacturerRepository.AddAsync(companyToBeAdded);
await _manufacturerRepository.SaveChangesAsync();
userToBeAdded.companyid = await _manufacturerRepository.GetManufacturerByName(user.name);
await _userRepository.AddAsync(userToBeAdded);
await _userRepository.SaveChangesAsync();
}
}
}
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Silk_Road_Api</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Bogus.Healthcare" Version="35.5.0" />
<PackageReference Include="Faker.Net" Version="2.0.163" />
<PackageReference Include="Microsoft.AspNetCore.Components" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.3" />
<PackageReference Include="MySql.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,6 @@
@Silk_Road_Api_HostAddress = http://localhost:5176
GET {{Silk_Road_Api_HostAddress}}/weatherforecast/
Accept: application/json
###
@@ -0,0 +1,7 @@
namespace Silk_Road_Api.Utils
{
public static class Constants
{
public const int Admin = 1234;
}
}
@@ -0,0 +1,7 @@
namespace Silk_Road_Api.ViewModels;
public class ChartViewModel
{
public string Manufacturer { get; set; }
public int Count { get; set; }
}
@@ -0,0 +1,36 @@
using System.ComponentModel.DataAnnotations;
namespace Silk_Road_Api.ViewModels;
public class DrugViewModel
{
public int id { get; set; } = 0;
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string name { get; set; }
[Range(0, 999.99)]
public decimal price { get; set; }
[Range(0, 20000)]
public int stock { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string description { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string manufacturer { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string sideEffects { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string interactions { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string dosage { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string contraindications { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string warnings { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string storage { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string pregnancy { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string breastfeeding { get; set; }
[RegularExpression(@"^[a-zA-Z''-'\s]{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string overdose { get; set; }
}
@@ -0,0 +1,8 @@
namespace Silk_Road_Api.ViewModels
{
public class LoginViewModel
{
public required string username { get; set; }
public required string password { get; set; }
}
}
@@ -0,0 +1,15 @@
using System.ComponentModel.DataAnnotations;
namespace Silk_Road_Api.ViewModels;
public class ManufacturerViewModel
{
public int id { get; set; } = 0;
[RegularExpression(@".{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string name { get; set; }
[RegularExpression(@".{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string address { get; set; }
[RegularExpression(@".{3,40}$", ErrorMessage = "Characters are not allowed.")]
public string contact { get; set; }
public int totalCount { get; set; } = 0;
}
@@ -0,0 +1,15 @@
namespace Silk_Road_Api.ViewModels
{
public class RegistrationViewModel
{
public required string name { get; set; }
public required string address { get; set; }
public required string contact { get; set; }
public required string firstname { get; set; }
public required string lastname { get; set; }
public required string username { get; set; }
public required string email { get; set; }
public required string password { get; set; }
}
}
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
@@ -0,0 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SilkRoadApiContext": "Server=tcp:silksongdb.database.windows.net,1433;Initial Catalog=SilkRoadDb;Persist Security Info=False;User ID=silksongdb;Password=Ni7BN6stuSTChkU;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
}