Skip to content

Commit

Permalink
Merge pull request #23 from neozhu/dev
Browse files Browse the repository at this point in the history
WIP: refactor BadRequest code
  • Loading branch information
neozhu authored Sep 14, 2021
2 parents a41c82d + 32eda8f commit 8edd170
Show file tree
Hide file tree
Showing 9 changed files with 59 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public ApplicationClaimsIdentityFactory(UserManager<ApplicationUser> userManager
_userManager = userManager;
_roleManager = roleManager;
}
public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
public override async Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);

Expand Down
7 changes: 5 additions & 2 deletions src/Infrastructure/Services/DomainEventService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using CleanArchitecture.Razor.Application.Common.Interfaces;
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using CleanArchitecture.Razor.Application.Common.Interfaces;
using CleanArchitecture.Razor.Application.Common.Models;
using CleanArchitecture.Razor.Domain.Common;
using MediatR;
Expand Down Expand Up @@ -31,4 +34,4 @@ private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent doma
typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent);
}
}
}
}
11 changes: 5 additions & 6 deletions src/Infrastructure/Services/UploadService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ public async Task<string> UploadAsync(UploadRequest request)
var folder = request.UploadType.ToDescriptionString();
var folderName = Path.Combine("Files", folder);
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
bool exists = System.IO.Directory.Exists(pathToSave);
if (!exists)
System.IO.Directory.CreateDirectory(pathToSave);
bool exists = Directory.Exists(pathToSave);
if (!exists) Directory.CreateDirectory(pathToSave);
var fileName = request.FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
Expand All @@ -43,7 +42,7 @@ public async Task<string> UploadAsync(UploadRequest request)
}
}

private static string numberPattern = " ({0})";
private static string _numberPattern = " ({0})";

public static string NextAvailableFilename(string path)
{
Expand All @@ -53,10 +52,10 @@ public static string NextAvailableFilename(string path)

// If path has extension then insert the number pattern just before the extension and return next filename
if (Path.HasExtension(path))
return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), numberPattern));
return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), _numberPattern));

// Otherwise just append the pattern to the path and return next filename
return GetNextFilename(path + numberPattern);
return GetNextFilename(path + _numberPattern);
}

