Assign value to new List property (ASP.NET MVC) - c#

I have table class Logging
Here is code:
public partial class Logging
{
public string Imei { get; set; }
public DateTime CurDateTime { get; set; }
public Nullable<System.DateTime> GPSDateTime2 { get; set; }
public Nullable<decimal> Latitude2 { get; set; }
public Nullable<decimal> Longitude2 { get; set; }
public int Speed { get; set; }
public Nullable<int> Datatype { get; set; }
public int Id { get; set; }
}
Also I have ViewModel
public class HeatmapViewModel
{
public decimal? Latitude2 { get; set; }
public decimal? Longitude2 { get; set; }
public int FirstStartDifference { get; set; }
public int LastStartDifference { get; set; }
public int coeff = 2;
public int Difference;
}
I have method in repository where I do all calculations
Here is code
var allitems = ctx.Loggings.AsEnumerable().Select(
x => new Logging
{
Longitude2 = x.Longitude2,
Latitude2 = x.Latitude2,
CurDateTime = x.CurDateTime,
Datatype = x.Datatype
});
var filteredQuery = allitems.Where(x => x.Datatype == 1 || x.Datatype == 2).OrderByDescending(x => x.Id).ToList();
for (int i = 1; i < filteredQuery.Count; i++)
{
if (filteredQuery[i].Datatype == 2 && filteredQuery[i - 1].Datatype == 1)
{
TimeSpan differenceTicks = filteredQuery[i].CurDateTime - filteredQuery[i - 1].CurDateTime;
var differenceInMinutes = (int) differenceTicks.TotalMinutes;
}
}
items.Add(new HeatmapViewModel
{
Latitude2 = allitems.Longitude2,
Longitude2 = allitems.Longitude2,
Difference = differenceInMinutes
});
I have trouble with this block of code:
items.Add(new HeatmapViewModel
{
Latitude2 = allitems.Longitude2,
Longitude2 = allitems.Longitude2,
Difference = differenceInMinutes
});
Here is errors:
Severity Code Description Project File Line Suppression State
Error CS1061 'IEnumerable' does not contain a definition for 'Longitude2' and no extension method 'Longitude2' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?) Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Repository\HeatmapRepository.cs 91 Active
Severity Code Description Project File Line Suppression State
Error CS1061 'IEnumerable' does not contain a definition for 'Longitude2' and no extension method 'Longitude2' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?) Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Repository\HeatmapRepository.cs 92 Active
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'differenceInMinutes' does not exist in the current context Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Repository\HeatmapRepository.cs 93 Active
How I can solve them?

Your problem is: allitems is an IEnumerable, so you can't use allitems.Longitude2 to get value of Longitude2. It's not a single item.
I think you should put items.Add(...) block to for loop.
And use filteredQuery[i].Longitude2 instead of allitems.Longitude2.
Like this
var filteredQuery = (
from log in ctx.Loggings
where log.Datatype == 1 || log.Datatype == 2
orderby log.Id descending
select log
).ToList();
var items = new List<HeatmapViewModel>();
for (int i = 1; i < filteredQuery.Count; i++)
{
if (filteredQuery[i].Datatype == 2 && filteredQuery[i - 1].Datatype == 1)
{
TimeSpan differenceTicks = filteredQuery[i].CurDateTime - filteredQuery[i - 1].CurDateTime;
items.Add(new HeatmapViewModel
{
Latitude2 = filteredQuery[i].Longitude2,
Longitude2 = filteredQuery[i].Longitude2,
Difference = (int)differenceTicks.TotalMinutes
});
}
}

Related

How adding items to list

