c# linq SELECT list inside another list - javascript

Here My Classes
public class EmployeeProjectMaster
{
public int EmployeeProjectMasterId { get; set; }
//Class Variables
//Here i wants to get list of EmployeeProjectTransaction
//this is the way i tried
public EmployeeProjectMasterModelClient()
{
this.EmployeeProjectTransactionModel = new HashSet<EmployeeProjectTransactionModelClient>();
}
public virtual IEnumerable<EmployeeProjectTransactionModelClient> EmployeeProjectTransactionModel { get; set; }
}
public class EmployeeProjectTransaction
{
public int EmployeeProjecTransactiontId { get; set; }
public int EmployeeProjectMasterId { get; set; }
public int EmployeeId { get; set; }
public string EmployeeName {get;set;}
//Class Variables
}
public class Employee
{
public int EmployeeId { get; set; }
public string Employeefullname {get;set;}
}
Then here my linq query
//Get All Employee Project Details To Grid
public ActionResult GetAllEmployeeProjectDetails()
{
//DataTable Parameter
var draw = Request.Form.GetValues("draw").FirstOrDefault();
//Paging parameter
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//Paging parameter
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
//filter parameter
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
List<EmployeeProjectMasterModelClient> allEmployeeProject = new List<EmployeeProjectMasterModelClient>();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
//Database Query
using (InnoESolutionsDbEntities oInnoESolutionsDbEntities = new InnoESolutionsDbEntities())
{
var v = (from Epmm in oInnoESolutionsDbEntities.EmployeeProjectMasterModels
join Eptm in oInnoESolutionsDbEntities.EmployeeProjectTransactionModels
on Epmm.EmployeeProjectMasterId equals Eptm.EmployeeProjectMasterId
select new {Epmm, Eptm});
if (!string.IsNullOrEmpty(searchValue))
{
v = v.Where(b =>
b.Epmm.ProjectModel.ProjectName.Contains(searchValue)
);
}
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
//for make sort simpler we will add system.linq.dynamic reference
//v = v.OrderBy(sortColumn + " " + sortColumnDir);
v = v.OrderBy(a => a.Epmm.EmployeeProjectMasterId + " " + a.Eptm.EmployeeProjectMasterId);
}
recordsTotal = v.Count();
allEmployeeProject = v.Skip(skip).Take(pageSize).Where(y => y.Epmm.IsActive && !y.Epmm.IsDelete && y.Eptm.IsActive && !y.Eptm.IsDelete).Select(x => new EmployeeProjectMasterModelClient
{
EmployeeProjectMasterId = x.Epmm.EmployeeProjectMasterId,
ProjectId = x.Epmm.ProjectId,
ProjectName = x.Epmm.ProjectModel.ProjectName,
WorkDateS = SqlFunctions.DateName("day", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("month", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("year", x.Epmm.WorkDate),
SalaryForEachEmployee = x.Epmm.SalaryForEachEmployee,
EmployeeProjectTransactionModel = *************************************How to Load Trnsaction Details As A list Here
}).ToList();
}
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = allEmployeeProject });
}
Above c# function and Linq query for load angular data table. it's needs to select List Inside a List. i Wrote linq query for join. I don't know whether If it is correct or not.when you answer my question please consider that query. Have tried lot of time but i have failed. in query when i try to get record into allEmployeeProject . how to load transaction Details As a list inside allEmployeeProject list asterisk symbol indicates what i need to do. i wants list of employee for particular master record.
Here output what i want
MasterId | TransactionId |Employee Id | Employee Name
---------+---------------+------------+---------------
1 | 1 | 4 | name 1
| 2 | 2 | name 3