private static string GetNextFilename(string pattern)
Expand Down
17 changes: 12 additions & 5 deletions src/SmartAdmin.WebUI/Areas/Authorization/Pages/Roles.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,9 @@ public async Task<IActionResult> OnPostAsync()
}

}
catch (Exception ex)
catch (Exception e)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return new JsonResult(ex.Message);
return BadRequest(Result.Failure(new string[] { e.Message }));
}
}
public async Task<IActionResult> OnGetDataAsync(int page = 1, int rows = 15, string sort = "Name", string order = "asc", string filterRules = "")
Expand All @@ -128,6 +127,10 @@ public async Task<IActionResult> OnGetDataAsync(int page = 1, int rows = 15, str
public async Task<IActionResult> OnGetDeleteAsync(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role.Name == "Admin")
{
return BadRequest(Result.Failure(new string[] { "Please do not delete the default role." }));
}
var result = await _roleManager.DeleteAsync(role);
return new JsonResult(result.ToApplicationResult());
}
Expand All @@ -136,6 +139,10 @@ public async Task<IActionResult> OnGetDeleteCheckedAsync([FromQuery] string[] id
foreach (var key in id)
{
var role = await _roleManager.FindByIdAsync(key);
if (role.Name == "Admin")
{
return BadRequest(Result.Failure(new string[] { "Please do not delete the default role." }));
}
var result = await _roleManager.DeleteAsync(role);
}
return new JsonResult(Result.Success());
Expand Down Expand Up @@ -189,7 +196,7 @@ public async Task<IActionResult> OnPostImportAsync()
var iresult = await _roleManager.CreateAsync(role);
if (iresult.Succeeded == false)
{
return new JsonResult(Result.FailureAsync(iresult.Errors.Select(x => x.Description)));
return BadRequest(Result.FailureAsync(iresult.Errors.Select(x => x.Description)));
}
}
}
Expand All @@ -198,7 +205,7 @@ public async Task<IActionResult> OnPostImportAsync()
}
catch (Exception e)
{
return new JsonResult(Result.Failure(new string[] { e.Message }));
return BadRequest(Result.Failure(new string[] { e.Message }));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@
reload();
})
.catch((error) => {
var msg = error.response.data;
var msg = error.response.data.Errors.join();
bootbox.alert({
size: "small",
title: "@_localizer["Error"]",
Expand Down
21 changes: 15 additions & 6 deletions src/SmartAdmin.WebUI/Areas/Authorization/Pages/Users.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ public async Task<IActionResult> OnGetUnlockAsync(string id)
public async Task<IActionResult> OnGetDeleteAsync(string id)
{
var user = await _userManager.FindByIdAsync(id);
if (user.UserName == "administrator")
{
return BadRequest(Result.Failure(new string[] { "Please do not delete the default user." }));
}
var result = await _userManager.DeleteAsync(user);
return new JsonResult(result.ToApplicationResult());
}
Expand All @@ -140,6 +144,10 @@ public async Task<IActionResult> OnGetDeleteCheckedAsync([FromQuery] string[] id
foreach(var key in id)
{
var user = await _userManager.FindByIdAsync(key);
if (user.UserName == "administrator")
{
return BadRequest(Result.Failure(new string[] { "Please do not delete the default user." }));
}
var result = await _userManager.DeleteAsync(user);
}
return new JsonResult(Result.Success());
Expand Down Expand Up @@ -192,7 +200,7 @@ public async Task<IActionResult> OnPostImportAsync()
if (result.Succeeded)
{
var importItems = result.Data;
foreach(var item in importItems)
foreach (var item in importItems)
{
var user = new ApplicationUser
{
Expand All @@ -204,21 +212,22 @@ public async Task<IActionResult> OnPostImportAsync()
Email = item.Email,
PhoneNumber = item.PhoneNumber
};
if((await _userManager.FindByNameAsync(user.UserName)) is null)
if ((await _userManager.FindByNameAsync(user.UserName)) is null)
{
var iresult = await _userManager.CreateAsync(user, item.Password);
if (iresult.Succeeded == false)
{
return new JsonResult(Result.FailureAsync(iresult.Errors.Select(x => x.Description)));
return BadRequest(Result.FailureAsync(iresult.Errors.Select(x => x.Description)));
}
}

}
}
return new JsonResult(Result.Success());
}catch(Exception e)
}
catch (Exception e)
{
return new JsonResult(Result.Failure(new string[]{ e.Message}));
return BadRequest(Result.Failure(new string[] { e.Message }));
}
}

Expand Down
14 changes: 7 additions & 7 deletions src/SmartAdmin.WebUI/Pages/Customers/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@
</div>
@await Component.InvokeAsync("ImportExcel", new { importUri = Url.Page("/Customers/Index") + "?handler=Import",
getTemplateUri = @Url.Page("/Customers/Index") + "?handler=CreateTemplate",
onImportedSucceeded = "reload()" })
onImportedSucceeded = "reloadData()" })
@section ScriptsBlock {
<partial name="_ValidationScriptsPartial" />

Expand All @@ -205,7 +205,7 @@

<script type="text/javascript">
$('#searchbutton').click(function () {
reload();
reloadData();
});
$('#addbutton').click(function () {
popupmodal(null);
Expand All @@ -232,9 +232,9 @@
axios.post('@Url.Page("/Customers/Index")', request).then(res => {
toastr["info"]('@_localizer["Save Success"]');
$('#customer_modal').modal('toggle');
reload();
reloadData();
}).catch((error) => {
var msg = error.response.data;
var msg = error.response.data.Errors.join();
bootbox.alert({
size: "small",
title: "@_localizer["Error"]",
Expand Down Expand Up @@ -321,7 +321,7 @@
}
var reload = () => {
var reloadData = () => {
$dg.datagrid('load', '@Url.Page("/Customers/Index")?handler=Data');
}
Expand Down Expand Up @@ -371,7 +371,7 @@
if (result) {
axios.get('@Url.Page("/Customers/Index")?handler=Delete&id=' + id).then(res => {
toastr["info"]('@_localizer["Delete Success"]');
reload();
reloadData();
})
.catch((error) => {
var msg = error.response.data;
Expand Down Expand Up @@ -407,7 +407,7 @@
console.log(paras.toString())
axios.get('@Url.Page("/Customers/Index")?handler=DeleteChecked&' + paras.toString()).then(res => {
toastr["info"](`@_localizer["Delete ${checkedId.length} Success"]`);
reload();
reloadData();
})
.catch((error) => {
var msg = error.response.data;
Expand Down
14 changes: 7 additions & 7 deletions src/SmartAdmin.WebUI/Pages/DocumentTypes/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@
{
importUri = Url.Page("/DocumentTypes/Index") + "?handler=Import",
getTemplateUri = @Url.Page("/DocumentTypes/Index") + "?handler=CreateTemplate",
onImportedSucceeded = "reload()"
onImportedSucceeded = "reloadData()"
})
@section ScriptsBlock {
<partial name="_ValidationScriptsPartial" />
Expand All @@ -144,7 +144,7 @@

<script type="text/javascript">
$('#searchbutton').click(function () {
reload();
reloadData();
});
$('#addbutton').click(function () {
popupmodal(null);
Expand All @@ -170,9 +170,9 @@
axios.post('/DocumentTypes/Index', request).then(res => {
toastr["info"]('@_localizer["Save Success"]');
$('#documentType_modal').modal('toggle');
reload();
reloadData();
}).catch((error) => {
var msg = error.response.data;
var msg = error.response.data.Errors.join();
bootbox.alert({
size: "small",
title: "@_localizer["Error"]",
Expand Down Expand Up @@ -247,7 +247,7 @@
}
var reload = () => {
var reloadData = () => {
$dg.datagrid('load', '@Url.Page("/DocumentTypes/Index")?handler=Data');
}
Expand Down Expand Up @@ -289,7 +289,7 @@
if (result) {
axios.get('@Url.Page("/DocumentTypes/Index")?handler=Delete&id=' + id).then(res => {
toastr["info"]('@_localizer["Delete Success"]');
reload();
reloadData();
})
.catch((error) => {
var msg = error.response.data;
Expand Down Expand Up @@ -325,7 +325,7 @@
console.log(paras.toString())
axios.get('@Url.Page("/DocumentTypes/Index")?handler=DeleteChecked&' + paras.toString()).then(res => {
toastr["info"](`@_localizer["Delete ${checkedId.length} Success"]`);
reload();
reloadData();
})
.catch((error) => {
var msg = error.response.data;
Expand Down
12 changes: 6 additions & 6 deletions src/SmartAdmin.WebUI/Pages/KeyValues/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
{
importUri = Url.Page("/KeyValues/Index") + "?handler=Import",
getTemplateUri = @Url.Page("/KeyValues/Index") + "?handler=CreateTemplate",
onImportedSucceeded = "reload()"
onImportedSucceeded = "reloadData()"
})
@section ScriptsBlock {
<script type="text/javascript" src="~/lib/easyui/jquery.easyui.min.js" asp-append-version="true"></script>
Expand All @@ -119,7 +119,7 @@

<script type="text/javascript">
$('#searchbutton').click(function () {
reload();
reloadData();
});
$('#addbutton').click(function () {
onAddRow(null);
Expand Down Expand Up @@ -222,7 +222,7 @@
}
var reload = () => {
var reloadData = () => {
$dg.datagrid('load', '@Url.Page("/KeyValues/Index")?handler=Data');
}
Expand Down Expand Up @@ -314,9 +314,9 @@
.then(response => {
toastr["info"]('@_localizer["Save Success"]');
$dg.datagrid('acceptChanges');
reload();
reloadData();
}).catch(error => {
var msg = error.response.data;
var msg = error.response.data.Errors.join();
bootbox.alert({
size: "small",
title: "@_localizer["Error"]",
Expand Down Expand Up @@ -352,7 +352,7 @@
console.log(paras.toString())
axios.get('@Url.Page("/KeyValues/Index")?handler=DeleteChecked&' + paras.toString()).then(res => {
toastr["info"](`@_localizer["Delete ${checkedId.length} Success"]`);
reload();
reloadData();
})
.catch((error) => {
var msg = error.response.data;
Expand Down

0 comments on commit 8edd170

Please sign in to comment.