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
Related
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]);
Right now in my ASP.NET MVC Core2 project I have a model in EF database, that contains several properties:
public class SchoolEvents
{
public long ID { get; set; }
[Required]
[StringLength(40, ErrorMessage = "Max 40 characters")]
public string Title { get; set; }
[Required]
public string Description { get; set; }
[Required]
public DateTime WhenHappens { get; set; }
}
I have no problem to get data from the EF database by MVC Razor Views. But I am using JavaScript Calendar plugin in one of my Views, that will mark events from db on it. To do it, the script is taking data in format:
{ title: 'EventTitle', description: 'Few words about the event', datetime: new Date(2018, 8, 14, 16) }
It seems to be obvious, that I supposed to use a for loop in the script, iterating on db objects.
As I am still noob about JS, right now the only way I know to do it is:
-to create JSON file in the controller:
[Route("events")]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public ActionResult Comments()
{
var _events= _context.Events.OrderBy(c => c.ProductID).ToList(); //yes, I know, I should use repository in the best practice
return Json(_events);
}
-in JS file I can use kinf of loadEventsFromServer() function, that uses XMLHttpRequest or Fetch and parsing it (I do not know yet how to do the parsing, I will be happy to get some suggestions),
And that it is it. Do you have some other ideas how to do it?
EDIT:
Update with part of plugins code, for console error d is undefined:
for (var i = 0; i < 42; i++) {
var cDay = $('<div/>');
if (i < dWeekDayOfMonthStart) {
cDay.addClass('c-day-previous-month c-pad-top');
cDay.html(dLastDayOfPreviousMonth++);
} else if (day <= dLastDayOfMonth) {
cDay.addClass('c-day c-pad-top');
if (day == dDay && adMonth == dMonth && adYear == dYear) {
cDay.addClass('c-today');
}
for (var j = 0; j < settings.events.length; j++) {
var d = settings.events[j].datetime;
if (d.getDate() == day && d.getMonth() == dMonth && d.getFullYear() == dYear) {
cDay.addClass('c-event').attr('data-event-day', d.getDate());
cDay.on('mouseover', mouseOverEvent).on('mouseleave', mouseLeaveEvent);
}
}
cDay.html(day++);
} else {
cDay.addClass('c-day-next-month c-pad-top');
cDay.html(dayOfNextMonth++);
}
cBody.append(cDay);
}
I will suggest you to use ajax request.
Javascript : Ajax
$.ajax({
type: 'POST',
url: '#URL.Action("Comments","Controller")',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: {},
success: function (data) {
var events = new Object();
events = $.map(data.d, function (item, i) {
for (var j = 0; j < data.d.length; j++) {
var event = new Object();
var startDate = Date.parse(item.WhenHappens )
event.start = startDate;
event.title = item.Title;
event.backgroundColor = "#c6458c";
event.description = item.Description;
return event;
}
})
callCalender(events);
},
error:function(e){
}
});
Controller
[Route("events")]
[HttpPost]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public ActionResult Comments()
{
var _events= _context.Events.OrderBy(c => c.ProductID).ToList(); //yes, I know, I should use repository in the best practice
return Json(_events);
}
I am adding some data in List of Tuple type like this in Razor view
List<Tuple<int, int, string>> Downloadlist = new List<Tuple<int, int, string>>();
And adding items to this list
Downloadlist.Add(new Tuple<int, int, string>(11, 7, "somedata"));
Now I would like to access the array of data in javascript
<script>
var listofdownloadpages = '#ViewData["DownloadPages"]';
if (listofdownloadpages != null) {
alert(listofdownloadpages.length);
for (var i = 0; i < listofdownloadpages.length; i++) {
alert(listofdownloadpages[i].wishid + ' ' + listofdownloadpages[i].remain);
}
}
else {
alert("not found anything");
}
But this not giving me the items in correct way please help.
This will work
Controller
public ActionResult Test()
{
List<Tuple<int, int, string>> Downloadlist = new List<Tuple<int, int, string>>();
Downloadlist.Add(new Tuple<int, int, string>(11, 7, "somedata"));
ViewData["DownloadPages"] = Downloadlist;
return View();
}
View & JS
<script>
var listofdownloadpages = #Html.Raw(Json.Encode(#ViewBag.DownloadPages));
if (listofdownloadpages != null) {
alert(listofdownloadpages.length);
for (var i = 0; i < listofdownloadpages.length; i++) {
alert(listofdownloadpages[i].Item1 + ' ' + listofdownloadpages[i].Item2);
}
}
else {
alert("not found anything");
}
</script>
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.
I wrote the code in Java, no problem. Here I am giving the Java code:
public class CarGallery {
static int carCounter=10;
static Gallery[] car = new Gallery[carCounter];
public static void main(String[] args) {
car[0].weight = (float) 1.25;
car[0].weight = (float) 0.87;
// ... and so on ... //
}
}
class Gallery {
public float weight;
public float height;
public int colorCode;
public int stockGallery;
};
The thing is, I want to write the same code in Javascript. Here is the code that does not work:
var cars = {weight:0 , height:0 , stock:0 , model:"..."};
var cars = new Array();
cars[0].weight=1.2;
cars[0].height=0.87;
cars[0].stock=2;
cars[0].model="320";
I read some documents and saw that there is no class definition in Javascript like Java classes.
I found class definition in JS with constructors, but I don't want to use constructors.
The member should be defined as array like:
static Gallery[] car = new Gallery[carCounter];
Thank you for your help!
The JavaScript equivalent to your Java would be.
function Gallery() {
this.weight = null;
this.height = null;
this.colorCode = null;
this.stockGallery = null;
};
var carCounter = 10;
var carGallery = new Array(carCounter);
carGallery[0] = new Gallery();
carGallery[0].weight = 1.2;
carGallery[0].height = 0.87;
carGallery[0].colorCode = 2
carGallery[0].stockGallery = 3;
carGallery[1] = new Gallery();
carGallery[1].weight = 2.2;
...