I have model in my project. Here is code of model
public partial class Logging
{
public string Imei { get; set; }
public DateTime CurDateTime { get; set; }
public Nullable<System.DateTime> GPSDateTime2 { get; set; }
public Nullable<decimal> Latitude2 { get; set; }
public Nullable<decimal> Longitude2 { get; set; }
public string Speed { get; set; }
public Nullable<int> Datatype { get; set; }
public int Id { get; set; }
[NotMapped]
public TimeSpan? FirstStartDifference
{
get
{
if (CurDateTime != null)
{
var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 00, 00, 00);
var difference = CurDateTime - midnight;
return difference;
}
return null;
}
}
[NotMapped]
public TimeSpan? LastStartDifference
{
get
{
if (CurDateTime != null)
{
var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 23, 59, 00);
var difference = midnight - CurDateTime;
return difference;
}
return null;
}
}
[NotMapped]
public int coeff = 2;
}
I need to get some items from database , it's first entry, where Datatype==1 and Last where Datatype ==2.
So I write this method on back-end
public JsonResult GetStops()
{
using (var ctx = new GoogleMapTutorialEntities())
{
var firstitem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
x => new
{
lng = x.Longitude2,
lat = x.Latitude2,
difference = (int)(x.FirstStartDifference?.TotalMinutes ?? -1) * x.coeff
}).FirstOrDefault();
var lastItem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
x => new
{
lng = x.Longitude2,
lat = x.Latitude2,
difference = (int)(x.LastStartDifference?.TotalMinutes ?? -1) * x.coeff
}).LastOrDefault();
List<Logging> items = new List<Logging> {firstitem, lastItem};
return Json(firstitem, JsonRequestBehavior.AllowGet);
}
}
After this I need to add firstitem and lastitem to list.
I write it like this List<Logging> items = new List<Logging> {firstitem, lastItem};
But I get an error
Severity Code Description Project File Line Suppression State
Error CS1950 The best overloaded Add method 'List.Add(Logging)' for the collection initializer has some invalid arguments Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Controllers\HomeController.cs 37 Active
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from '' to 'Heatmap.Models.Logging' Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Controllers\HomeController.cs 37 Active
for this List<Logging> items = new List<Logging> {firstitem, lastItem};
How I can add them to List?
You are returning an anonymous type instead of Logging. The firstitem and lastItem are Anonymous Types. Change your code to this:
x => new Logging
{
Longitude2 = x.Longitude2,
Latitude2 = x.Latitude2,
//And other properties
}
And if you still get error probably it is because you cannot project onto a mapped entity then you need to create a DTO class with needed properties from the Logging entity:
public class LoggingDTO
{
public string Longitude2 { get; set; }
public string Latitude2 { get; set; }
//And other properties
}
Then:
x => new LoggingDTO

Error in sorting a list missing a cast

