LINQ2SQL - FirstItem - linq-to-sql

How do you get the first item only? It seems like I have to do the following otherwise i will get an error as if it was a multiple item and i can't get just the first element of it.
My goal is i would like to remove the foreach loop from the code below.
MetaDataPropertyBag propertyBag = new MetaDataPropertyBag();
var dbResultsOfType = db.spi_GetTypesByCaseType(caseType);
foreach (var item in dbResultsOfType)
{
if (item.ASSOC_TYPE_ID == primaryChildTypeID)
{
propertyBag.CaseTypeDesc = item.DESCRIPTION;
propertyBag.Required = item.IS_REQUIRED == 'Y' ? true : false;
propertyBag.Parent = item.PARENT_ID.Value;
propertyBag.Child = item.CHILD_ID.Value;
propertyBag.AssocTypeID = item.ASSOC_TYPE_ID;
propertyBag.CaseTypeID = item.CASE_TYPE_ID;
break; // Only one entry is requested
}
}

FirstorDefault should do it:
MSDN article on firstordefault

Here is one way to do it:
var first = dbResultsOfType.FirstOrDefault(item => item.ASSOC_TYPE_ID == primaryChildTypeID);
if (first != null) {
propertyBag.CaseTypeDesc = first.DESCRIPTION;
propertyBag.Required = first.IS_REQUIRED == 'Y' ? true : false;
propertyBag.Parent = first.PARENT_ID.Value;
propertyBag.Child = first.CHILD_ID.Value;
propertyBag.AssocTypeID = first.ASSOC_TYPE_ID;
propertyBag.CaseTypeID = first.CASE_TYPE_ID;
}

Related

Laravel Query builder returns a row from join instead of multiples row