I think what you need is GroupBy method.
allEmployeeProject = v.Skip(skip).Take(pageSize).Where(y => y.Epmm.IsActive && !y.Epmm.IsDelete && y.Eptm.IsActive && !y.Eptm.IsDelete).Select(x => new EmployeeProjectMasterModelClient
{
EmployeeProjectMasterId = x.Epmm.EmployeeProjectMasterId,
ProjectId = x.Epmm.ProjectId,
ProjectName = x.Epmm.ProjectModel.ProjectName,
WorkDateS = SqlFunctions.DateName("day", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("month", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("year", x.Epmm.WorkDate),
SalaryForEachEmployee = x.Epmm.SalaryForEachEmployee
});
var allEmployeeProjectsByMaster = allEmployeeProject.GroupBy(x => x.EmployeeProjectMasterId).ToList();
Now you can have transaction list grouped by EmployeeProjectMaster with allEmployeeProjectsByMaster variable, just map it to relevant data model using Select.

Related

Angular 8:mat pagination can not choose page

My mat-paginator in app.component.html:
<mat-paginator [pageSizeOptions]="[5, 15, 30]" [pageSize]="5" [length]="totalElements"
(page)="nextPage($event)">
</mat-paginator>
app component:
totalElements = 5;
// tslint:disable-next-line:typedef
nextPage(event: PageEvent) {
const request = {};
// #ts-ignore
request.page = event.pageIndex.toString();
// #ts-ignore
this.totalElements = request.size = event.pageSize.toString();
// #ts-ignore
this.getDevelopers(request);
}
getDevelopers:
public getDevelopers(request: {page: string, size: string}): void {
this.loading = true;
this.developerService.getAllUsers(request)
.subscribe(data => {
// #ts-ignore
this.users = data.content;
// #ts-ignore
this.totalElements = data.totalElements;
this.loading = false;
}
}
My controller:
#GetMapping
#ResponseBody
#ApiOperation(value = "Get list of all developers")
public Page<GetByIdDeveloperResponse> getAllDevelopers(
#RequestParam(name = "page", defaultValue = "0") int page,
#RequestParam(name = "size", defaultValue = "4") int size,
#RequestParam(name = "sort_by", defaultValue = "id") String sortBy
) {
Page<GetByIdDeveloperResponse> developers = developerMapper.getDeveloperResponseListFromDeveloperList(developerService.getAllDevelopers(page, size, sortBy));
return new PageImpl<GetByIdDeveloperResponse>(developers.getContent(), PageRequest.of(page, size), developers.getTotalElements());
}
I can change size of page, but i can't open other page.
< > are not aviable for me
In postman everything in is ok, but here it doesn't work.
How looks my service method:
public List<Developer> getAllDevelopers(int page, int size, String sortValue) {
logger.info("Get all developers was called, page: " + page + " size: " + size + " sort by: " + sortValue);
Pageable paging = PageRequest.of(page, size, Sort.by(sortValue));
Page<Developer> pagedResult = developerRepository.findAll(paging);
return pagedResult.getContent();
}
How repository looks:
#Repository
public interface DeveloperRepository extends PagingAndSortingRepository<Developer, String> {
Developer findById(String id);
}
How json looks:
When i am trying to GET .../developers?size=10
I got 10 total elements, i think problem is related to "totalPages": 1,
Because even if i get all elements, there will be only 1 page
Debug:
You lose your paged result data (page number, page size, etc.) in your service method when you do return pagedResult.getContent().
Consider the following:
Service method:
public Page<Developer> getAllDevelopers(int page, int size, String sortValue) {
logger.info("Get all developers was called, page: " + page + " size: " + size + " sort by: " + sortValue);
Pageable paging = PageRequest.of(page, size, Sort.by(sortValue));
return developerRepository.findAll(paging);
}
Controller method:
#GetMapping
#ApiOperation(value = "Get list of all developers")
public Page<GetByIdDeveloperResponse> getAllDevelopers(
#RequestParam(name = "page", defaultValue = "0") int page,
#RequestParam(name = "size", defaultValue = "4") int size,
#RequestParam(name = "sort_by", defaultValue = "id") String sortBy
) {
return this.developerService.getAllDevelopers(page, size, sortBy)
.map(this.developerMapper::mapToGetByIdDeveloperResponse)
}

How to fix the DataTables not working after publish in IIS using MVC

I have a problem with my MVC App with datatables it not working after I publish it into IIS but when I run my source code it works
When I try to troubleshoot I found out something:
Here is my controller code for datatables:
public ActionResult LoadData()
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
//Paging Size (10,20,50,100)
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var customerData = (from tempcustomer in objCmp.ToList()
select tempcustomer);
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
customerData = customerData.OrderBy(sortColumn + " " + sortColumnDir);
}
if (!string.IsNullOrEmpty(searchValue))
{
customerData = customerData.Where(m => m.FileAs.Contains(searchValue.ToUpper()) || m.ContactID.Contains(searchValue.ToUpper()) || m.Gender.Contains(searchValue.ToUpper()));
}
recordsTotal = customerData.Count();
var data = customerData.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
}
Hopefully you cant help me.

Attempting a Binary Search on a Object Array (Comparable)

I've been struggling a couple days now attempting to write this code. Basically,we have to perform a binarySearch based on the SSN of Comparable "Student" objects in a Student array. After performing the binarySearch on the SSN, the student who is associated with that SSN's first and last name should print out. I am finding difficulty in writing the binarySearch.
Here's my code so far:
my Student class:
public class Student implements Comparable<Student>{
private String firstName, lastName, SSN, bankAccount;
public Student(String first, String last, String ssn, String bkacct) {
this.firstName = first;
this.lastName = last;
this.SSN = ssn;
this.bankAccount = bkacct;
}
//toString method
public String toString() {
return "Employee: [FirstName = " + firstName + ", LastName = " + lastName + ", SSN = " + SSN + ", BankAccount = "
+ bankAccount + "]";
}
public boolean equals(Object other) {
return (lastName.equals(((Student)other).getLastName()) &&
firstName.equals(((Student)other).getFirstName())&&
SSN.equals(((Student)other).getSSN()) &&
bankAccount.equals(((Student)other).getBankAccount()));
}
//Sorting the array based on SSN
public int compareTo(Student target) {
int result;
if (lastName.equals(target.getLastName()))
result = SSN.compareTo((String) target.getSSN());
else
result = SSN.compareTo((String) target.getSSN());
return result;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Object getSSN() {
return SSN;
}
public String getBankAccount() {
return bankAccount;
}
and my class where i perform my binarySearch
public class ObjectBubbleSortTest {
//setting up binarySearch to find Array
public static <Student extends Comparable<Student>> int binarySearch(Student[] student, Student target) {
int low = 0;
int high = student.length - 1;
int middle = (low+high + 1)/2;
int location = -1;
while((low <= high) && (location == -1)) {
if (student[middle].compareTo(target) == 0 ) {
location = middle;
}
else if (student[middle].compareTo(target) < 0) { //middle element too high
high = middle - 1;
}
else {
low = middle + 1;
}
middle = (low + high + 1)/2;
}
return location;
}
public static void main(String[] args) {
//EMPLOYEES OF BURGER KING
Student[] student = new Student[5];
//order: First Name, Last Name, SSN, Bank_Account_Number
student[0] = new Student("Adam", "Sarrone", "1234567", "9022345");
student[1] = new Student("Ryan", "Petrowvoksi", "4345123", "0120345");
student[2] = new Student("Jenn", "Henderson", "8124512", "564214");
student[3] = new Student("Ricky", "Jean", "3512345", "612345");
student[4] = new Student("Dare", "Ogun", "421451", "198213");
System.out.println("Original array order: \n");
for (Student element : student)
System.out.print(element + "\n");
ObjectBubbleSorter.bubbleSort(student);
System.out.println();
System.out.println("\nSorted array order: \n");
for (Student element : student)
System.out.print(element + "\n");
System.out.println();
//need helping figuring out why the binary search is not printing out
int studentName = binarySearch(student, "421451");
System.out.print(studentName);
}
}
I am also getting an error on "int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String). I understand what it means but struggling to make my binarySearch adaptable to fix that error.
Any help would be greatly appreciated. Thank you.
It would be clear if you read the error message once again carefully.
"int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String).
So basically the method signature you have is int binarySearch(Student[] student, Student target), but when you call it in main() it's binarySearch(student, "421451");
You may want to instead call the method like binarySearch(student, student[4]);

How to send an object array from c# to javascript?

Im trying to send an array that contains some objects via connection made in SignalR, the connection is not a problem, everything works fine. When the data arrives to the view it is no longer the array i need to use.
This is the class:
public class Empresa
{
public string nombre { get; set; }
public int vidID { get; set; }
public string img64 { get; set; }
public string color { get; set; }
}
At the end the object will be something like this:
The object is send to the view and this is the output:
I have already tried with JsonConvert.SerializeObjectas i found on other threads, yet it doesnt seems to work. I tried to convert the data send with this jQuery.parseJSON(data) (Left) and with this JSON.parse(data)(Right); it throws an error on both cases as seen in the picture below.
I'm not sure if it is that way because the object sended is made this way:
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
var data = new List<Empresa>
{
new Empresa{nombre ="Globex Corp",color="red",vidId=1, img="data:image/jpeg;base64,blabla" },
new Empresa{nombre ="AM",color="blue",vidId=2, img="data:image/jpeg;base64,blabla" }
}
for(int i = 0; i<=6; i++)
{
_ar1.TryAdd(data[i].vidID, data[i]);
}
This is inside other function but it is the next one that involves the data send.
public IEnumerable<Empresa> GetArreglo()
{
return _ar1;
}
So far im not sure what could be wrong or if i need to aproach a different solution.
If any more info is needed ill post it. And even it is obvious im a newby still learning on this.
EDIT:
This is all the code involved:
// This is the JS
<script>
var ubi = '#ViewBag.ubicacion';
console.log("UbicaciĆ³n: " + ubi);
var conex = $.connection.channel;
var $marco = $('#marco');
var $imagen = $('#imagen');
var $empresa = $('#empresa');
function empezar() {
var min;
var max;
var pos;
var arreglo = new Array;
function init() {
conex.server.createGroup(ubi);
console.log("Entro al canal");
arreglo = conex.server.getArreglo(ubi);
//pos = arreglo.split('|');
//a.split is not a function
console.log(arreglo);
//console.log(pos);
setInterval(update, 6000);
}
function update() {
}
$.connection.hub.start().done(init);
}
window.onload = function() { empezar(); }
</script>
//It gets the conection to the HUB:
[HubName("channel")]
public class CanalHub : Hub
{
private readonly Canal _canal;
public CanalHub() : this(Canal.Instance) { }
public CanalHub(Canal canal)
{
_canal = canal;
}
public string[] GetArreglo(string ubi)
{
string[] array = _canal.GetArreglo(ubi);
return array;
//it is now a string[] because i wanted to
//try creating the obj with .split('|')
}
// And finally this is the last part involved:
public class Canal
{
private static Random random = new Random();
private volatile List<Canales> listaCan = new List<Canales>();
private readonly static Lazy<Canal> _instance = new Lazy<Canal>(() => new Canal(GlobalHost.ConnectionManager.GetHubContext<CanalHub>().Clients));
private readonly ConcurrentDictionary<int, Empresa> _datos = new ConcurrentDictionary<int, Empresa>();
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
private Canal(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
//Create the sample objects for the class
var datos = new List<Empresa>
{
new Empresa{nombre="Globex Corp", color="#A87F3D", vidID=1, img="balbal" },
new Empresa{nombre="AM", color="#535E89", vidID=2, img="balba" },
new Empresa{nombre="Frutijugos", color="#92191A", vidID=3, img="askldj" }
};
for (int i = 0; i <=6 ; i++)
{
_ar1.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 7; i <= 13; i++)
{
_ar2.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 14; i <= 20; i++)
{
_ar3.TryAdd(datos[i].vidID, datos[i]);
}
//sort them on 3 different arrays
}
private IHubConnectionContext<dynamic> Clients { get; set; }
public static Canal Instance
{
get { return _instance.Value; }
}
public string[] GetArreglo(string ubi)
{
string[] array = new string[7];
int i = 0;
if (ubi == "Campanario")
{
foreach (var item in _ar1)
{
array[i] += item.Value.nombre + "|";
array[i] += item.Value.color + "|";
array[i] += item.Value.img + "|";
array[i] += item.Value.vidID + "|";
i++;
}
return array;
}
//sort the array values and add them to the array
else return null;
}
It appears that your javascript promise is not set up correctly. The object in the view is the promise object and not the object returned. You are going to need to set up the promise correctly. deferred promise

Adding element with jquery to empty list

Hi I need to add items to list, it works when the list have elements but when list is empty javascript return undefined.
this is my function: namevalue is undefined when list is empty I think its main problem.
function submitAjaxForm(formId)
{
var form = $("<form></form>");
var targetID = formId.substr(1);
form.append($(formId).html());
var nameValue = $(formId).find('.showDictionariesList').first().find('input[type="hidden"]').first().attr('name');
var indexToCut = nameValue.indexOf('[', nameValue.indexOf('[', 0) + 1);
var featureIndex = nameValue.substring(0, indexToCut);
var contentVal = $("#dropDownList option:selected").val();
var returnValue = form.serializeArray();
returnValue[returnValue.length - 1].value = contentVal;
}
This list
public List<ShowDictionaryModel> ShowDictionaries { get; set; }
class of this items:
public class ShowDictionaryModel
{
public long Id { get; set; }
public string Value { get; set; }
public long? ProductId { get; set; }
public string FeatureId { get; set; }
internal static ShowDictionaryModel FromDto(DictionaryDto dto)
{
ShowDictionaryModel model = new ShowDictionaryModel();
model.Id = dto.Id;
model.Value = dto.Value;
model.ProductId = dto.ProductId;
model.FeatureId = dto.FeatureId;
return model;
}
}
Cshtml code: showDictionariesList is class who contains the list what i want to modify
#model MultiShop.Panel.Models.Product.AddProductFeatureTextModel
<div>
<div id="featureText-#Model.TypeId">
#Html.HiddenFor(m => m.TypeId)
#Html.HiddenFor(m => m.IsRequired)
#Html.HiddenFor(m => m.Name)
#Html.Label(Model.Name)
#Html.TextBoxFor(m => m.Value)
#if (Model.IsRequired)
{
<span class="requiredField"></span>
}
#Html.ValidationMessageFor(m => m.Value)
<div class="showDictionariesList">
#Html.EditorFor(m => m.ShowDictionaries)
</div>
#Html.DropDownListFor(m => m.SelectedDictionaryItemId, new SelectList(Model.DictionaryItems, "Id", "Value", Model.SelectedDictionaryItemId), new { id = "dropDownList" })
<input type="button" value="Save" onclick="#("submitAjaxForm('#featureText-" + #Model.TypeId + "')")" />
</div>
//}
your problem that youre trying to get attribute on non existing object
you should get it after check
var container = $(formId).find('.showDictionariesList').first();
var nameValueObj = container.find('input[type="hidden"]').first();
if (nameValueObj.length !== 0){
// input was found so we can get name attribute
var nameValue= nameValueObj.attr('name');
var indexToCut = nameValue.indexOf('[', nameValue.indexOf('[', 0) + 1);
// .........
} else{
// as far no input elements inside .showDictionariesList your logic to add first one item
// container.append(
}
I got answer for it. I just initialize list with basic element if is null. My experience with programming is very low so my code look bad but it works as I want.
if (!dictionaryType.HasItems())
{
DictionaryDto newForEmptyList = new DictionaryDto();
List<DictionaryDto> newList = new List<DictionaryDto>();
newForEmptyList.FeatureId = type;
newForEmptyList.ProductId = productId;
newForEmptyList.Value = "";
newForEmptyList.Id = -1;
newList.Add(newForEmptyList);
dictionaryType = newList.ToArray();
}

Categories