Add in the middle ware and Fallbackcontroller.

This commit is contained in:
Kham
2021-08-30 17:02:26 +10:00
parent 8bdf6dabdc
commit c5ab17115d
8 changed files with 183 additions and 79 deletions
@@ -25,7 +25,9 @@ namespace CarParkValidationAPI.Authorization
if (userId != null)
{
// attach user to context on successful jwt validation
context.Items["User"] = userService.GetById(userId.Value);
//here to put in the real user
//TODO if you want to add information for User
// context.Items["User"] = userService.GetById(userId.Value);
}
await _next(context);
@@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
namespace CarParkValidationAPI.Controllers
{
public class FallbackController : Controller
{
public IActionResult Index()
{
return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot", "index.html"), "text/HTML");
}
}
}
+60 -22
View File
@@ -17,8 +17,7 @@ namespace CarParkValidationAPI.Datas
public DbSet<User> Users { get; set; }
public DbSet<AdminUser> AdminUsers { get; set; }
public DbSet<ValidationPoint> Validations { get; set; }
public DbSet<ConcessionValidation> ConcessionValidations { get; set; }
public DbSet<ConcessionValidation> ConcessionValidations { get; set; }
public DbSet<ConcessionType> ConcessionTypes { get; set; }
private readonly IConfiguration Configuration;
private IOptions<AppSettings> _appSettings;
@@ -31,18 +30,15 @@ namespace CarParkValidationAPI.Datas
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ValidationPoint>().ToTable("ValidationPoint");
modelBuilder.Entity<ConcessionValidation>().ToTable("ConcessionValidation");
modelBuilder.Entity<ConcessionValidation>().ToTable("ConcessionValidation");
modelBuilder.Entity<ConcessionType>().ToTable("ConcessionType");
modelBuilder.Entity<AdminUser>().ToTable("AdminUser");
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// in memory database used for simplicity, change to a real db for production applications
// options.UseInMemoryDatabase("TestDb");
options.UseSqlServer(_appSettings.Value.SQLConnectionString);
}
@@ -52,7 +48,7 @@ namespace CarParkValidationAPI.Datas
object myobj;
myobj = reader["ValidationID"];
if (myobj != System.DBNull.Value)
item.Id = (int)myobj;
item.Id = (int) myobj;
myobj = reader["ValidateDate"];
if (myobj != System.DBNull.Value)
@@ -60,15 +56,15 @@ namespace CarParkValidationAPI.Datas
myobj = reader["ConcessionCard"];
if (myobj != System.DBNull.Value)
item.ConcessionCard = (string)myobj;
item.ConcessionCard = (string) myobj;
myobj = reader["ConcessionHolder"];
if (myobj != System.DBNull.Value)
item.ConcessionHolder = (string)myobj;
item.ConcessionHolder = (string) myobj;
myobj = reader["ConcessionExpiry"];
if (myobj != System.DBNull.Value)
item.ConcessionExpiry = (bool)myobj;
item.ConcessionExpiry = (bool) myobj;
/*
myobj = reader["ConcessionTypeID"];
if (myobj != System.DBNull.Value)
@@ -80,23 +76,22 @@ namespace CarParkValidationAPI.Datas
myobj = reader["ConcessionType"];
if (myobj != System.DBNull.Value)
item.ConcessionType = (string)myobj;
item.ConcessionType = (string) myobj;
myobj = reader["ValidationPoint"];
if (myobj != System.DBNull.Value)
item.ValidationPoint = (string)myobj;
item.ValidationPoint = (string) myobj;
myobj = reader["StaffFirstName"];
if (myobj != System.DBNull.Value)
item.StaffFirstName = (string)myobj;
item.StaffFirstName = (string) myobj;
myobj = reader["StaffLastName"];
if (myobj != System.DBNull.Value)
item.StaffLastName = (string)myobj;
item.StaffLastName = (string) myobj;
myobj = reader["StaffEmail"];
if (myobj != System.DBNull.Value)
item.StaffEmail = (string)myobj;
item.StaffEmail = (string) myobj;
/*
myobj = reader["ValidationPointID"];
if (myobj != System.DBNull.Value)
@@ -145,11 +140,58 @@ namespace CarParkValidationAPI.Datas
}
}
}
return result;
}
public async Task<List<int>> SelectCheckConcessionValidationAsync(DateTime fromDate, string concessionCard, string staffLinkNo)
{
var pfromDate = new SqlParameter
{
ParameterName = "FromDate",
Value = fromDate.Date,
};
var pStaffLink = new SqlParameter
{
ParameterName = "StaffLinkNo",
Value = staffLinkNo,
};
var pConcessionCard = new SqlParameter
{
ParameterName = "ConcessionCard",
Value = concessionCard,
};
ConcessionValidationExtDto item;
List<int> result = new List<int>();
object myobj;
int id;
using (var command = this.Database.GetDbConnection().CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = ("capv_CheckConValidation_Sel");
command.Parameters.Add(pfromDate);
command.Parameters.Add(pStaffLink);
command.Parameters.Add(pConcessionCard);
this.Database.OpenConnection();
using (DbDataReader reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
myobj = reader["ValidationID"];
if (myobj != System.DBNull.Value)
{
id = (int)myobj;
result.Add(id);
}
}
}
}
return result;
}
public async Task<List<ConcessionValidationExtDto>> SelectConcessionValidationByDate(bool activeOnly, DateTime fromDate, DateTime toDate)
{
var pfromDate = new SqlParameter
@@ -157,8 +199,6 @@ namespace CarParkValidationAPI.Datas
ParameterName = "fromDate",
Value = fromDate.Date
};
var pToDate = new SqlParameter
{
ParameterName = "toDate",
@@ -183,9 +223,7 @@ namespace CarParkValidationAPI.Datas
}
}
}
return result;
}
}
}
@@ -61,8 +61,8 @@ namespace CarParkValidationAPI.Repository
sl.SetCellValue(row, col++, "ConcessionType");
sl.SetCellValue(row, col++, "Validation Piont");
sl.SetCellValue(row, col++, "StaffLink No");
sl.SetCellValue(row, col++, "Staff first name");
sl.SetCellValue(row, col++, "Staff last name");
sl.SetCellValue(row, col++, "Staff First name");
sl.SetCellValue(row, col++, "Staff Last name");
sl.SetCellValue(row, col++, "Staff Email");
sl.FreezePanes(row, col - 1); //frozen the row.
//wrap text on is concession Expiry
@@ -156,9 +156,45 @@ namespace CarParkValidationAPI.Repository
StatusCode = statuscode,
Message = error
};
}
}
public async Task<ResultModel<int>> CheckConcessionValidationStaffLinkNoAsync(string staffLinkNo, string concessionCard, DateTime currentDate)
public async Task<ResultModel<int>> CheckConcessionValidationStaffLinkNoAsync(string staffLinkNo, string concessionCard, DateTime currentDate)
{
int statuscode = 1;
int result = 1;
string message = "warning you already add concession card on this date!";
try
{
var anyRecord = await _context.SelectCheckConcessionValidationAsync(currentDate.ToLocalTime().Date, concessionCard, staffLinkNo);
if (anyRecord.Count > 0)
{
result = -1;
}
else
{
result = 1; //test
message = "test OK just one time";
}
statuscode = 1;
}
catch (Exception ex)
{
message = "Error " + ex.ToString();
statuscode = 0;
result = 0;
}
return new ResultModel<int>()
{
Data = result,
StatusCode = statuscode,
Message = message,
};
}
public async Task<ResultModel<int>> CheckConcessionValidationStaffLinkNoAsync_old(string staffLinkNo, string concessionCard, DateTime currentDate)
{
int statuscode = 1;
int result = 1;
+58 -50
View File
@@ -23,14 +23,14 @@ using System.Threading.Tasks;
namespace CarParkValidationAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
public class Startup
{
Configuration = configuration;
}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
@@ -38,8 +38,8 @@ namespace CarParkValidationAPI
services.AddControllers();
//** security
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
//***
@@ -67,12 +67,12 @@ namespace CarParkValidationAPI
//**
//publish need to take comment out
services.AddSwaggerGen(c =>
{
// c.ResolveConflictingActions(api => api.First());
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CarParkValidationAPI", Version = "v1" });
});
services.AddSwaggerGen(c =>
{
// c.ResolveConflictingActions(api => api.First());
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CarParkValidationAPI", Version = "v1" });
});
/*
services.AddSwaggerGen(option =>
{
@@ -94,48 +94,56 @@ namespace CarParkValidationAPI
services.AddScoped(typeof(ConcessionValidationReportRepository));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext context)
{
c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CarParkValidationAPI v1");
});
app.UseRouting();
// global cors policy
app.UseCors(x => x
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Content-Disposition")
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
.AllowCredentials());
}
// global error handler
//app.UseMiddleware<ErrorHandlerMiddleware>();
app.UseSwagger();
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.UseSwaggerUI(c =>
{
c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CarParkValidationAPI v1");
});
app.UseAuthorization();
app.UseRouting();
// global cors policy
app.UseCors(x => x
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Content-Disposition")
.AllowCredentials());
// global error handler
//app.UseMiddleware<ErrorHandlerMiddleware>();
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.UseAuthorization();
/* if add angular under wwwroot then two line below needed*/
/***************************/
// app.UseDefaultFiles(); //it will use index.html <------------------
// app.UseStaticFiles(); //it for angular <-------------------------
/***************************/
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// endpoints.MapFallbackToController("Index", "Fallback"); //<------------------ put angular in wwwroot.
});
}
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
@@ -1,7 +1,7 @@
{
"AppSettings": {
"Secret": "Nepean Blue Mountain Super Secret SIGN AND VERIFY JWT TOKENS, BEARER TOKEN USE WHEN CALLING THIS API.",
"SQLConnectionString": "Server=NEPHICT-040931L;Initial Catalog=CarParkValidation;Persist Security Info=False;User ID=bids_admin;Password=Password4BI;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;",
"SQLConnectionString": "Server=NEPHMDB-SQL007;Initial Catalog=CarParkValidation;Persist Security Info=False;User ID=bids_admin;Password=Password4BI;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;",
"LDAPPath": "LDAP://ldap.nswhealth.net:389/OU=Accounts,DC=nswhealth,DC=net",
"LDAPUser": "SRV-NBMS-BIDSPMS",
"LDAPPassword": "42Ytp2AE3nN16eBoyia86UZH6",
@@ -17,7 +17,8 @@
},
"AllowedHosts": "*"
}
/*Positive~1
/*
"SQLConnectionString": "Server=NEPHICT-040931L;Initial Catalog=CarParkValidation;Persist Security Info=False;User ID=bids_admin;Password=Password4BI;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;",
user id=bids_admin;password=Password4BI;
Server=tcp:10.60.207.82,1433;
*/
+1
View File
@@ -1,6 +1,7 @@
{
"AppSettings": {
"Secret": "Nepean Blue Mountain Super Secret SIGN AND VERIFY JWT TOKENS, BEARER TOKEN USE WHEN CALLING THIS API.",
"SQLConnectionString": "Server=NEPHMDB-SQL007;Initial Catalog=CarParkValidation;Persist Security Info=False;User ID=bids_admin;Password=Password4BI;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;",
"LDAPPath": "LDAP://ldap.nswhealth.net:389/OU=Accounts,DC=nswhealth,DC=net",
"LDAPUser": "SRV-NBMS-BIDSPMS",
"LDAPPassword": "42Ytp2AE3nN16eBoyia86UZH6",