I am getting fewer results than expected , The data returns 57 rows instead of 70 rows. I need help to get all the rows please, I returned a collection using get(), and i joined it with foreach() to include the rows to existing query, Please any help?
public function getempAttendance(Request $request) {
$id = $request->id;
$department_id = $request->department_id;
if($id !== null){ //return based on type;
$emp = AsEmployee::where('id','=',$id)->orderBy('id','ASC')->get();
} else if($department_id != null){
$emp = AsEmployee::where('department_id','=',$department_id)->orderBy('id','ASC')->get();
} else{ //return all if nothing is given;
$emp = AsEmployee::orderBy('id','DESC')->get();
}
foreach($emp as $emp_data){
$department = AsDepartment::where('id','=',$emp_data->department_id)->get(['department'])->first();
if($department !== NULL){
$emp_data->department_name = $department->department;
}else{
$emp_data->department_name = '';
}
$position = AsEmployeePosition::where('id','=',$emp_data->position_id)->get(['position_name'])->first();
if($position !== NULL){
$emp_data->position_name = $position->position_name;
}else{
$emp_data->position_name = '';
}
$attendances = AsAttendanceLog::select('CHECK_IN_TIME','CHECK_OUT_TIME')
->where('EMPLOYEE_ID','=',$emp_data->employee_id)->get();
if($attendances !== NULL){
foreach($attendances as $attendance){
$emp_data->CHECK_IN_TIME = Carbon::parse($attendance->CHECK_IN_TIME)->toTimeString();
$emp_data->CHECK_OUT_TIME = Carbon::parse($attendance->CHECK_OUT_TIME)->toTimeString();
$emp_data->Date = Carbon::parse($attendance->CHECK_IN_TIME)->format('Y-m-d');
$hours = Carbon::parse($attendance->CHECK_OUT_TIME)->diffInSeconds(Carbon::parse($attendance->CHECK_IN_TIME));
$emp_data->Hours = gmdate('H:i', $hours);
}
}else {
$emp_data->CHECK_IN_TIME = '';
$emp_data->CHECK_OUT_TIME = '';
}
}
return $this->sendResponse($emp);
}
Meanwhile, this works but i need the query builder format to allow me use Carbon and do some operations
$attendanceData = DB::table('as_tbl_employee_master AS emp')
->leftJoin('as_tbl_department AS dept','emp.department_id','=', 'dept.id')
->leftJoin('as_tbl_employee_position AS pos', 'emp.position_id', '=', 'pos.id')
->leftJoin('as_tbl_emp_attendance_daily_log AS att', 'att.EMPLOYEE_ID', '=', 'emp.employee_id')
->select('emp.id','emp.employee_id','emp.english_name','dept.department','pos.position_name','att.CHECK_IN_TIME','att.CHECK_OUT_TIME')
->orderby('att.CHECK_IN_TIME', 'DESC')
->get();
return $this->sendResponse($attendanceData);
if the user's table is "one to many" to as_tbl_emp_attendance_daily_log's table.
You should select('as_tbl_emp_attendance_daily_log') first then left join to user's table.
I assumed that you want to show all as_tbl_emp_attendance_daily_log's row. If that right your Query builder should be like this.
$attendanceData = DB::table('as_tbl_emp_attendance_daily_log AS att')
->leftJoin('as_tbl_employee_master AS emp', 'att.EMPLOYEE_ID', '=', 'emp.employee_id')
->leftJoin('as_tbl_department AS dept','emp.department_id','=', 'dept.id')
->leftJoin('as_tbl_employee_position AS pos', 'emp.position_id', '=', 'pos.id')
->select('emp.id','emp.employee_id','emp.english_name','dept.department','pos.position_name','att.CHECK_IN_TIME','att.CHECK_OUT_TIME')
->orderby('att.CHECK_IN_TIME', 'DESC')
->get();
UPDATE
If you want to add the custom attribute to the model you should define it at the model.
This is for reference:
https://laravel.com/docs/5.1/eloquent-serialization#appending-values-to-json
But you can directly change the attribute if you change the collections to the array first.
I don't have your table, so I cannot test it, I just changed it based on your snippet.
public function getempAttendance(Request $request) {
$id = $request->id;
$department_id = $request->department_id;
if($id !== null){ //return based on type;
$emp = AsEmployee::where('id','=',$id)->orderBy('id','ASC')->toArray();
} else if($department_id != null){
$emp = AsEmployee::where('department_id','=',$department_id)->orderBy('id','ASC')->toArray();
} else{ //return all if nothing is given;
$emp = AsEmployee::orderBy('id','DESC')->toArray();
}
for($i=0;$i < count($emp); $i++){
$department = AsDepartment::where('id','=',$emp[$i]->department_id)->get(['department'])->first();
if($department !== NULL){
$emp[$i]['department_name'] = $department->department;
}else{
$emp[$i]['department_name'] = '';
}
$position = AsEmployeePosition::where('id','=',$emp[$i]['position_id'])->get(['position_name'])->first();
if($position !== NULL){
$emp[$i]['position_name'] = $position->position_name;
}else{
$emp[$i]['position_name'] = '';
}
$attendances = AsAttendanceLog::select('CHECK_IN_TIME','CHECK_OUT_TIME')
->where('EMPLOYEE_ID','=',$emp[$i]['employee_id'])->toArray();
$attendances_data = [];
if($attendances !== NULL){
for($j=0;$j<count($attendances);$j++){
$data = [];
$data['CHECK_IN_TIME'] = Carbon::parse($attendance['i']['CHECK_IN_TIME'])->toTimeString();
$data['CHECK_OUT_TIME'] = Carbon::parse($attendance['i']['CHECK_OUT_TIME'])->toTimeString();
$data['Date'] = Carbon::parse($attendance['i']['CHECK_IN_TIME'])->format('Y-m-d');
$hours = Carbon::parse($attendance['i']['CHECK_OUT_TIME'])->diffInSeconds(Carbon::parse($attendance['i']['CHECK_IN_TIME']));
$data['Hours'] = gmdate('H:i', $hours);
$attendances_data[] = $data
}
$emp[$i]['attendances'] = $attendances_data;
}else {
$emp[$i]['attendances'] = [];
$emp[$i]['attendances'] = [];
}
}
return $this->sendResponse($emp);
}
UPDATE
If you want to multiple row, I think you should try this:
$attendanceData = DB::table('as_tbl_emp_attendance_daily_log AS att')
->leftJoin('as_tbl_employee_master AS emp', 'att.EMPLOYEE_ID', '=', 'emp.employee_id')
->leftJoin('as_tbl_department AS dept','emp.department_id','=', 'dept.id')
->leftJoin('as_tbl_employee_position AS pos', 'emp.position_id', '=', 'pos.id')
->select('emp.id','emp.employee_id','emp.english_name','dept.department','pos.position_name','att.CHECK_IN_TIME','att.CHECK_OUT_TIME')
->orderby('att.CHECK_IN_TIME', 'DESC')
->toArray();
for($i=0;$i<count($attendaceData);$i++)
{
$attendaceData[$i]['CUSTOM VARIABLE'] = 'NEW VALUE CUSTOM VARIABLE AT HERE';
}
return $this->sendResponse($emp);

