Skip to content

Commit

Permalink
Use PagerAsync and PagerSlimAsync instead of using dynamic New (#14978)
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeAlhayek authored Jan 4, 2024
1 parent cbac3d5 commit 87f7a43
Show file tree
Hide file tree
Showing 28 changed files with 546 additions and 428 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,17 @@ namespace OrchardCore.AdminMenu.Controllers
[Admin]
public class MenuController : Controller
{
private const string _optionsSearch = "Options.Search";

private readonly IAuthorizationService _authorizationService;
private readonly IAdminMenuService _adminMenuService;
private readonly PagerOptions _pagerOptions;
private readonly IShapeFactory _shapeFactory;
private readonly INotifier _notifier;
private readonly ILogger _logger;

protected readonly IStringLocalizer S;
protected readonly IHtmlLocalizer H;
protected readonly dynamic New;
private readonly ILogger _logger;

public MenuController(
IAuthorizationService authorizationService,
Expand All @@ -45,7 +48,7 @@ public MenuController(
_authorizationService = authorizationService;
_adminMenuService = adminMenuService;
_pagerOptions = pagerOptions.Value;
New = shapeFactory;
_shapeFactory = shapeFactory;
_notifier = notifier;
S = stringLocalizer;
H = htmlLocalizer;
Expand All @@ -72,7 +75,7 @@ public async Task<IActionResult> List(ContentOptions options, PagerParameters pa
var pageSize = pager.PageSize;
IEnumerable<Models.AdminMenu> results = new List<Models.AdminMenu>();

//todo: handle the case where there is a deserialization exception on some of the presets.
// todo: handle the case where there is a deserialization exception on some of the presets.
// load at least the ones without error. Provide a way to delete the ones on error.
try
{
Expand All @@ -87,11 +90,15 @@ public async Task<IActionResult> List(ContentOptions options, PagerParameters pa
await _notifier.ErrorAsync(H["Error when retrieving the list of admin menus."]);
}

// Maintain previous route data when generating page links
// Maintain previous route data when generating page links.
var routeData = new RouteData();
routeData.Values.Add("Options.Search", options.Search);

var pagerShape = (await New.Pager(pager)).TotalItemCount(adminMenuList.Count).RouteData(routeData);
if (!string.IsNullOrEmpty(options.Search))
{
routeData.Values.TryAdd(_optionsSearch, options.Search);
}

var pagerShape = await _shapeFactory.PagerAsync(pager, adminMenuList.Count, routeData);

var model = new AdminMenuListViewModel
{
Expand All @@ -100,22 +107,21 @@ public async Task<IActionResult> List(ContentOptions options, PagerParameters pa
Pager = pagerShape,
};

model.Options.ContentsBulkAction = new List<SelectListItem>()
{
new SelectListItem() { Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove) },
};
model.Options.ContentsBulkAction =
[
new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),
];

return View(model);
}

[HttpPost, ActionName("List")]
[HttpPost, ActionName(nameof(List))]
[FormValueRequired("submit.Filter")]
public ActionResult IndexFilterPOST(AdminMenuListViewModel model)
{
return RedirectToAction(nameof(List), new RouteValueDictionary {
{ "Options.Search", model.Options.Search }
=> RedirectToAction(nameof(List), new RouteValueDictionary
{
{_optionsSearch, model.Options.Search }
});
}

public async Task<IActionResult> Create()
{
Expand Down Expand Up @@ -234,9 +240,9 @@ public async Task<IActionResult> Delete(string id)
return RedirectToAction(nameof(List));
}

[HttpPost, ActionName("List")]
[HttpPost, ActionName(nameof(List))]
[FormValueRequired("submit.BulkAction")]
public async Task<ActionResult> IndexPost(ViewModels.ContentOptions options, IEnumerable<string> itemIds)
public async Task<ActionResult> IndexPost(ContentOptions options, IEnumerable<string> itemIds)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
Expand All @@ -260,7 +266,7 @@ public async Task<ActionResult> IndexPost(ViewModels.ContentOptions options, IEn
await _notifier.SuccessAsync(H["Admin menus successfully removed."]);
break;
default:
throw new ArgumentOutOfRangeException(nameof(options.BulkAction), "Invalid bulk action.");
throw new ArgumentOutOfRangeException(options.BulkAction.ToString(), "Invalid bulk action.");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,7 @@ public async Task<ActionResult> Index([ModelBinder(BinderType = typeof(AuditTrai
// Populate route values to maintain previous route data when generating page links.
options.RouteValues.TryAdd("q", options.FilterResult.ToString());

var pagerShape = await _shapeFactory.CreateAsync("Pager", Arguments.From(new
{
pager.Page,
pager.PageSize,
TotalItemCount = result.TotalCount
}));

var pagerShape = await _shapeFactory.PagerAsync(pager, result.TotalCount, options.RouteValues);
var items = new List<IShape>();

foreach (var auditTrailEvent in result.Events)
Expand All @@ -104,13 +98,13 @@ await _displayManager.BuildDisplayAsync(auditTrailEvent, updater: _updateModelAc
);
}

var startIndex = (pager.Page - 1) * (pager.PageSize) + 1;
var startIndex = (pager.Page - 1) * pager.PageSize + 1;
options.StartIndex = startIndex;
options.EndIndex = startIndex + items.Count - 1;
options.EventsCount = items.Count;
options.TotalItemCount = result.TotalCount;

var header = await _auditTrailOptionsDisplayManager.BuildEditorAsync(options, _updateModelAccessor.ModelUpdater, false, "", "");
var header = await _auditTrailOptionsDisplayManager.BuildEditorAsync(options, _updateModelAccessor.ModelUpdater, false, string.Empty, string.Empty);

var shapeViewModel = await _shapeFactory.CreateAsync<AuditTrailListViewModel>("AuditTrailAdminList", viewModel =>
{
Expand All @@ -123,19 +117,19 @@ await _displayManager.BuildDisplayAsync(auditTrailEvent, updater: _updateModelAc
return View(shapeViewModel);
}

[HttpPost, ActionName("Index")]
[HttpPost, ActionName(nameof(Index))]
[FormValueRequired("submit.Filter")]
public async Task<ActionResult> IndexFilterPOST(AuditTrailIndexOptions options)
{
await _auditTrailOptionsDisplayManager.UpdateEditorAsync(options, _updateModelAccessor.ModelUpdater, false, "", "");
await _auditTrailOptionsDisplayManager.UpdateEditorAsync(options, _updateModelAccessor.ModelUpdater, false, string.Empty, string.Empty);
// When the user has typed something into the search input no further evaluation of the form post is required.
if (!string.Equals(options.SearchText, options.OriginalSearchText, StringComparison.OrdinalIgnoreCase))
{
return RedirectToAction(nameof(Index), new RouteValueDictionary { { "q", options.SearchText } });
}

// Evaluate the values provided in the form post and map them to the filter result and route values.
await _auditTrailOptionsDisplayManager.UpdateEditorAsync(options, _updateModelAccessor.ModelUpdater, false, "", "");
await _auditTrailOptionsDisplayManager.UpdateEditorAsync(options, _updateModelAccessor.ModelUpdater, false, string.Empty, string.Empty);

// The route value must always be added after the editors have updated the models.
options.RouteValues.TryAdd("q", options.FilterResult.ToString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,16 @@ namespace OrchardCore.BackgroundTasks.Controllers
[Admin]
public class BackgroundTaskController : Controller
{
private const string _optionsSearch = $"{nameof(BackgroundTaskIndexViewModel.Options)}.{nameof(AdminIndexOptions.Search)}";
private const string _optionsStatus = $"{nameof(BackgroundTaskIndexViewModel.Options)}.{nameof(AdminIndexOptions.Status)}";

private readonly IAuthorizationService _authorizationService;
private readonly IEnumerable<IBackgroundTask> _backgroundTasks;
private readonly BackgroundTaskManager _backgroundTaskManager;
private readonly PagerOptions _pagerOptions;
private readonly INotifier _notifier;
protected readonly dynamic New;
private readonly IShapeFactory _shapeFactory;

protected readonly IStringLocalizer S;
protected readonly IHtmlLocalizer H;

Expand All @@ -47,8 +51,7 @@ public BackgroundTaskController(
_backgroundTaskManager = backgroundTaskManager;
_pagerOptions = pagerOptions.Value;
_notifier = notifier;

New = shapeFactory;
_shapeFactory = shapeFactory;
S = stringLocalizer;
H = htmlLocalizer;
}
Expand Down Expand Up @@ -102,20 +105,27 @@ public async Task<IActionResult> Index(AdminIndexOptions options, PagerParameter
items = items.Where(entry => !entry.Enable);
}

options.Statuses = new List<SelectListItem>()
{
new SelectListItem() { Text = S["Enabled"], Value = "enabled" },
new SelectListItem() { Text = S["Disabled"], Value = "disabled" }
};
options.Statuses =
[
new SelectListItem(S["Enabled"], "enabled"),
new SelectListItem(S["Disabled"], "disabled")
];

var taskItems = items.ToList();
var routeData = new RouteData();

routeData.Values.Add($"{nameof(BackgroundTaskIndexViewModel.Options)}.{nameof(options.Search)}", options.Search);
routeData.Values.Add($"{nameof(BackgroundTaskIndexViewModel.Options)}.{nameof(options.Status)}", options.Status);
if (!string.IsNullOrEmpty(options.Search))
{
routeData.Values.TryAdd(_optionsSearch, options.Search);
}

if (!string.IsNullOrEmpty(options.Status))
{
routeData.Values.TryAdd(_optionsStatus, options.Status);
}

var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize());
var pagerShape = (await New.Pager(pager)).TotalItemCount(taskItems.Count).RouteData(routeData);
var pagerShape = await _shapeFactory.PagerAsync(pager, taskItems.Count, routeData);

var model = new BackgroundTaskIndexViewModel
{
Expand All @@ -130,12 +140,11 @@ public async Task<IActionResult> Index(AdminIndexOptions options, PagerParameter
[HttpPost, ActionName(nameof(Index))]
[FormValueRequired("submit.Filter")]
public ActionResult IndexFilterPOST(BackgroundTaskIndexViewModel model)
{
return RedirectToAction(nameof(Index), new RouteValueDictionary {
{ $"{nameof(model.Options)}.{nameof(AdminIndexOptions.Search)}", model.Options.Search },
{ $"{nameof(model.Options)}.{nameof(AdminIndexOptions.Status)}", model.Options.Status },
=> RedirectToAction(nameof(Index), new RouteValueDictionary
{
{ _optionsSearch, model.Options.Search },
{ _optionsStatus, model.Options.Status },
});
}

public async Task<IActionResult> Edit(string name)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ public class AdminController : Controller

protected readonly IHtmlLocalizer H;
protected readonly IStringLocalizer S;
protected readonly dynamic New;

public AdminController(
IAuthorizationService authorizationService,
Expand Down Expand Up @@ -80,7 +79,6 @@ public AdminController(

H = htmlLocalizer;
S = stringLocalizer;
New = shapeFactory;
}

[HttpGet]
Expand Down Expand Up @@ -153,33 +151,33 @@ public async Task<IActionResult> List(
}

// We populate the remaining SelectLists.
options.ContentStatuses = new List<SelectListItem>()
{
options.ContentStatuses =
[
new SelectListItem(S["Latest"], nameof(ContentsStatus.Latest), options.ContentsStatus == ContentsStatus.Latest),
new SelectListItem(S["Published"], nameof(ContentsStatus.Published), options.ContentsStatus == ContentsStatus.Published),
new SelectListItem(S["Unpublished"], nameof(ContentsStatus.Draft), options.ContentsStatus == ContentsStatus.Draft),
new SelectListItem(S["All versions"], nameof(ContentsStatus.AllVersions), options.ContentsStatus == ContentsStatus.AllVersions),
};
];

if (await IsAuthorizedAsync(Permissions.ListContent))
{
options.ContentStatuses.Insert(1, new SelectListItem() { Text = S["Owned by me"], Value = nameof(ContentsStatus.Owner) });
}

options.ContentSorts = new List<SelectListItem>()
{
options.ContentSorts =
[
new SelectListItem(S["Recently created"], nameof(ContentsOrder.Created), options.OrderBy == ContentsOrder.Created),
new SelectListItem(S["Recently modified"], nameof(ContentsOrder.Modified),options.OrderBy == ContentsOrder.Modified ),
new SelectListItem(S["Recently modified"], nameof(ContentsOrder.Modified), options.OrderBy == ContentsOrder.Modified),
new SelectListItem(S["Recently published"], nameof(ContentsOrder.Published), options.OrderBy == ContentsOrder.Published),
new SelectListItem(S["Title"], nameof(ContentsOrder.Title), options.OrderBy == ContentsOrder.Title),
};
];

options.ContentsBulkAction = new List<SelectListItem>()
{
options.ContentsBulkAction =
[
new SelectListItem(S["Publish Now"], nameof(ContentsBulkAction.PublishNow)),
new SelectListItem(S["Unpublish"], nameof(ContentsBulkAction.Unpublish)),
new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),
};
];

if (options.ContentTypeOptions == null
&& (string.IsNullOrEmpty(options.SelectedContentType) || string.IsNullOrEmpty(contentTypeId)))
Expand All @@ -200,9 +198,8 @@ public async Task<IActionResult> List(
// Populate route values to maintain previous route data when generating page links.
options.RouteValues.TryAdd("q", options.FilterResult.ToString());

var routeData = new RouteData(options.RouteValues);
var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize());
var pagerShape = (await New.Pager(pager)).TotalItemCount(_pagerOptions.MaxPagedCount > 0 ? _pagerOptions.MaxPagedCount : await query.CountAsync()).RouteData(routeData);
dynamic pagerShape = await _shapeFactory.PagerAsync(pager, _pagerOptions.MaxPagedCount > 0 ? _pagerOptions.MaxPagedCount : await query.CountAsync(), options.RouteValues);

// Load items so that loading handlers are invoked.
var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync(_contentManager);
Expand Down Expand Up @@ -308,7 +305,7 @@ public async Task<ActionResult> ListPOST(ContentOptionsViewModel options, IEnume
await _notifier.SuccessAsync(H["Content removed successfully."]);
break;
default:
throw new ArgumentOutOfRangeException(nameof(options.BulkAction), "Invalid bulk action.");
throw new ArgumentOutOfRangeException(options.BulkAction.ToString(), "Invalid bulk action.");
}
}

Expand Down Expand Up @@ -417,7 +414,7 @@ public async Task<IActionResult> Edit(string contentItemId)
return View(model);
}

[HttpPost, ActionName("Edit")]
[HttpPost, ActionName(nameof(Edit))]
[FormValueRequired("submit.Save")]
public Task<IActionResult> EditPOST(string contentItemId, [Bind(Prefix = "submit.Save")] string submitSave, string returnUrl)
{
Expand All @@ -434,7 +431,7 @@ await _notifier.SuccessAsync(string.IsNullOrWhiteSpace(typeDefinition?.DisplayNa
});
}

[HttpPost, ActionName("Edit")]
[HttpPost, ActionName(nameof(Edit))]
[FormValueRequired("submit.Publish")]
public async Task<IActionResult> EditAndPublishPOST(string contentItemId, [Bind(Prefix = "submit.Publish")] string submitPublish, string returnUrl)
{
Expand Down
Loading

0 comments on commit 87f7a43

Please sign in to comment.