i have a list that I am trying to sort by datetime and return it. but I get a error.How do I fix this?
Cannot implicitly convert type
System.Linq.IOrderedEnumerable<ConsoleApplication2.DTNBars> to
System.Collections.Generic.List<ConsoleApplication2.DTNBars>. An
explicit conversion exists (are you missing a cast?)
public static List<DTNBars> getDTNBars(string symbol, DateTime dt)
{
TextReader tr = new StreamReader(File.Open(#"C:\historicaldata\" + symbol + ".txt", FileMode.Open));
List<DTNBars> dtnbars = new List<DTNBars>();
CsvReader csvr = new CsvReader(tr);
while (csvr.Read())
{
DTNBars b = new DTNBars();
b.Date_Time = csvr.GetField<DateTime>(0);
b.Open = csvr.GetField<double>(1);
b.High = csvr.GetField<double>(2);
b.Close = csvr.GetField<double>(4);
b.Ticker = symbol;
dtnbars.Add(b);
}
return dtnbars.OrderBy(x => x.Date_Time);
}
public class DTNBars
{
public DateTime Date_Time { get; set; }
public double Open { get; set; }
public double High { get; set; }
public double Low { get; set; }
public double Close { get; set; }
public string Ticker { get; set; }
}
Use ToList()
return dtnbars.OrderBy(x => x.Date_Time).ToList();
Your method states a return type of List<DTNBars> but you are returning IOrderedEnumerable<DTNBars> - which is the result of the OrderBy. Add ToList():
return dtnbars.OrderBy(x => x.Date_Time).ToList();
Or better just change return type to an IEnumerable<DTNBars>
Also you can refactor your initializing of the new DTNBars and use the object initializer:
dtnbars.Add( new DTNBars {
Date_Time = csvr.GetField<DateTime>(0),
Open = csvr.GetField<double>(1),
High = csvr.GetField<double>(2),
Close = csvr.GetField<double>(4),
Ticker = symbol });

Why is this type not assignable to the parameter type?

The OWF_ManagersNextTwoMonths return type is a copy of the OWF_ManagerRelationshipViewModel a couple things in it commented out. This method is a modified version of the original that used OWF_ManagerRelationshipViewModel as the return type. The goal is to eliminate one of the proxy classes to reduce the number of records being returned.
One other difference is passing in the the new OWF_ManagersNextTwoMonthsViewModel to automapper in the return statement.
I get a red squiggle under the item in managerListFinal.Add(item); and (managerListFinal) in the automapper part of the return type.
The first red squiggle in the managerListFinal.Add(item); says:
'Argument type Jupiter.Core.Model.OWF_ManagerRelationship is not
assignable to parameter type
Jupiter.Core.Model.OWF_ManagersNextTwoMonthsViewModel'.
The second red squiggle in (managerListFinal) says:
'Argument type Jupiter.Core.Model.OWF_ManagersNextTwoMonthsViewModel
is not assignable to parameter type
Jupiter.Core.Model.OWF_ManagerRelationship'.
I tried also returning the managerListFinal below the automapper return, but get a message that says same thing as it did for the first one above that uses the automapper.
The new OWF_ManagersNextTwoMonthsViewModel was created with out the Document request list in an effort to not return these records. I thought it would work because it's so similar the original OWF_ManagerRelationshipViewModel.
I think the automapper return would return what I need, if it worked correctly. I'm trying to get the onsites dates, Target dates, usernames and manager types. The onsite and target dates are used in the method below while the DisplayName, Manager Type and Users are displayed in the view's grid.
I thought this would be as simple as copying the viewmodel and ommiting the doc request list portion of it. I don't understand why the compiler doesn't like this or how to correct it.
Original OWF_ManagerRelationshipViewModel:
public class OWF_ManagerRelationshipViewModel
{
public OWF_ManagerRelationshipViewModel()
{
OWF_Onsites = new List<OWF_OnsitesViewModel>();
OWF_DocumentRequestList = new List<OWF_DocumentRequestListViewModel>();
}
public int RelationshipId { get; set; }
[Required]
public int ManagerId { get; set; }
public string Users { get; set; }
public string ManagerType { get; set; }
[Required]
public string DisplayName { get; set; }
public string CurrentState { get; set; }
public Nullable<bool> IsActive { get; set; }
public IEnumerable<OWF_AccessGroupViewModel> UsernameList { get; set; }
public virtual ICollection<OWF_DocumentRequestListViewModel> OWF_DocumentRequestList { get; set; }
public virtual ICollection<OWF_OnsitesViewModel> OWF_Onsites { get; set; }
}
My new OWF_ManagersNextTwoMonthsViewModel:
public class OWF_ManagersNextTwoMonthsViewModel
{
public OWF_ManagersNextTwoMonthsViewModel()
{
//OWF_DocumentRequestList = new List<OWF_DocumentRequestListViewModel>();
OWF_Onsites = new List<OWF_OnsitesViewModel>();
}
public int RelationshipId { get; set; }
[Required]
public int ManagerId { get; set; }
public string Users { get; set; }
public string ManagerType { get; set; }
[Required]
public string DisplayName { get; set; }
public string CurrentState { get; set; }
public Nullable<bool> IsActive { get; set; }
public IEnumerable<OWF_AccessGroupViewModel> UsernameList { get; set; }
//public virtual ICollection<OWF_DocumentRequestListViewModel> OWF_DocumentRequestList { get; set; }
public virtual ICollection<OWF_OnsitesViewModel> OWF_Onsites { get; set; }
}
Method with the red squiggles:
public IEnumerable<OWF_ManagersNextTwoMonthsViewModel> GetAllExistingManagersByCurrentDate()
{
var managers = _relationshipRepo.GetAll();
var managerListFinal = new List<OWF_ManagersNextTwoMonthsViewModel>();
var year = DateTime.Now.Year;
var prevYear = DateTime.Now.AddYears(-1).Year;
foreach (var item in managers)
{
foreach (var onsite in item.OWF_Onsites.Where(x => x.OnsiteDate != null))
{
if (Convert.ToDateTime(onsite.OnsiteDate).Month == DateTime.Now.Month && Convert.ToDateTime(onsite.OnsiteDate).Year == year ||
onsite.TargetMonth == DateTime.Now.Month && onsite.OnsiteDate == null && Convert.ToDateTime(onsite.OnsiteDate).Year == year ||
onsite.TargetMonth == (DateTime.Now.Month + 1) && onsite.OnsiteDate == null && Convert.ToDateTime(onsite.OnsiteDate).Year == year ||
Convert.ToDateTime(onsite.OnsiteDate).Month == (DateTime.Now.Month + 1) && Convert.ToDateTime(onsite.OnsiteDate).Year == year ||
Convert.ToDateTime(onsite.OnsiteDate).Month == DateTime.Now.Month && Convert.ToDateTime(onsite.OnsiteDate).Year == prevYear ||
onsite.TargetMonth == DateTime.Now.Month && onsite.OnsiteDate == null && Convert.ToDateTime(onsite.OnsiteDate).Year == prevYear ||
onsite.TargetMonth == (DateTime.Now.Month + 1) && onsite.OnsiteDate == null && Convert.ToDateTime(onsite.OnsiteDate).Year == prevYear ||
Convert.ToDateTime(onsite.OnsiteDate).Month == (DateTime.Now.Month + 1) && Convert.ToDateTime(onsite.OnsiteDate).Year == prevYear)
{
managerListFinal.Add(item);
}
}
}
//return Mapper.Map<IEnumerable<OWF_ManagerRelationship>, IEnumerable<OWF_ManagersNextTwoMonthsViewModel>>(managerListFinal);
return managerListFinal;
}
You take items from OWF_ManagerRelationship check them and then place them into a list of OWF_ManagersNextTwoMonthsViewModel. and afterwards you want to map them.
I think you should do something like this
managerListFinal.Add(Mapper.Map<OWF_ManagerRelationship,OWF_ManagersNextTwoMonthsViewModel>(item));
and you should be good

Implicitly Convert Type

i am doing this in WPF and i am using entity-framework .
this is my query code in my CRUD class file :
public class QuestionHint
{
public int? QuestionNo { get; set; } //change the type accordingly
public int? ActivityID { get; set; } //change the type accordingly
public int? TaskID { get; set; } //change the type accordingly
public string Answer { get; set; } //change the type accordingly
public string QuestionContent { get; set; } //change the type accordingly
public string joined { get; set; } //change the type accordingly
public string joinOption { get; set; } //change the type accordingly
}
public IList<QuestionHint> GetListKeys(int listTask, int listActivity)
{
IList<QuestionHint> lstRecords = context.questionhints.GroupBy(x => new { x.QuestionNo, x.ActivityID, x.TaskID }).ToList().Select(g => new QuestionHint()
{
QuestionNo = g.Key.QuestionNo,
ActivityID = g.Key.ActivityID,
TaskID = g.Key.TaskID,
joined = String.Join(" ",
g.OrderBy(q => q.questionhintID)
.Select(i => i.QuestionContent + "[" + i.Answer + "]")),
joinOption = String.Join(" ",
g.OrderBy(q => q.questionhintID)
.Select(a => "[" + a.Option1 + "," + a.Option2 + "]"))
}).Where(x => x.TaskID == listTask && x.ActivityID == listActivity)
//.Take(50)
.ToList();
return lstRecords;
}
i call this in code behind :
private DAO.DAOQuestionHint qh = new DAO.DAOQuestionHint();
public MainWindow2()
{
InitializeComponent();
PopulateQuestion(1, 5);
}
private void PopulateQuestion(int activityID, int taskID)
{
IList<QuestionHint> lstQuestionHints = qh.GetListKeys(taskID, activityID); // ERROR
//codes here...
}
i am getting this error in the code behind of my xaml.cs :
Cannot implicitly convert type
'System.Collections.Generic.IList'
to 'System.Collections.Generic.IList'. An
explicit conversion exists (are you missing a cast?)
iStellar is the name of the project. DAOQuestionHint is the name of the CRUD class file.
There is no error in the CRUD class file , i use the same query to retrieve records in the other project and it works well , don't know why it don't work in here.
You're using different capitalization for the generic argument in each example - IList<QuestionHint> in GetListKeys() and IList<Model.questionhint> in PopulateQuestion(). I'd guess these refer to similarly named but different types.

Linq lambda join error

I have been following the book Pro ASP.net MVC 2 Framework, which I have found to be quite brilliant. But it's a real learning curve and now I'm stuck.
In the book you build something like the below, which allows for paging.
public ViewResult List([DefaultValue(0)] string cityzip, [DefaultValue(1)] int page)
{
var roomsToShow = roomsRepository.Rooms.Where(x => x.CountryID == cityzip);
var viewModel = new RoomsListViewModel
{
Rooms = roomsToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList(),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = roomsToShow.Count()
}
};
return View(viewModel); // Passed to view as ViewData.Model (or simply Model)
}
I think needed to adapt this, so that I could do a join on the search
public ViewResult List([DefaultValue(0)] string cityzip, [DefaultValue(1)] int page)
{
var roomsToShow = roomsRepository.Rooms.Join(
roomCoordinatesRepository.RoomCoordinates,
room => room.RoomID,
roomCoordinate => roomCoordinate.RoomID,
(room, roomCoordinate) => new { RoomCoordinate = roomCoordinate, Room = room });
var viewModel = new RoomsListViewModel
{
Rooms = roomsToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList(),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = roomsToShow.Count()
}
};
return View(viewModel); // Passed to view as ViewData.Model (or simply Model)
}
...but immediately I get an intellisense error saying -
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.IList<MeetingRoom.Domain.Entities.Room>'. An explicit conversion exists (are you missing a cast?)
I obviously don't understand the code well enough to figure out what is wrong. I'm also feeling a bit out of my depth with this lamda linq stuff
Room is a domain object which is defined as:
namespace MeetingRoom.Domain.Entities
{
[Table(Name = "Rooms")]
public class Room
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int RoomID { get; set; }
[Column] public string Name { get; set; }
[Column] public string Description { get; set; }
[Column] public decimal Price { get; set; }
[Column] public string Category { get; set; }
[Column] public string Pcode { get; set; }
[Column] public int CountryID { get; set; }
public MeetingRooms.Domain.entities.RoomCoordinate RoomCoordinate { get; set; }
}
}
and represents my Room table. Do I need some sort of parent entity that would represent the join between the Room and Room-co-ordinates table?
The co-ordinates entity looks like this:
namespace MeetingRooms.Domain.entities
{
[Table(Name = "RoomCoordinate")]
public class RoomCoordinate
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert, Name = "ID")]
public int CoordID { get; set; }
[Column]
public int RoomID { get; set; }
[Column]
public string Coordinates { get; set; }
[Column]
public decimal Latitude { get; set; }
[Column]
public decimal Longitude { get; set; }
}
}
The RoomsListViewModel looks like follows:
namespace MeetingRoomsMVC.WebUI.Models
{
public class RoomsListViewModel
{
public IList RoomsWithCoordinates { get; set; }
public PagingInfo PagingInfo { get; set; }
}
}
The problem is, in this code
var roomsToShow = roomsRepository.Rooms.Join(
roomCoordinatesRepository.RoomCoordinates,
room => room.RoomID,
roomCoordinate => roomCoordinate.RoomID,
(room, roomCoordinate) => new { RoomCoordinate = roomCoordinate, Room = room });
you're constructing an IEnumerable of anonymous-type objects: (room, roomCoordinate) => new { RoomCoordinate = roomCoordinate, Room = room }
And then, in the next line you're trying to assing it to a list of Room.
The problem can be resolved by initially creating an IEnumerable of the correct item type:
var roomsToShow = roomsRepository.Rooms.Join(
roomCoordinatesRepository.RoomCoordinates,
room => room.RoomID,
roomCoordinate => roomCoordinate.RoomID,
(room, roomCoordinate) => new MeetingRoom.Domain.Entities.Room{ RoomCoordinate = roomCoordinate, Room = room });
(note the class name in the lambda).
Here's my suggestion based on the OP's further description:
1) Create an aggregate class that holds both Room and RoomCoordinates info:
public class RoomWithCoordinates
{
public Room Room { get; set; }
public RoomCoordinates Coordinates { get; set; }
}
2) Modify your controller action as follows:
public ViewResult List([DefaultValue(0)] string cityzip, [DefaultValue(1)] int page)
{
var roomsToShow = roomsRepository.Rooms.Join(
roomCoordinatesRepository.RoomCoordinates,
room => room.RoomID,
roomCoordinate => roomCoordinate.RoomID,
(room, roomCoordinate) => new RoomWithCoordinates{ Coordinates = roomCoordinate, Room = room } );
var viewModel = new RoomsListViewModel
{
RoomsWithCoordinates = roomsToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList(),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = roomsToShow.Count()
}
};
return View(viewModel); // Passed to view as ViewData.Model (or simply Model)
}
3) Modify your RoomsListViewModel class and your view to reflect these changes.

Categories

Resources