Unable to cast object of type 'System.Collections.Generic.List`1 [<>f__AnonymousType6`65[System.String,System.Decimal,System.Nullable`1 - linq-to-sql

I'm trying to hit my head to get out of this issue in which I'm not able to convert System.Collections.Generic.List to IEnumerable, below is my code :
IEnumerable<PY_History_TransactionTAB> FilteredReport;
var ReportData = db.PY_History_TransactionTAB
.Where(x => x.SystemCode == SysCode)
.GroupBy(x => x.EmployeeCode);
FilteredReport = (IEnumerable<PY_History_TransactionTAB>)ReportData.Select(x => new
{
EmployeeCode = x.Key,
H_SalaryDays = x.Sum(y => y.H_SalaryDays ?? 0),
H_NET_Overtime = x.Sum(y => y.H_NET_Overtime),
H_Overtime_Amount = x.Sum(y => y.H_Overtime_Amount),
H_SL_Breakup1 = x.Sum(y => y.H_SL_Breakup1 ?? 0),
H_SL_Breakup2 = x.Sum(y => y.H_SL_Breakup2 ?? 0),
H_SL_Breakup3 = x.Sum(y => y.H_SL_Breakup3 ?? 0),
H_OT_Allowance1 = x.Sum(y => y.H_OT_Allowance1 ?? 0),
H_OT_Allowance2 = x.Sum(y => y.H_OT_Allowance2 ?? 0),
H_OT_Allowance3 = x.Sum(y => y.H_OT_Allowance3 ?? 0),
H_OT_Allowance4 = x.Sum(y => y.H_OT_Allowance4 ?? 0),
H_OT_Allowance5 = x.Sum(y => y.H_OT_Allowance5 ?? 0)
}).ToList();
When I run the application, it throws a runtime exception System.InvalidCastException at point of assignment to FilteredReport variable, by saying :
{"Unable to cast object of type 'System.Collections.Generic.List1[<>f__AnonymousType665
[System.String,System.Decimal,System.Nullable1[System.Decimal],System.Nullable1[System.Decimal],
System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,
System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal
,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,
System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,
System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,
System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,
System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,
System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,
System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal]]' to type 'System.Collections
.Generic.IEnumerable`1[HrAndPayrollSystem.Models.PY_History_TransactionTAB]'."}
So, what I get is that I'm not going right, I need to find a right way, What should I do to get rid of this issue or what is the right way to convert a List to IEnumerable? Any Help will be deeply appreciated, Thanks in Advance!
Update:
Ok, René Vogt's answer is correct for the above issue, but then I encounter an another Exception System.NotSupportedException at the same point saying :
The entity or complex type
'HrAndPayrollSystem.Models.PY_History_TransactionTAB'
cannot be constructed in a LINQ to Entities query.
How should I resolve it?

The reason is that you return an List of an anonymous type. So this List<anonymousType> is a totally different type than a IEnumerable<HrAndPayrollSystem.Models.PY_History_TransactionTAB>.
So you need to change your Select call to something like:
FilteredReport = (IEnumerable<PY_History_TransactionTAB>)ReportData.Select(x =>
new PY_History_TransactionTAB // specify type!!
{
EmployeeCode = x.Key,
// shortened for brevity... set properties appropriatly
}).ToList();
Now the returned list is of type List<PY_History_TransactionTAB> which implements IEnumerable<PY_History_TransactionTAB>.

Related

Make a Person Using Getters and Setters: JavaScript not understanding where my codebase is performing the wrong action. Help requested

The "Make a Person" intermediate algorithm scripting challenge on freeCodeCamp requires you to fill an object constructor with the following methods:
/*
getFirstName()
getLastName()
getFullName()
setFirstName(first)
setLastName(last)
setFullName(firstAndLast)
*/
My code is as follows and includes the test cases and their required values commented in at the end:
const Person = function(firstAndLast) {
// Only change code below this line
// Complete the method below and implement the others similarly
//create a holder variable to hold a copy of the full name passed as parameter
let fullName = firstAndLast;
//create a variable to pay respect to "DRY" so as not to have to type this variable and method multiple times throughout
let splitter = fullName.split(" ");
//return the first name from the full name passed as parameter
this.getFirstName = function() {
return splitter[0];
};
//return the last name from the full name passed as parameter
this.getLastName = function() {
return splitter[1];
};
//return the full name passed as a parameter
this.getFullName = function() {
return fullName;
};
//update the full name to now include the given first name instead of the original passed parameter
this.setFirstName = function(first) {
fullName = first + " " + splitter[1];
};
//update the full name to now include the given last name instead of the original passed parameter
this.setLastName = function(last) {
fullName = splitter[0] + " " + last;
};
//update the full name to the given firstAndLast name instead of the original passed parameter
this.setFullName = function(newFull) {
fullName = newFull;
};
};
//create a new Person, bob, and name him 'Bob Ross'
const bob = new Person('Bob Ross');
//expected to return => 'Bob Ross'
let result = bob.getFullName();
//no expected return value, but fullName should now return => 'Haskell Curry'
bob.setFullName('Haskell Curry')
//my code here returns => 'Haskell Curry'
let result2 = bob.getFullName();
//my code here returns => 'Bob'
//should be returning => 'Haskell'
let result3 = bob.getFirstName();
//my code here returns => 'Ross'
//should be returning => 'Curry'
let result4 = bob.getLastName();
//Console.log in place for value testing during algorithm creation
console.log(result, result2, result3, result4)
//Check for length of bob, should not exceed 6 for the purposes of this test
console.log(Object.keys(bob).length)
/*Tests
Required returning values for each test
bob instanceof Person => true (Passing)
Object.keys(bob).length => 6 (Passing)
bob.firstName => undefined (Passing)
bob.lastName => undefined (Passing)
bob.getFirstName() => "Bob" (Passing)
bob.getLastName() => "Ross" (Passing)
bob.getFullName() => "Bob Ross" (Passing)
bob.getFullName() => "Haskell Ross" AFTER bob.setFirstName("Haskell") (Passing)
bob.getFullName() => "Haskell Curry" AFTER bob.setLastName("Curry") (Passing)
bob.getFullName() => "Haskell Curry" AFTER bob.setFullName("Haskell Curry") (Passing)
bob.getFirstName() => "Haskell" AFTER bob.setFullName("Haskell Curry") (NOT Passing)
bob.getLastName() => "Curry" AFTER bob.setFullName("Haskell Curry") (NOT Passing)
*/
After checking my code up against the solution code, the two are virtually the same, the only differences are the usage of
let splitter = fullName.split(" ")
//this does not exist in the solution code
//used in my code to avoid having to type fullName.split(" ") multiple times throughout
And where the setters ask for parameters "first", "last", and "newFull", respectively, the solution code uses "name" for each instead
I couldn't imagine that these two differences could make that big of a difference, so could I get some clarity in the understanding of their importance, and furthermore, why my code won't pass all the cases as is? Thanks in advance!

Telerik Line Graph Categories Null

I have tried everything I know to do but I cannot seem to get this to work...
My goal is to show tickets submitted in the past two weeks. I have already done all the logic on the back side of my MVC project but I cannot seem to display it properly. I just get a blank line graph with the legend to the right. I have provided my Razor code and the JSON return data. Please help. Thanks.
#(Html.Kendo().Chart<NewTicketsTwoWeekGraph>()
.Name("TwoWeekTickets")
.DataSource(dataSource => dataSource
.Read(read => read.Action("NewTicketsData_Read", "Home"))
)
.Series(series =>
{
series.Line(d => d.TicketCount).Name("Ticket Count");
})
.CategoryAxis(axis => axis
.Categories(t => t.TicketDate).Date().BaseUnit(ChartAxisBaseUnit.Days)
.Labels(labels => labels.Rotation(-90))
.Crosshair(c => c.Visible(true))
)
.ValueAxis(axis => axis.Numeric()
.Labels(labels => labels.Format("{0:N0}"))
.MajorUnit(10)
)
)
JSON Return:
{"Data":[{"TicketCount":1,"TicketDate":"\/Date(1426651200000)\/","TicketDateString":"2015-03-18"},
{"TicketCount":2,"TicketDate":"\/Date(1426564800000)\/","TicketDateString":"2015-03-17"}],"Total":2,"AggregateResults":null,"Errors":null}
The problem was with the JSON data being sent back. It doesnt like be wrapped in the "Data" array.
So I changed up my ActionResult to fix this...
public ActionResult _NewTicketCtOverTwoWeeks_Read([DataSourceRequest]DataSourceRequest request, string username)
{
using (var ctx = new GuardianContext())
{
var startDate = DateTime.Now.AddDays(-14);
var graphData = from ticket in ctx.TICKETS
where ticket.CREATED > startDate
group ticket by DbFunctions.TruncateTime(ticket.CREATED)
into a
orderby a.Key
select new TicketCount() { TicketCt = a.Count(), TicketDate = (DateTime)a.Key, TicketDateString = a.Key.ToString().Substring(0, 10) };
return Json(graphData.ToList());
}
}
So now my JSON request returns the following...
[{"TicketCt":2,"TicketDate":"\/Date(1426564800000)\/","TicketDateString":"2015-03-17"},{"TicketCt":11,"TicketDate":"\/Date(1426651200000)\/","TicketDateString":"2015-03-18"},{"TicketCt":20,"TicketDate":"\/Date(1426737600000)\/","TicketDateString":"2015-03-19"}]

Conditional Anonymous type

I am working on Web API and using Anonymous type to make JSON as output. I am stuck in the following scenario:
If there is no record(VALUE) available then i don't want to show that KEY. Meaning, Key should only appear when and only when there is value.
Below is the JSON object i am creating -
"TU": [
{
"BLOCK": [
[
"00:00",
"00:59"
]
]
}
],
"WE": [],// empty
"TH": [],// empty
"FR": [],// empty
"SA": [] // empty
Here for Tuesday we do have records and hence its showing but later for WE,TH,FR,SA there are not records and hence i don't want to show them so my result will be MO/TU only.
I am using below code:
var result = new
{
CustomerID = custId,
DeviceID = dId,
Kind = kind,
WebList = filter.Select(filt => new
{
URL = filt.FilterName,
TimeBlockFlag = new ChicoHelper().GetFlag(browserlimit, filt.ID, filt.FilterOptionID, KindId),
DAILY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == daily).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
WEEKLY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == weekly).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
MONTHLY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == monthly).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
HASVALUES = browserlimit.Where(xx => xx.FilterID == filt.ID).Count() > 0 ? 1 : 0,
BLOCKTYPE = new ChicoHelper().GetBlockType(browserlimit,filt.ID,filt.FilterOptionID,KindId),
SU = blockedlimit.Where(x => x.OptionID == sunday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
MO = blockedlimit.Where(x => x.OptionID == monday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
TU = blockedlimit.Where(x => x.OptionID == tuesday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
// if i can put some condition like if there is not record for WE then don't show it.
WE = blockedlimit.Where(x => x.OptionID == wednesday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
The main reason for doing this is to reduce the JSON size which will be consumed by Mobile Devices.
Please help me with this.
The properties of an anonymous type are fixed at compile-time - you can't make them conditional. However, some other approaches you might want to think about:
You could investigate whether a property is still included in the JSON representation if its value is null. If it's not, you could add an extension method NullIfEmpty() which returns null if its input is empty.
You could try performing the JSON conversion from the anonymous type in code first, then delete any properties with an empty set of results, then just return that JSON object from the API. (I don't know Web API myself, but there must be a way of saying "Here's a JSON object - ask it for its string representation" rather than using an anonymous type.)
You could ditch the anonymous type entirely, and build up the JSON representation programmatically, setting just the properties you want.
In any approach, I would strongly advise you to extract a common method to come up with the property value based on a day of the week, so you can have:
...
SU = blockedLimit.GetDayBlocks(sunday),
MO = blockedLimit.GetDayBlocks(monday),
TU = blockedLimit.GetDayBlocks(tuesday),
...
There's no reason to have all that code repeated 7 times. In fact, I'd probably refactor that part before doing anything else - it'll make it easier to experiment.

How to extend google maps from Dart

I'm using the google_maps package (v. 2.0.1). Now I'd like to use the MarkerWithLabel marker extension (http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/).
My choices appear to be to create new Dart classes by cutting and pasting the Marker and MarkerOptions classes from the goggle_maps package or to somehow subclass of Marker (and MarkerOptions) in Dart.
The first option is just ugly, but I can't wrap my head around how to go about the second option. Am I missing something obvious? How should I approach this problem?
The following wrappers should work :
class MarkerWithLabel extends Marker {
MarkerWithLabel([MarkerWithLabelOptions opts])
: this.fromJsObject(new js.JsObject(js.context['MarkerWithLabel'],
[opts == null ? null : opts.$unsafe]));
MarkerWithLabel.fromJsObject(js.JsObject proxy) : super.fromJsObject(proxy);
}
class MarkerWithLabelOptions extends MarkerOptions {
MarkerWithLabelOptions();
MarkerWithLabelOptions.fromJsObject(js.JsObject proxy)
: super.fromJsObject(proxy);
String get crossImage => $unsafe['crossImage'];
set crossImage(String crossImage) => $unsafe['crossImage'] = crossImage;
String get handCursor => $unsafe['handCursor'];
set handCursor(String handCursor) => $unsafe['handCursor'] = handCursor;
Point get labelAnchor => Point.$wrap($unsafe['labelAnchor']);
set labelAnchor(Point labelAnchor) =>
$unsafe['labelAnchor'] = labelAnchor == null ? null : labelAnchor.$unsafe;
String get labelClass => $unsafe['labelClass'];
set labelClass(String labelClass) => $unsafe['labelClass'] = labelClass;
dynamic/*string|Node*/ get labelContent => $unsafe['labelContent'];
set labelContent(dynamic/*string|Node*/ labelContent) =>
$unsafe['labelContent'] = labelContent;
bool get labelInBackground => $unsafe['labelInBackground'];
set labelInBackground(bool labelInBackground) =>
$unsafe['labelInBackground'] = labelInBackground;
js.JsObject get labelStyle => $unsafe['labelStyle'];
set labelStyle(js.JsObject labelStyle) => $unsafe['labelStyle'] = labelStyle;
bool get labelVisible => $unsafe['labelVisible'];
set labelVisible(bool labelVisible) => $unsafe['labelVisible'] = labelVisible;
bool get optimized => $unsafe['optimized'];
set optimized(bool optimized) => $unsafe['optimized'] = optimized;
bool get raiseOnDrag => $unsafe['raiseOnDrag'];
set raiseOnDrag(bool raiseOnDrag) => $unsafe['raiseOnDrag'] = raiseOnDrag;
}

Linq - pulling a value from a null query result

I have a linq query that needs to pull a date column out of a row. The expression currently looks like this
myObject.OrderByDescending(s=> s.MyDate).Where(s => s.CRAStatus.Description == "CheckedOut").FirstOrDefault().MyDate)
The problem is that if there are no rows that are "CheckedOut", the query will return a null and attempting to get "MyDate" will throw an exception. We have some verbose solutions, like:
.ForMember(dest => dest.CheckOutDate, opt => opt.MapFrom(src => {
var temp = src.CRAStatusChangeEvents.OrderByDescending(s=> s.MyDate).Where(s => s.CRAStatus.Description == "CheckedOut").FirstOrDefault();
return temp == null ? temp.MyDate : null;
}));
But it would be nice to find something a little more concise. Any Ideas?
Why not
myObject.OrderByDescending(s=> s.MyDate)
.Where(s => s.CRAStatus.Description == "CheckedOut")
.Select(s => s.MyDate as DateTime?)
.FirstOrDefault();
or
myObject.Where(s => s.CRAStatus.Description == "CheckedOut")
.Max(s => s.MyDate as DateTime?);
One option is to set the default if empty to an "empty" instance (think of string.Empty--its a known instance that represents an empty result):
var date = (myObject
.OrderByDescending(s=> s.MyDate)
.Where(s => s.CRAStatus.Description == "CheckedOut")
.DefaultIfEmpty(MyObject.Empty)
.FirstOrDefault()).MyDate;
Here's a snippet that shows how it works:
var strings = new string[]{"one", "two"};
var length =
(strings.Where(s=>s.Length > 5)
.DefaultIfEmpty(string.Empty)
.FirstOrDefault()).Length;
run that and length is 0. Remove the DefaultIfEmpty line and you get a NRE.
var checkedOut = myObject.Where(s => s.CRAStatus.Description == "CheckedOut");
if (checkedOut.Count() > 0) {
var result = checkedOut.Max(s=> s.MyDate).MyDate;
}
How about an extension method?
static class MyObjectEnumerableExtensions
{
public static TMember GetMemberOfFirstOrDefault<TMember>(this IEnumerable<MyObject> items, Func<MyObject, TMember> getMember)
{
MyObject first = items.FirstOrDefault();
if (first != null)
{
return getMember(first);
}
else
{
return default(TMember);
}
}
}
Sample usage:
List<MyObject> objects = new List<MyObject>();
objects.Add(new MyObject { MyDate = DateTime.MinValue });
var filteredObjects = from s in objects where s.MyDate > DateTime.MinValue select s;
DateTime date = filteredObjects.GetMemberOfFirstOrDefault(s => s.MyDate);
Console.WriteLine(date);