Stuck with an query that getting async error - entity-framework

I have a controller wich contains follows:
List<Game> gamesRat = new List<Game>();
if (selectedRating.Count() != 0)//User select any checkboxes
{
FilterGamesByRating(gamesRat, selectedRating, "Shooter");//Filter by user inputs
my = true;//Boolean
}
So the my question is:
when i try to return a View:
return View(await PaginatedList<Game>.CreateAsync(gamesRat.AsQueryable(), page ?? 1, pSize));
I get the following error:
The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IEntityQueryProvider can be used for Entity Framework asynchronous operations
But when in other method, i put that query:
IQueryable<Game> games = _context.Games.Where(x => x.Category == "Shooter");
return View(await PaginatedList<Game>.CreateAsync(games, page ?? 1, pSize));
It works perfectly. How can i fix that error? Thanks.
Of course, my PaginatedList method:
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}

Related

MVVM AsyncExecute causing lag

AsyncExecute method causing lag in my treeview application when I am expanding a branch.
Important parts of my TreeView
public DirectoryItemViewModel(string fullPath, DirectoryItemType type, long size)
{
this.ExpandCommand = new AsyncCommand(Expand, CanExecute);
this.FullPath = fullPath;
this.Type = type;
this.Size = size;
this.ClearChildren();
}
public bool CanExecute()
{
return !isBusy;
}
public IAsyncCommand ExpandCommand { get; set; }
private async Task Expand()
{
isBusy = true;
if (this.Type == DirectoryItemType.File)
{
return;
}
List<Task<long>> tasks = new();
var children = DirectoryStructure.GetDirectoryContents(this.FullPath);
this.Children = new ObservableCollection<DirectoryItemViewModel>(
children.Select(content => new DirectoryItemViewModel(content.FullPath, content.Type, 0)));
//If I delete the remaining part of code in this method everything works fine,
in my idea it should output the folders without lag, and then start calculating their size in other threads, but it first lags for 1-2 sec, then output the content of the folder, and then start calculating.
foreach (var item in children)
{
if (item.Type == DirectoryItemType.Folder)
{
tasks.Add(Task.Run(() => GetDirectorySize(new DirectoryInfo(item.FullPath))));
}
}
var results = await Task.WhenAll(tasks);
for (int i = 0; i < results.Length; i++)
{
Children[i].Size = results[i];
}
isBusy = false;
}
My command Interface and class
public interface IAsyncCommand : ICommand
{
Task ExecuteAsync();
bool CanExecute();
}
public class AsyncCommand : IAsyncCommand
{
public event EventHandler CanExecuteChanged;
private bool _isExecuting;
private readonly Func<Task> _execute;
private readonly Func<bool> _canExecute;
public AsyncCommand(
Func<Task> execute,
Func<bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute()
{
return !_isExecuting && (_canExecute?.Invoke() ?? true);
}
public async Task ExecuteAsync()
{
if (CanExecute())
{
try
{
_isExecuting = true;
await _execute();
}
finally
{
_isExecuting = false;
}
}
RaiseCanExecuteChanged();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void ICommand.Execute(object parameter)
{
//I suppose that here is the problem cause IDE is hinting me that I am not awaiting here, but I don't know how to change it if it is.
ExecuteAsync();
}
}

my area is not getting printed (abstract using interface)

I am currently new to interfaces and I encountered this problem regarding my getArea(), I would love if you guys can point out the error on my code
while this is my Triangle abstract class, I am not sure whether I putted the Semi-perimeter(sp) right or not:
private int sideA;
private int sideB;
private int sideC;
int sp = (sideA+sideB+sideC)/2;
double area = Math.sqrt(sp*(sp-sideA)*(sp-sideB)*(sp-sideC));
public Triangle() {
}
public Triangle(int sideA, int sideB, int sideC, int sp, double area) {
this.sideA=sideA;
this.sideB=sideB;
this.sideC=sideC;
}
public int getSideA() {
return sideA;
}
public void setSideA(int sideA) {
this.sideA = sideA;
}
public int getSideB() {
return sideB;
}
public void setSideB(int sideB) {
this.sideB = sideB;
}
public int getSideC() {
return sideC;
}
public void setSideC(int sideC) {
this.sideC = sideC;
}
public double getPerimeter() {
return sideA+sideB+sideC;
}
public double getArea() {
return getArea();
}
public void getDetails() {
System.out.println("\nType: Triangle" + "\nSides: " +this.sideA +", " +this.sideB+", "+this.sideC + "\nPerimeter: "
+ getPerimeter() + "\nArea: " + getArea() + "\ns: "+sp);
}
}```

EF core 5 Paging Performance issue

I am using EF core 5. I am trying to retrieve records from the table having 1 Million records. I would like to know how I can improve my performance.
Note: I have already implemented the index in the DB. I did google but not find any solution. please advice
How to improve Skip and Take performance in EF core 5
public async Task<IEnumerable<User>> GetUsers(PaginationFilter filter)
{
**return await _context.User.AsNoTracking().Include(e => e.Roles)
.Skip((filter.PageNumber - 1) * filter.PageSize)
.Take(filter.PageSize)
.ToListAsync<User>();**
}
public class PaginationFilter
{
public int PageNumber { get; set; }
public int PageSize { get; set; }
public PaginationFilter()
{
this.PageNumber = 1;
this.PageSize = 10;
}
public PaginationFilter(int pageNumber, int pageSize)
{
this.PageNumber = pageNumber < 1 ? 1 : pageNumber;
this.PageSize = pageSize > 10 ? 10 : pageSize;
}
}
public static UsersPagedResponse<List<T>> CreateUsersPagedReponse<T>(List<T> pagedData, PaginationFilter validFilter, int totalRecords, IUriService uriService, string route)
{
var respose = new UsersPagedResponse<List<T>>(pagedData, validFilter.PageNumber, validFilter.PageSize);
var totalPages = ((double)totalRecords / (double)validFilter.PageSize);
int roundedTotalPages = Convert.ToInt32(Math.Ceiling(totalPages));
respose.MetaData = new MetaData()
{
Page = validFilter.PageNumber,
PageSize = validFilter.PageSize,
Links = new Links()
{
Self = uriService.GetPageUri(new PaginationFilter(validFilter.PageNumber, validFilter.PageSize), route),
First = uriService.GetPageUri(new PaginationFilter(1, validFilter.PageSize), route),
Previous = validFilter.PageNumber - 1 >= 1 && validFilter.PageNumber <= roundedTotalPages ? uriService.GetPageUri(new PaginationFilter(validFilter.PageNumber - 1, validFilter.PageSize), route) : null,
Next = validFilter.PageNumber >= 1 && validFilter.PageNumber < roundedTotalPages ? uriService.GetPageUri(new PaginationFilter(validFilter.PageNumber + 1, validFilter.PageSize), route) : null,
}
};
return respose;
}
}
public class UsersPagedResponse<T> : UsersResponse<T>
{
public MetaData MetaData { get; set; }
public UsersPagedResponse(T users, int pageNumber, int pageSize)
{
this.Users = users;
}
public UsersPagedResponse(T users)
{
this.Users = users;
}
}

Cannot access array of a custom class

In unity I keep getting the error message "NullReferenceException: Object reference not set to an instance of an object" on this:
listOfBanks[0].Deposit(50);
and
accntBlnce.text = "Account Balance:\n" + listOfBanks[curBank].GetBalance().ToString("c");
I have 3 options listed in the drop down menu and when I Debug.Log the number of items in the array I get 3 as my count. But I can't do anything with them. The banks variable is set as the Dropdown object in the inspector as well as the accntBlnce as the text object in my panel.
The code is below.
Banks.cs
public class Banks : MonoBehaviour {
public Dropdown banks;
public Text accntBlnce;
public Bank[] listOfBanks;
public int curBank = 0;
void Start() {
listOfBanks = new Bank[banks.options.Count];
listOfBanks[0].Deposit(50);
}
void Update() {
curBank = banks.value;
accntBlnce.text = "Account Balance:\n" + listOfBanks[curBank].GetBalance().ToString("c");
}
}
Bank.cs
public class Bank{
public Bank() { }
public Bank(string orgn, float amntToRprt, float blnce) {
origin = orgn;
amountToReport = amntToRprt;
balance = blnce;
}
public string origin { get; set; }
public float amountToReport { get; set; }
public float balance { get; set; }
public bool Deposit(float amnt) {
if (amnt > 0) {
balance += amnt;
if(amnt > amountToReport) {
FlagForReport();
}
return true;
}
else
return false;
}
private void FlagForReport() {
throw new NotImplementedException();
}
public float GetBalance() {
return balance;
}
public bool Withdraw(float amnt) {
if (amnt > 0) {
if (balance >= amnt) {
balance -= amnt;
return true;
}
else
return false;
}
else
return false;
}
public bool Transfer(float amnt, Bank bank) {
if (amnt > 0) {
if (balance >= amnt) {
if(bank.Deposit(amnt))
balance -= amnt;
return true;
}
else
return false;
}
else
return false;
}
}
This is the fourth time array question is asked this week with the-same problem and the-same solution.
You declared the array here:
listOfBanks = new Bank[banks.options.Count];
but you did not create new instance of each Bank script before calling
listOfBanks[0].Deposit(50); and listOfBanks[curBank].GetBalance().ToString("c").
Declaring array and setting the size is NOT the-same as creating new instance of a script.
The solution is to loop through the array and create new instance of each one.
In your Banks.cs, replace the code in your Start() function with the one below:
void Start()
{
//Declare how much Bank array should be created
listOfBanks = new Bank[banks.options.Count];
//Now Create instance of each bank
for (int i = 0; i < listOfBanks.Length; i++)
{
//Create new instance of each Bank class
//listOfBanks[i] = new Bank();
listOfBanks[i] = new Bank("", 50, 50);
}
listOfBanks[0].Deposit(50);
}

SimplePager row count is working incorrectly

I'm using SimplePager and I want to show 12 items (users) per page. My entire data set is 20 items.
The problem is that the first page (correctly) shows items 1-12, but the second page shows items 9-20. I want the second page to show items 13-20.
What's going wrong?
Here is my code:
CellTable<User> cellTable = new CellTable<User>();
SimplePager pager = new SimplePager(TextLocation.CENTER);
pager.setDisplay(cellTable);
pager.setPageSize(12);
ListDataProvider<User> dataProvider = new ListDataProvider<User>();<br>
dataProvider.setList(USERSList);
dataProvider.addDataDisplay(cellTable);
Thank you in advance!
Setting
setRangeLimited(false)
will always show a next page.
Instead, I have rangeLimited at true and I've overridden the following method for this :
#Override
public void setPageStart(int index) {
if (getDisplay() != null) {
Range range = getDisplay().getVisibleRange();
int pageSize = range.getLength();
// Removed the min to show fixed ranges
//if (isRangeLimited && display.isRowCountExact()) {
// index = Math.min(index, display.getRowCount() - pageSize);
//}
index = Math.max(0, index);
if (index != range.getStart()) {
getDisplay().setVisibleRange(index, pageSize);
}
}
}
Try setting:
setRangeLimited(false)
More details:
http://groups.google.com/group/google-web-toolkit/browse_thread/thread/45e77082b796281d/d5101729e83a74ff?lnk=gst&q=pager+last+page#d5101729e83a74ff
#fbfcn and #MasterUZ's solution works, with a few slight modifications to make it comply with GWT 2.4's SimplePager:
public class MySimplePager extends SimplePager {
public MySimplePager() {
this.setRangeLimited(true);
}
public MySimplePager(TextLocation location, Resources resources, boolean showFastForwardButton, int fastForwardRows, boolean showLastPageButton) {
super(location, resources, showFastForwardButton, fastForwardRows, showLastPageButton);
this.setRangeLimited(true);
}
public void setPageStart(int index) {
if (this.getDisplay() != null) {
Range range = getDisplay().getVisibleRange();
int pageSize = range.getLength();
if (!isRangeLimited() && getDisplay().isRowCountExact()) {
index = Math.min(index, getDisplay().getRowCount() - pageSize);
}
index = Math.max(0, index);
if (index != range.getStart()) {
getDisplay().setVisibleRange(index, pageSize);
}
}
}
}
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.view.client.Range;
public class MySimplePager extends SimplePager {
public MySimplePager() {
this.setRangeLimited(true);
}
public MySimplePager(TextLocation location, Resources resources, boolean showFastForwardButton, int fastForwardRows, boolean showLastPageButton) {
super(location, resources, showFastForwardButton, fastForwardRows, showLastPageButton);
this.setRangeLimited(true);
}
#Override
public void setPageStart(int index) {
if (getDisplay() != null) {
Range range = getDisplay().getVisibleRange();
int pageSize = range.getLength();
if (!isRangeLimited() && getDisplay().isRowCountExact()) {
index = Math.min(index, getDisplay().getRowCount() - pageSize);
}
index = Math.max(0, index);
if (index != range.getStart()) {
getDisplay().setVisibleRange(index, pageSize);
}
}
}
}