Error when trying to set Google Forms quiz score

I'm trying to change the grade of a response based on its answer.
Here's the code I'm using:
function myFunction() {
var form = FormApp.openById('formID123456');
// For a question with options: "1", "2", "3", and "4",
// award points for responses that correlate with their answers.
var formResponses = FormApp.getActiveForm().getResponses();
// Go through each form response
for (var i = 0; i < formResponses.length; i++) {
var response = formResponses[i];
var items = FormApp.getActiveForm().getItems();
// Assume it's the first item
var item = items[0];
var itemResponse = response.getGradableResponseForItem(item);
// Give 4 points for "4".
if (itemResponse != null && itemResponse.getResponse() == '4') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 4);
}
// Give 3 points for "3".
else if (itemResponse != null && itemResponse.getResponse() == '3') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 3);
}
// Give 2 points for "2".
else if (itemResponse != null && itemResponse.getResponse() == '2') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 2);
}
// Give 1 points for "1".
else if (itemResponse != null && itemResponse.getResponse() == '1') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 1);
// This saves the grade, but does not submit to Forms yet.
response.withItemGrade(itemResponse);
}
}
// Grades are actually submitted to Forms here.
FormApp.getActiveForm().submitGrades(formResponses);
}
This returns the error:
We're sorry, a server error occurred. Please wait a bit and try again. (line 23, file "Code")
It seemed like it was having issues changing the score of the response, but it didn't return a specific error, so I tried to isolate the part that changes the score.
Here, the script attempts only to change the score of the response.
function myFunction() {
var form = FormApp.openById('formID123456');
var formResponses = FormApp.getActiveForm().getResponses();
// Go through each form response
for (var i = 0; i < formResponses.length; i++) {
var response = formResponses[i];
var items = FormApp.getActiveForm().getItems();
// Assume it's the first item
var item = items[0];
var itemResponse = response.getGradableResponseForItem(item);
// Set Score to 3
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 3);
}}
Again, it returned the same error, which confirms my suspicions. Why am I having this problem and how can I fix it? Any help would be much appreciated. Thanks!
As I mentioned in comments, your posted code erroneously uses a Boolean value in the call to ItemResponse#setScore, when the method expects to receive an Integer value.
Resolving the internal server error can be done by changing your entire if-elseif chain from this:
if (itemResponse != null && itemResponse.getResponse() == '4') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 4); //<--- 'points == 4' evaluates to True or False
}
// Give 3 points for "3".
else if (...
to this:
// Skip changing the score if there was no answer or the answer is "falsey"
if (!itemResponse || !itemResponse.getResponse())
continue;
var answer = itemResponse.getResponse();
var newPoints = answer *1; // Convert "2" to 2, etc.
// Assumption: newPoints <= maximum possible points.
itemResponse.setScore(newPoints);
response.withItemGrade(itemResponse);
The below code is an example of how to set all graded items in all responses to a form to their maximum possible value.
function everyonePassesForTrying() {
var form = FormApp.getActiveForm();
var responses = form.getResponses();
responses.forEach(function (fr) {
fr.getGradableItemResponses().forEach(function (gr) {
if (gr.getResponse()) {
var maxPoints = getPointValue_(gr.getItem());
if (gr.getScore() !== maxPoints) {
// Re-grade the item's response.
gr.setScore(maxPoints);
// Update the form response with the new grade.
fr.withItemGrade(gr);
}
}
else { /* They didn't even try, so no change */ }
});
});
// Submit the altered scores.
form.submitGrades(responses);
}
var itemCache = {};
function getPointValue_(item) {
var id = item.getId();
// Use a pseudo-cache of the item's point values to avoid constantly determining what
// type it is, casting to that type, and getting the max points.
if(!itemCache[id]) {
// Haven't seen it yet, so cast and cache.
item = castToType_(item);
itemCache[id] = {maxPoints: item.getPoints() *1};
}
return itemCache[id].maxPoints;
}
function castToType_(item) {
// Cast the generic item to its type.
var CHECKBOX = FormApp.ItemType.CHECKBOX,
DATE = FormApp.ItemType.DATE,
DATETIME = FormApp.ItemType.DATETIME,
DURATION = FormApp.ItemType.DURATION,
LIST = FormApp.ItemType.LIST,
MULTICHOICE = FormApp.ItemType.MULTIPLE_CHOICE,
PARAGRAPH = FormApp.ItemType.PARAGRAPH_TEXT,
SCALE = FormApp.ItemType.SCALE,
TEXT = FormApp.ItemType.TEXT,
TIME = FormApp.ItemType.TIME;
switch (item.getType()) {
case CHECKBOX: item = item.asCheckboxItem();
break;
case DATE: item = item.asDateItem();
break;
case DATETIME: item = item.asDateTimeItem();
break;
case DURATION: item = item.asDurationItem();
break;
case LIST: item = item.asListItem();
break;
case MULTICHOICE: item = item.asMultipleChoiceItem();
break;
case PARAGRAPH: item = item.asParagraphTextItem();
break;
case SCALE: item = item.asScaleItem();
break;
case TEXT: item = item.asTextItem();
break;
case TIME: item = item.asTimeItem();
break;
default:
throw new Error("Unhandled gradable item type '" + item.getType() + "'");
break;
}
return item;
}

query not displaying if another table has null value(sequence contains no elements)

I have a problem with the following code. It displays details if all tables have at least one value, but nothing if at least one table does not have a value. I get the message
sequence contains no elements.
My code as follow:
public sneakerDetails GetSneakerDetails(int id)
{
IQueryable<sneakerDetails> query = from sneaks in _context.sneakers
from image in _context.sneakerImages
from website in _context.sneakerWebsites
// from website in _context.sneakerWebsites
where sneaks.sneaker_id == id && image.sneaker_id == website.sneaker_id && sneaks.sneaker_id == website.sneake_id
select new sneakerDetails
{
//sneaker_id = sneaks.sneaker_id,
Colorway = sneaks.Colorway,
Name = sneaks.Name,
description = sneaks.description,
imageAlternative = image.imageAlternative,
release_date = sneaks.release_date,
imageB = image.imageB,
imageF = image.imageF,
imageL = image.imageL,
imageR = image.imageR,
website = website.website,
websiteLogo = website.websiteLogo
};
return query.ToList().First();
I have tried to change the return value to FirstOrDefault but when i click a particular sneaker it displays only the title and no data.
Do i need to write an if statement for both tables?
Try with DefaultIfEmpty():
from sneaks in _context.sneakers.DefaultIfEmpty()
from image in _context.sneakerImages.DefaultIfEmpty()
from website in _context.sneakerWebsites.DefaultIfEmpty()
// from website in _context.sneakerWebsites
where sneaks.sneaker_id == id
&& image.sneaker_id == website.sneaker_id
&& sneaks.sneaker_id == website.sneake_id
select new sneakerDetails
{
//sneaker_id = sneaks.sneaker_id,
Colorway = sneaks.Colorway,
Name = sneaks.Name,
description = sneaks.description,
imageAlternative = image.imageAlternative,
release_date = sneaks.release_date,
imageB = image.imageB,
imageF = image.imageF,
imageL = image.imageL,
imageR = image.imageR,
website = website.website,
websiteLogo = website.websiteLogo
};

AS3 - sort arraycollection alpha numeric values

i'm trying to sort an arraycollection that uses letters and numbers
Currently I'm getting "b12,c1,b1,b3,b4,b5,b6,b7,b8,b9,b10,b11,b0,b13,b14,b15" but want "b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,c1"
Please can anyone suggest when're I have gone wrong?
var dataSortField:SortField = new SortField();
dataSortField.name = "order";
dataSortField.numeric = false;
dataSortField.compareFunction = sortAlphaNumeric;
var numericDataSort:Sort = new Sort();
numericDataSort.fields = [dataSortField];
pageArrCol.sort = numericDataSort;
private function sortAlphaNumeric(a:String, b:String):int {
var reA:RegExp = /[^a-zA-Z]/g;
var reN:RegExp = /[^0-9]/g;
var aA:String = a.replace(reA,"");
var bA:String = b.replace(reA,"");
if (aA === bA) {
var aN:int = parseInt(a.replace(reN,""),10);
var bN:int = parseInt(b.replace(reN,""),10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
myArrayCollectionToSort.source.sortOn("order", sortAlphaNumeric);
private function sortAlphaNumeric(a:String, b:String):int {
var reA:RegExp = /[^a-zA-Z]+/g;
var reN:RegExp = /[^0-9]+/g;
var aA:String = a.match(reA)[0];
var bA:String = b.match(reA)[0];
if (aA == bA) {
var aN:int = parseInt(a.match(reN)[0],10);
var bN:int = parseInt(b.match(reN)[0],10);
return aN == bN ? 0 : aN > bN ? 1 : -1;
}
return aA > bA ? 1 : -1;
}
I don't test it but it should works, and array is way faster than an ArrayCollection. (arraycollection.source is an array). If the sorted ArrayCollection is binded you need to dispatch a refresh event if you want the bind to works:
myArrayCollectionToSort.dispatchEvent(new CollectionEvent(CollectionEvent.COLLECTION_CHANGE, false, false, CollectionEventKind.REFRESH));
or
myArrayCollectionToSort.refresh();
Assuming that b12,c1,b1 is your input format
You may have meant, a.match(regex)[0]
var reA:RegExp = /[a-zA-Z]+/g;
var reN:RegExp = /[0-9]+/g;
var aA:String = a.match(reA)[0];
var bA:String = b.match(reA)[0];
if (aA === bA) {
var aN:int = parseInt(a.match(reN)[0],10);
var bN:int = parseInt(b.match(reN)[0],10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
}else {
return aA > bA ? 1 : -1;
}
I have not tested this, but you should not be using replace, use match instead. Also, the regular expression is wrong. You have to revisit the regular expression.

A conflict exists with definition newBox in namespace internal

function makeABox(e):void {
if (e.name == "seri1"){
var newBox:karo1 = new karo1();
}else if(e.name == "seri2"){
var newBox:karo2 = new karo2();
}else{
var newBox:zemin1 = new zemin1();
}
ust_bar.addChild(newBox);
newBox.x = i*60;
newBox.y = s*60;
}
Dee, you should make a question. I'm presuming you got problems with 'namespaces'. Try to define de variable first, with a superclass type, then in those conditionals just give a value. Like this:
function makeABox(e):void {
var newBox:somesuperclass;
if (e.name == "seri1") {
newBox = new karo1();
} else if (e.name == "seri2") {
newBox = new karo2();
} else {
newBox = new zemin1();
}
ust_bar.addChild(newBox);
newBox.x = i*60;
newBox.y = s*60;
}
This is actionsscript3? If is, you probably need e.currentTarget.name.
Hope this helps.