How to get data from list by condition in Xamarin - xamarin.forms

I have Class Model:
Class ProductInfo
public class ProductInfo
{
public int ID { get; set; }
public int IDProduct { get; set; }
public List<ProductImages> ProductImages { get; set; }
}
Class ProductImages
public class ProductImages
{
public int ID { get; set; }
public int ProductID { get; set; }
public string Images { get; set; }
public Boolean ImgFlag { get; set; }
}
I have data
This is how I get product information
async Task ExecuteLoadProductCommand()
{
IsBusy = true;
try
{
ProductInfos.Clear();
var prodList = await productRepository.GetProductsAsync();
foreach (var prod in prodList)
{
//Get Imgaes by condition
//prod.Images = ProductImages()
ProductInfos.Add(prod);
}
}
catch (Exception)
{
throw;
}
finally
{
IsBusy = false;
}
}
The first:
How can I Binding Images with the condition ImgFlag = true in ContentPage Product.axml
The Second:
I have a ContentPage that shows ProductDetails.axml. I show the following information:
"Name": Name Product,... ---> This is fine. However I have an extra CarouselView. I want to show a list of images with the condition that ProductID = ID(ProductInfo)
This is how I pass the ProductDetail data
public DashboardsViewModel()
{
LoadProductCommand = new Command(async () => await ExecuteLoadProductCommand());
ProductInfos = new ObservableCollection<ProductInfo>();
ProductTappedView = new Command<ProductInfo>(OnViewDetailProduct);
}
private async void OnViewDetailProduct(ProductInfo prod)
{
await Navigation.PushAsync(new DetailProduct(prod));
}
Thank you!

Related

asp.net core does not respect case sensitivity

i have this controller method that return an array of objects
public async Task<ActionResult<List<AllClientsDataModelDb>>> GetAll()
{
var ReturnValue = new List<AllClientsDataModelDb>();
ReturnValue = await Clda.GetClients(new { cm = 1 });
return (ReturnValue);
}
here is the code of AllClientsDataModelDb class
public class AllClientsDataModelDb
{
public long IDCLIENT { get; set; }
public string CL_CODE { get; set; }
public string CL_NOM { get; set; }
public string CL_ADRESSE { get; set; }
public string CL_CODEPOS { get; set; }
public string CL_VILLE { get; set; } = null;
public int CL_ETATCOMPTE { get; set; }
public int CL_AlerteCompta { get; set; }
}
but the result of that method (in browser) does not respect the case sensitivity of the class properties
Example :
[{"idclient":1,"cL_CODE":"1","cL_NOM":"EUROPEQUIPEMENTMysql","cL_ADRESSE":"ModifSoft","cL_CODEPOS":"44","cL_VILLE":"STDENIS","cL_ETATCOMPTE":1,"cL_AlerteCompta":0},
{"idclient":2,"cL_CODE":"2","cL_NOM":"A UTOMATISMES-SERVICESzzzz","cL_ADRESSE":null,"cL_CODEPOS":"97420","cL_VILLE":"LEPORT","cL_ETATCOMPTE":1,"cL_AlerteCompta":0},
what i'm doing wrong ?
You need to create your own Json Profile Formatter by inheriting from JsonOutputFormatter.
public class PascalCaseJsonProfileFormatter : JsonOutputFormatter
{
public PascalCaseJsonProfileFormatter() : base(new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }, ArrayPool<char>.Shared)
{
SupportedMediaTypes.Clear();
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse
("application/json;profile=\"https://en.wikipedia.org/wiki/PascalCase\""));
}
}
Then modify your Startup.cs file's ConfigureServices Method like this.
services.AddMvc()
.AddMvcOptions(options =>
{
options.OutputFormatters.Add(new PascalCaseJsonProfileFormatter());
});
Try this, it should work.

Do I need set primary key in join table? MVC many to many relationship

