I have class for capturing all parameters :
public class UserParams
{
private const int MaxPageSize = 50;
public int PageNumber { get; set; } = 1;
private int pageSize = 10;
public int PageSize
{
get { return pageSize;}
set { pageSize = (value > MaxPageSize) ? MaxPageSize : value;}
}
public int UserId { get; set; }
public string OrderBy { get; set; }
public bool isAll {get; set;} = true;
public bool isManagers { get; set; } = false;
public bool isPartners { get; set; } = false;
}
and my controllers:
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery] UserParams userParams)
{
var users = await _appRepo.GetUsers(userParams);
var usersDto = _mapper.Map<IEnumerable<UserSimpleDto>>(users);
Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);
return Ok(usersDto);
}
While my appRepo.GetUsers:
public async Task<PagedList<User>> GetUsers(UserParams userParams)
{
var users = _context.Users.OrderByDescending(p => p.FirstName).AsQueryable();
if(userParams.isManagers)
{
users = users.Where( u => u.IsManager == true);
}
if(userParams.isPartners)
{
users = users.Where( u => u.IsPartner == true);
}
return await PagedList<User>.CreateAsync(users, userParams.PageNumber, userParams.PageSize);
}
I tried to debug the code with Postman :
http://localhost:5000/api/user?isManagers=1
or
http://localhost:5000/api/user?isManagers=true
but it seems the params isManagers still false (the result is still get all users)
How to fix this bug?
Related
I am having the below model class CallbackResponse.cs :
public class CallbackResponse
{
public Callback Data { get; set; }
}
public class Callback
{
public IEnumerable<ReviewInProgressActivityFeed> ActivitiesFeed { get; set; }
}
public class ReviewInProgressActivityFeed
{
public ReviewInProgressStatus ReviewerSession { get; set; }
}
public class ReviewInProgressStatus
{
public Guid ReviewActivityId { get; set; }
public string ReviewerName { get; set; }
public string ReviewComments { get; set; }
public DateTime ActivityDateTime { get; set; }
}
Sample Payload:
{
"data":
{
"activitiesFeed": [
{
"reviewerSession":
{
"reviewActivityId": "dd9937c3-7c01-4a4a-bc8d-05ef37b07ee5",
"ReviewerName": "Verification Team",
"reviewComments": "upload business verification document for further verification.",
"activityDateTime": "2021-03-31T18:34:26.5978962Z"
},
},
{
"reviewerSession":
{
"reviewActivityId": "dd9937c3-7c01-4a4a-bc8d-05ef37b07ee5",
"ReviewerName": "Other Team",
"reviewComments": "other documents required for verification.",
"activityDateTime": "2021-03-31T19:34:26.5978962Z"
},
}
]
}
}
I am trying to get the data from DB via the CallbackResponse model class. Please find the code for below.
public async Task<CallbackResponse> CallbackActivityFeedAsync(Guid Id)
{
CallbackResponse containerItems = new CallbackResponse();
IQueryable<HumanReviewRequest> query = cosmosReviewRequestContainer.GetItemLinqQueryable<HumanReviewRequest>(true);
query = query.Where(x => x.id == Id);
FeedIterator<HumanReviewRequest> feedIterator = query.ToFeedIterator();
while (feedIterator.HasMoreResults)
{
FeedResponse<HumanReviewRequest> r = await feedIterator.ReadNextAsync().ConfigureAwait(false);
foreach (HumanReviewRequest requestModel in r)
{
containerItems = new CallbackResponse
{
Data = new Callback
{
ActivitiesFeed = new List<ReviewInProgressActivityFeed>
{
new ReviewInProgressActivityFeed
{
ReviewerSession = new ReviewInProgressStatus
{
ReviewActivityId = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewActivityId).LastOrDefault(),
ActivityDateTime = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ActivityDateTime).LastOrDefault(),
ReviewComments = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewerComments).LastOrDefault(),
ReviewerName = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewerName).LastOrDefault()
}
}
}
}
};
}
}
return containerItems;
}
The Problem here is I could not able to fetch all the records present in activitiesFeed array in DB. Instead I could only able to fetch the last record in that array(I am using Azure Cosmos DB). Please help me in this.
HumanReviewRequest.cs (which is DB Class)for reference:
public class HumanReviewRequest
{
public Guid Id { get; set; }
public IEnumerable<ReviewActivity> ReviewActivities { get; set; }
public class ReviewActivity
{
public ReviewerSession ReviewerSession { get; set; }
public string UserComments { get; set; }
}
public class ReviewerSession
{
public Guid ReviewActivityId { get; set; }
public Guid ReviewerUserId { get; set; }
public DateTime ActivityDateTime { get; set; }
public string ReviewerComments { get; set; }
}
This is because you are creating a new List<ReviewInProgressActivityFeed>, a new ReviewInProgressActivityFeed and reading only the last element in activitiesFeed for each iteration:
ReviewerSession = new ReviewInProgressStatus
{
ReviewActivityId = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewActivityId).LastOrDefault(),
ActivityDateTime = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ActivityDateTime).LastOrDefault(),
ReviewComments = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewerComments).LastOrDefault(),
ReviewerName = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewerName).LastOrDefault()
}
Try below code instead of the above code:
public async Task<CallbackResponse> CallbackActivityFeedAsync(Guid Id)
{
CallbackResponse containerItems = new CallbackResponse();
containerItems.Data = new Callback();
containerItems.Data.ActivitiesFeed = new List<ReviewInProgressActivityFeed>();
IQueryable<HumanReviewRequest> query = cosmosReviewRequestContainer.GetItemLinqQueryable<HumanReviewRequest>(true);
query = query.Where(x => x.id == Id);
FeedIterator<HumanReviewRequest> feedIterator = query.ToFeedIterator();
while (feedIterator.HasMoreResults)
{
FeedResponse<HumanReviewRequest> r = await feedIterator.ReadNextAsync().ConfigureAwait(false);
if (r != null || r.ReviewActivities != null)
{
foreach (HumanReviewRequest requestModel in r.ReviewActivities)
{
containerItems.Data.ActivitiesFeed.Add(
new ReviewInProgressActivityFeed
{
ReviewerSession = new ReviewInProgressStatus
{
ReviewActivityId = requestModel.ReviewerSession.ReviewActivityId,
ActivityDateTime = requestModel.ReviewerSession.ActivityDateTime,
ReviewComments = requestModel.ReviewerSession.ReviewerComments,
ReviewerName = requestModel.ReviewerSession.ReviewerName
}
});
}
}
}
};
}
}
return containerItems;
}
My entity looks as follows:
public class AddPatientReportDentalChartInput : IInputDto
{
[Required]
[MaxLength(PatientReportDentalChart.TeethDesc)]
public string Image { get; set; }
[Required]
public virtual int PatientID { get; set; }
[Required]
public virtual int TeethNO { get; set; }
public string SurfaceDefault1 { get; set; }
public string SurfaceDefault2 { get; set; }
public string SurfaceDefault3 { get; set; }
public string SurfaceDefault4 { get; set; }
public string SurfaceDefault5 { get; set; }
}
And the method by which i want to update is:
public async Task addPatientReportDentalChart(AddPatientReportDentalChartInput input)
{
var pid = input.PatientID;
var chartdetails = _chartReportRepository
.GetAll()
.WhereIf(!(pid.Equals(0)),
p => p.PatientID.Equals(pid)).ToList();
if (chartdetails.Count>0)
{
//Update should be apply here
//please suggest me the solution using updatesync
}
else
{
var patientinfo = input.MapTo<PatientReportDentalChart>();
await _chartReportRepository.InsertAsync(patientinfo);
}
}
What is the equivalent of InsertAsync when I want to update an existing entity? Is there an UpdateAsync equivalent method?
Updating an entity in Entity Framework requires you to retrieve the record, update it and then save changes. It will look roughly like this:
public async Task AddPatientReportDentalChartAsync(AddPatientReportDentalChartInput input)
{
var pid = input.PatientID;
var chartdetails = _chartReportRepository
.GetAll()
.WhereIf(!(pid.Equals(0)),
p => p.PatientID.Equals(pid)).ToList();
if (chartdetails.Count > 0)
{
var entity = await _chartReportRepository
.YourTableName
.FindAsync(entity => entity.SomeId == matchingId);
entity.PropertyA = "something"
entity.PropertyB = 1;
await _chartReportRepository.SaveChangesAsync();
}
else
{
var patientinfo = input.MapTo<PatientReportDentalChart>();
await _chartReportRepository.InsertAsync(patientinfo);
}
}
Try this if you're using .NET CORE 3.1
public async Task<int> UpdateChat(MChat mChat)
{
try
{
return await Task.Run(() =>
{
BDContext.Chat.Update(new Chat
{
Id = mChat.id,
UsuarioIdInicia = mChat.usuarioIdInicia,
UsuarioIdFinaliza = mChat.usuarioIdFinaliza,
EstadoChatId = mChat.estadoChatId
});
return BDContext.SaveChanges();
});
}
catch (Exception ex)
{
Console.WriteLine(Constantes.ERROR_DETECTADO + ex.InnerException.ToString());
return Constantes.ERROR_1;
}
}
I'm trying to set a property Klimatogram.Locatie in a controller class like this:
public ActionResult SelectKlimatorgramVanLocatie(LocatieKlimatogramViewModel model)
{
Locatie selectedLocatie = (Locatie)Session["GevondenLocatie"];
Klimatogram klimatogram = new Klimatogram(selectedLocatie);
TempData["kilmatogram"] = klimatogram;
return RedirectToAction("Index", "Vragen");
}
So if I debug I can see that klimatogram.Locatie is being set by selectedLocatie.
EDIT :
Now klimatogram.Locatie gets filled up. But when i look at the values from Klimatogram they are all 0.
Here is an example in the class Klimatogram:
public class Klimatogram
{
public Klimatogram(Locatie selectedLocatie)
{
Locatie =selectedLocatie;
}
public Locatie Locatie { get; set; }
public int Id { get; set; }
private double warmsteMaand;
private double aantalDrogeMaanden;
private double gemJaarTemp;
private double gemJaarNeerslag;
private double hoeveelNeerslagWinter;
private double hoeveelNeerslagZomer;
private double koudsteMaand;
public int klimaId { get; set; }
public double TempWarmsteMaand
{
get { return warmsteMaand; }
set
{
value = Locatie.TemperatuurPerMaand[0];
for (int i = 1; i < 12; i++)
{
if (Locatie.TemperatuurPerMaand[i] > value)
{
value = Locatie.TemperatuurPerMaand[i];
}
}
warmsteMaand = value;
}
}
So this method doesn't get any value from my Locatie. When i debug it says it is 0 which is wrong.
this is my vragenController:
public ActionResult Index()
{
var klimatogram = (Klimatogram)TempData["kilmatogram"];
VragenViewModel vragenViewModel = new VragenViewModel(klimatogram);
return View("VragenControl",vragenViewModel);
}
This is the viewmodel:
public class VragenViewModel
{
// public SelectList Maanden { get; set; }
public VragenViewModel()
{
}
public VragenViewModel(Klimatogram klima)
{
warm = klima.TempWarmsteMaand;
koud = klima.TempKoudsteMaand;
droge = klima.AantalDrogeMaanden;
winterneerslag = klima.HoeveelheidNeerslagWinter;
zomerneerslag = klima.HoeveelheidNeerslagZomer;
}
public double zomerneerslag
{ get; set; }
public double winterneerslag { get; set; }
public double droge { get; set; }
public double koud { get; set; }
public double warm { get; set; }
}
maybe just
public ActionResult SelectKlimatorgramVanLocatie(LocatieKlimatogramViewModel model)
{
Locatie selectedLocatie = (Locatie)Session["GevondenLocatie"];
Klimatogram klimatogram = new Klimatogram();
klimatogram.Locatie = selectedLocatie;
return Index(klimatogram);
}
The third argument of RedirectToAction is routeValues, not passing a model like you do with View.
You can use the TempData variable to pass data through as per this answer:
public ActionResult SelectKlimatorgramVanLocatie(LocatieKlimatogramViewModel model)
{
Locatie selectedLocatie = (Locatie)Session["GevondenLocatie"];
Klimatogram klimatogram = new Klimatogram();
klimatogram.Locatie = selectedLocatie;
TempData["kilmatogram"] = kilmatogram;
return RedirectToAction("Index", "Vragen");
}
// ...
public ActionResult Index()
{
var kilmatogram = (Kilmatogram)TempData["kilmatogram"];
// ...
}
I have this:
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
public List<???prpClass???> Whatever(string prpClass)
where string prpClass can be "Blah" or "Doh".
I would like the List type to be class Blah or Doh based on what the string prpClass holds.
How can I achieve this?
EDIT:
public List<prpClass??> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result;
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result;
}
return null
}
}
you have to have a common supertype:
public interface IHaveAnId
{
int id { get;set; }
}
public class Blah : IHaveAnId
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh : IHaveAnId
{
public int id {get;set;}
public string dohh { get; set; }
public string mahh { get; set; }
}
then you can do:
public List<IHaveAnId> TheList = new List<IHaveAnId>();
and in some method:
TheList.Add(new Blah{id=1,blahh = "someValue"});
TheList.Add(new Doh{id =2, dohh = "someValue", mahh = "someotherValue"});
to iterate through the list:
foreach(IHaveAnId item in TheList)
{
Console.WriteLine("TheList contains an item with id {0}", item.id);
//item.id is allowed since you access the property of the class over the interface
}
or to iterate through all Blahs:
foreach(Blah item in TheList.OfType<Blah>())
{
Console.WriteLine("TheList contains a Blah with id {0} and blahh ='{1}'", item.id, item.blahh);
}
Edit:
the 2 methods and a int field holding the autovalue:
private int autoValue = 0;
public void AddBlah(string blahh)
{
TheList.Add(new Blah{id = autovalue++, blahh = blahh});
}
public void AddDoh(string dohh, string mahh)
{
TheList.Add(new Doh{id = autovalue++, dohh = dohh, mahh = mahh});
}
Another Edit
public List<object> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result.Cast<object>().ToList();
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result.Cast<object>.ToList();
}
return null;
}
}
in the view you then have to decide what type it is. In asp.net MVC you can use a display template and use reflection to get a good design. But then i still don't know what technology you are using.
Yet another Edit
TestClass:
public class SomeClass
{
public string Property { get; set; }
}
Repository:
public static class Repository
{
public static List<object> Whatever(string prpClass)
{
switch (prpClass)
{
case "SomeClass":
return new List<SomeClass>()
{
new SomeClass{Property = "somestring"},
new SomeClass{Property = "someOtherString"}
}.Cast<object>().ToList();
default:
return null;
}
}
}
And a controller action in mvc:
public JsonResult Test(string className)
{
return Json(Repository.Whatever("SomeClass"),JsonRequestBehavior.AllowGet);
}
then i called it with: http://localhost:56619/Home/Test?className=SomeClass
And got the result:
[{"Property":"somestring"},{"Property":"someOtherString"}]
Is this what you are trying to do?
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
class Program
{
public static List<T> Whatever<T>(int count) where T: new()
{
return Enumerable.Range(0, count).Select((i) => new T()).ToList();
}
static void Main(string[] args)
{
var list=Whatever<Doh>(100);
// list containts 100 of "Doh"
}
}
I am writing an app that has an Azure database. I've never did nything connected with Azure, so I am new to all the stuff. I've found on the internet and at microsoft documentation some tutorials, but I must have got sth wrong, cause it doesn't work. So I have a table at my database called Week, I've created a model in my code:
[DataContract]
public class Week
{
//[JsonProperty(PropertyName = "Id")]
//[DataMember]
public int Id { get; set; }
[JsonProperty(PropertyName = "Book")]
[DataMember]
public Book CurrentBook { get; set; }
[JsonProperty(PropertyName = "Is_Read")]
[DataMember]
public Boolean IsRead { get; set; }
[JsonProperty(PropertyName = "Pages_Read")]
[DataMember]
public int PagesRead { get; set; }
[JsonProperty(PropertyName = "Start_Date")]
[DataMember]
public DateTime StartDate { get; set; }
[JsonProperty(PropertyName = "User")]
[DataMember]
public User Reader { get; set; }
[JsonProperty(PropertyName = "Week_Number")]
[DataMember]
public int WeekNumber { get; set; }
public Week(Book currentBook, Boolean isRead, int pagesRead, DateTime startDate, User reader, int weekNumber)
{
CurrentBook = currentBook;
IsRead = isRead;
PagesRead = pagesRead;
StartDate = startDate;
Reader = reader;
WeekNumber = weekNumber;
}
public Week()
{
}
public int GetMonth()
{
//TODO: Implement the method.
return 0;
}
}
Then I created the WeekRepository for CRUD operations:
public class WeekRepository : BaseRepository<Week>
{
private IMobileServiceTable<Week> weekTable;
public string errorMesage = string.Empty;
public WeekRepository()
{
weekTable = MobileService.GetTable<Week>();
}
public async override Task<int> Save(Week entity)
{
try
{
await weekTable.InsertAsync(entity);
// .ContinueWith(t =>
//{
// if (t.IsFaulted)
// {
// errorMesage = "Insert failed";
// }
// else
// {
// errorMesage = "Inserted a new item with id " + entity.Id;
// }
//});
}
catch (WebException ex)
{
errorMesage = ex.Message;
}
return entity.Id;
}
public override void Update(Week entity)
{
return;
}
public override Week Load(int bookId)
{
var week = weekTable.Where(w => w.IsRead == false).ToListAsync();
return week.Result.Single();
}
public override List<Week> LoadByUserId(int userId)
{
return new List<Week>();
}
public Week LoadCurrentWeek(int userId)
{
return new Week();
}
}
To test if it works, I wrote a simple test:
[TestMethod]
public void ShouldSaveWeekToTheDB()
{
//ARANGE
Week weekTestEntity = new Week(null, false, 10, new DateTime(), null, 1);
//ACT
int id = weekRepository.Save(weekTestEntity).Result;
//ASSERT
var savedItem = weekRepository.Load(1);
Assert.AreEqual(false, savedItem.IsRead);
}
However, InsertAsync() throws an exception - Not Found. I've no idea what I am doing wrong, cause it seems a simple thing as far as I can see from the material on the Internet.
If You could help me, I would be really grateful!
Thank You in advance!
Best Regards,
Roman.