As in question: is primary key in join table needed?
I have job table:
public partial class Job
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Job()
{
this.Room = new HashSet<Room>();
}
public int JobID { get; set; }
public string Title { get; set; }
public Nullable<int> DepartmentID { get; set; }
public virtual Department Department { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Room> Room { get; set; }
}
And user table:
public partial class AspNetUsers
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public AspNetUsers()
{
this.Department = new HashSet<Department>();
}
public string Id { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<int> PhoneNo { get; set; }
public Nullable<System.DateTime> HireDate { get; set; }
public Nullable<System.DateTime> BirthDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Department> Department { get; set; }
}
Every user can be in few departments, and every deparment can have many users.
In my controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Praca.Models;
using Praca.ViewModels;
namespace Praca.Controllers
{
public class EmployeeController : Controller
{
private Entities1 db = new Entities1();
// GET: Employee
public ActionResult Index(string id)
{
var viewModel = new AspNetUserDepartmentVM();
viewModel.AspNetUsers = db.AspNetUsers
.Include(i => i.Department)
.OrderBy(i => i.LastName);
if (id != null)
{
ViewBag.EmployeeID = id;
viewModel.Departments = viewModel.AspNetUsers.Where(
i => i.Id == id).Single().Department;
}
return View(viewModel);
}
// GET: Employee/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
// GET: Employee/Create
public ActionResult Create()
{
return View();
}
// POST: Employee/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName,FirstName,LastName,PhoneNo,HireDate,BirthDate")] AspNetUsers aspNetUsers)
{
if (ModelState.IsValid)
{
db.AspNetUsers.Add(aspNetUsers);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(aspNetUsers);
}
// GET: Employee/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers
.Include(i => i.Department)
.Where(i => i.Id == id)
.Single();
PopulateAssignedCourseData(aspNetUsers);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
private void PopulateAssignedCourseData(AspNetUsers aspNetUsers)
{
var allCourses = db.Department;
var instructorCourses = new HashSet<int>(aspNetUsers.Department.Select(c => c.DepartmentID));
var viewModel = new List<AssignedDepartment>();
foreach (var course in allCourses)
{
viewModel.Add(new AssignedDepartment
{
DepartmentID = course.DepartmentID,
DepartmentName = course.DepartmentName,
Assigned = instructorCourses.Contains(course.DepartmentID)
});
}
ViewBag.Courses = viewModel;
}
// POST: Employee/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string id, string[] selectedCourses)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var instructorToUpdate = db.AspNetUsers
.Include(i => i.Department)
.Where(i => i.Id == id)
.Single();
if (TryUpdateModel(instructorToUpdate, "",
new string[] { "LastName"}))
{
try
{
UpdateInstructorCourses(selectedCourses, instructorToUpdate);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
}
private void UpdateInstructorCourses(string[] selectedCourses, AspNetUsers instructorToUpdate)
{
if (selectedCourses == null)
{
instructorToUpdate.Department = new List<Department>();
return;
}
var selectedCoursesHS = new HashSet<string>(selectedCourses);
var instructorCourses = new HashSet<int>
(instructorToUpdate.Department.Select(c => c.DepartmentID));
foreach (var course in db.Department)
{
if (selectedCoursesHS.Contains(course.DepartmentID.ToString()))
{
if (!instructorCourses.Contains(course.DepartmentID))
{
instructorToUpdate.Department.Add(course);
}
}
else
{
if (instructorCourses.Contains(course.DepartmentID))
{
instructorToUpdate.Department.Remove(course);
}
}
}
}
// GET: Employee/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
// POST: Employee/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
db.AspNetUsers.Remove(aspNetUsers);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}`
Unfortunately I have error: Unable to update the EntitySet 'AspNetUsersDepartment' because it has a DefiningQuery and no element exists in the element to support the current operation.
How can I solve this problem?
When i set primary key on that table, there is no many to many relationship but two one to many's relations.
OK. I have figuerd it out for myself..
If anyone also have this kind of problem:
You have to set primary keys, but not as separate value in your table.
In my case
CONSTRAINT [PK_dbo.AspNetUserDepartment] PRIMARY KEY CLUSTERED ([EmployeeId] ASC, [DepartmentId] ASC),
works perfectly.

ASP.NET json object doesn't contain custom object

When a user gets to a location, he will get a question. As such, I have a class for "Questions" and a class for "Locations". When I retrieve a location, however, the Question parameter is always null.
This seems to be a problem with the whole project, as the same problem repeats itself somewhere else (here, a "Game" has a list of "Teams", but the teams are always empty).
Objects are created when database is initialized:
public static void Initialize(DBContext context)
{
context.Database.EnsureCreated();
if (!context.Games.Any())
{
var teams = new List<Team>();
var team1 = new Team()
{
TeamName = "Kwizmasterz",
TotalPoints = 0,
TotalBoobyTraps = 2
};
var team2 = new Team()
{
TeamName = "Xesennettet",
TotalPoints = 0,
TotalBoobyTraps = 2
};
teams.Add(team1);
teams.Add(team2);
var game = new Game()
{
GameCode = "X35H0",
team = teams
};
context.Games.Add(game);
context.SaveChanges();
}
if (!context.Locations.Any())
{
var que = new Question()
{
QuestionText = "How much is 2 + 2?",
Answer = "4",
IsSolved = false,
Points = 1000000
};
var loc = new Location()
{
LocationName = "LocationName",
Latitude = 50.2299036,
Longitude = 5.4163052,
Question = que,
IsBoobyTrapped = false
};
context.Locations.Add(loc);
context.SaveChanges();
}
}
Location Class:
public class Location
{
public int LocationID { get; set; }
public string LocationName { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public Question Question { get; set; }
public bool IsBoobyTrapped { get; set; }
public int VictorTeamID { get; set; } = -1;
}
Question Class:
public class Question
{
public int QuestionID { get; set; }
public int QuestionType { get; set; } // 1 = Question - Answer
public string QuestionText { get; set; }
public int Points { get; set; }
public bool IsSolved { get; set; }
public string Answer { get; set; }
}
Controller Class:
[Route("api/v1")]
public class GameController : Controller
{
private readonly DBContext context;
public GameController(DBContext context)
{
this.context = context;
}
public IActionResult Index()
{
return View();
}
[Route("location")]
[HttpPost]
public IActionResult postGame([FromBody] Location newLocation)
{
newLocation.LocationID = context.Games.Count();
context.Locations.Add(newLocation);
return Created("", newLocation);
}
[Route("location")]
[HttpGet]
public List<Location> getLocations()
{
return context.Locations.ToList();
}
[Route("location/{id}")]
[HttpGet]
public Location getLocation(int id)
{
int _id = id - 1;
List<Location> loc = context.Locations.ToList();
if (loc[_id] != null)
return loc[_id];
else
return null;
}
[Route("game")]
[HttpPost]
public IActionResult postGame([FromBody] Game newGame)
{
newGame.GameID = context.Games.Count();
context.Games.Add(newGame);
return Created("", newGame);
}
[Route("game")]
[HttpGet]
public List<Game> getGames()
{
return context.Games.ToList();
}
[Route("game/{id}")]
[HttpGet]
public Game getGame(int id)
{
List<Game> game = context.Games.ToList();
if (game[id] != null)
return game[id];
else
return null;
}
}
This is because of lazy loading so objects stored in other tables won't load unless you include them.
Link
You can do this by using Include("Question") so the complete syntax would be:
context.Locations.Include("Question") so you will include the question when retrieving the locations
You can do also multiple includes by chaining them context.Locations.Include("Question").Include("SomethingElse")
Edit as i see in your code getLocation still does not use the include. see below for the correct way to use it
public Location getLocation(int id)
{
int _id = id - 1;
List<Location> loc = context.Locations.Include("Question").ToList();
if (loc[_id] != null)
return loc[_id];
else
return null;
}
2nd edit
Also i would rewrite getLocation because your pulling the whole list first and after getting the single location
public Location getLocation(int id)
{
int _id = id - 1;
//FirstOrDefault will return automatically a null if the id cannot be found.
//This will result in only getting the single Location from context instead the complete list
return context.Locations.Include("Question").FirstOrDefault(x=>x.id == _id);
}

Can't receive the value of selectec item from Radio Button

So, I'm trying to do a online pool but I cant receive the value of selected item...
If someone can help me here is my Controller:
public async Task<IActionResult> Vote(int id, string text)
{
using (var poolDbContext = new PoolContext())
{
var Voted = new Vote();
var queq = new Answer { Id = id, Text = text };
// var Question = await poolDbContext.Questions.Include(s => s.Answers).AsNoTracking().SingleOrDefaultAsync(m => m.Id == id);
var Question = await poolDbContext.Questions.Include(A => A.Answers).AsNoTracking().SingleOrDefaultAsync(r => r.Id == r.Id);
if (Question == null)
{
return NotFound();
}
return View(Question);
}
}
[HttpPost, ActionName("Vote")]
[ValidateAntiForgeryToken]
public ActionResult VotePost(Question question)
{
try
{
if (ModelState.IsValid)
{
using (var poolDbContext = new PoolContext())
{
var id = question.Id.ToString();
var qId = question.Id;
var selectedAnswer = question.SelectedAnswer;
poolDbContext.SaveChanges();
// Save the data
return RedirectToAction("Index");
}
}
return View(question);
}
catch (DbUpdateException /* ex */)
{
ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator.");
}
return View();
}
And also here are my Question Model:
public class Question
{
public Question()
{
Answers = new List<Answer>();
}
public int Id { get; set; }
public string Text { get; set; }
public virtual List<Answer> Answers { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public Boolean Active { get; set; }
public string SelectedAnswer { set; get; }
}
Here is my Answer Model:
public class Answer
{
public int Id { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public List<Vote> Votes { get; set; }
}
And here is my Vote Model
public int Id { get; set; }
public string IpAdress { get; set; }
public DateTime VoteDate { get; set; }
public List<Question> Questions { set; get; }
public Vote()
{
Questions = new List<Question>();
}
}
My objective right now is to receive the vote from the Vote.Cshtml by the way here it is :
#model PoolManager.Models.Question
<div>
#Html.HiddenFor(x => x.Id)
<h3> #Model.Text </h3>
#foreach (var a in Model.Answers)
{
<p>
#Html.RadioButtonFor(b => b.SelectedAnswer, a.Id) #a.Text
#Model.SelectedAnswer
</p>
<input type="submit" />
}
So my objective is to receive the vote for each question and add the vote to the db, I don't know what i'm doing wrong..

How to get sum of all items?

I'm trying to get sum of all items of cars. But i'm just getting sum of each items, which you can see here Link
So how can I get sum of all items, like the sum is (4), instead of getting each items?
Controller:
public ActionResult Home()
{
var model = new CompositeModel();
model.CountCars = getCountOfCars();
return View(model);
}
private IEnumerable<CountCarsrCountView> getCountOfCars()
{
var countCars = this.Data.Cars.All()
.Select(t => new CountCarsrCountView
{
counter = t.Cars.Count()
});
return countCars ;
}
ViewModel
public class CountCarsViewModel
{
public int counter { get; set; }
}
CompositeModel
public class CompositeModel
{
public IEnumerable<CountCarsViewModel> CountCars { get; set; }
}
View
#model CompositeModel
<div class="container">
#for (int i = 0; i < Model.CountCarsViewModel.Count(); i++)
{
var cars = Model.CountCarsViewModel.ElementAt(i);
<p>#cars.counter</p>
}
</div>
Car model:
public class Car
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Price { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
public int FilePathId { get; set; }
public string FileName { get; set; }
public string UserId { get; set; }
public virtual User Users { get; set; }
}
You can use Linq as so:
public class MyItem
{
public int MyCount { get; set; }
}
public List<MyItem> AllItems { get; set; }
In this example if you want the count of all items in the list you would do this:
var count = AllItems.Count();
If you wanted to sum the Counts of all items in the list you would do this:
var count2 = AllItems.Sum(a => a.MyCount);
Example:
AllItems = new List<UserQuery.MyItem>()
{
new MyItem(){ MyCount = 3 },
new MyItem(){ MyCount = 4 },
};
var count = AllItems.Count(); // This would be 2
var count2 = AllItems.Sum(a => a.MyCount); // This would be 7

Resources