Pie Charts issue use in controller - c#

I need to draw a pie chart with HighCharts. I did this in my controller:
class SimpleClass
{
public string x { set; get; }
public int y { set; get; }
}
public ActionResult Index()
{
var multas = from multa in db.Multa select multa;
int MultaSinPago = multas.Where(s => s.Estado == "sin pago").Count();
int MultaPagado = multas.Where(s => s.Estado == "Pagado").Count();
var results = new List<SimpleClass>();
results.Add(new SimpleClass { x = "Sin Pago", y = MultaSinPago });
results.Add(new SimpleClass { x = "Pagado", y = MultaPagado });
//Create chart Model
var chart1 = new Highcharts("Chart1");
chart1
.InitChart(new Chart() { DefaultSeriesType = ChartTypes.Pie })
.SetTitle(new Title() { Text = "Multas" })
.SetSeries(new[] { new Series { Data = new List<SimpleClass>(results) } });
//pass Chart1Model using ViewBag
ViewBag.Chart1Model = chart1;
return View();
}
But where Data = new List<SimpleClass>(results) is bad, how can i do for it?

I found solution!..
var multas = from multa in db.Multa select multa;
int MultaSinPago = multas.Where(s => s.Estado == "sin pago").Count();
int MultaPagado = multas.Where(s => s.Estado == "Pagado").Count();
TempData["CountMulta"] = (MultaPagado + MultaSinPago).ToString();
Highcharts chart = new Highcharts("chart")
.SetTitle(new Title() { Text = "Multas"})
.InitChart(new Chart())
.SetPlotOptions(new PlotOptions
{
Pie = new PlotOptionsPie
{
AllowPointSelect = true,
Cursor = Cursors.Pointer,
ShowInLegend = true,
Events = new PlotOptionsPieEvents { Click = "function(event) { alert('The slice was clicked!'); }" },
Point = new PlotOptionsPiePoint { Events = new PlotOptionsPiePointEvents { LegendItemClick = "function(event) { if (!confirm('Do you want to toggle the visibility of this slice?')) { return false; } }" } }
}
})
.SetSeries(new Series
{
Type = ChartTypes.Pie,
Name = "Cantidad",
Data = new Data(new object[]
{
new object[] { "Pagado", MultaPagado},
new object[] { "Sin pago", MultaSinPago}
})
});
ViewBag.Chart1Model = chart;
return View();
Hope this is helpful for somebody! :)

Related

need to group data based on `InstanceData` Name property

I have one Packet like below,
var dataPacket = new Packet
{
Id = new Guid("2e08bd98-68eb-4358-8efb-9f2adedfb034"),
Results = new Result
{
ResultName = "ResultName1",
Instances = new List<Instance>
{
new Instance
{
InstanceName = "InstanceName1",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "N1", Value = "V1"},
new InstanceData{Name = "N2", Value = "V2"}
}
},
new Instance
{
InstanceName = "InstanceName2",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "N1", Value = "V3"},
new InstanceData{Name = "N2", Value = "V4"}
}
}
}
}
};
Here are the class structures,
public class Packet
{
public Guid Id { get; set; }
public Result Results { get; set; }
}
public class Result
{
public string ResultName { get; set; }
public List<Instance> Instances { get; set; }
}
public class Instance
{
public string InstanceName { get; set; }
public List<InstanceData> InstanceDatas { get; set; }
}
public class InstanceData
{
public string Name { get; set; }
public string Value { get; set; }
}
For above Packet I want to spilt this into 2 Packets based on InstanceData common Name
All N1 from InstanceName1 and InstanceName2 into one packet
All N2 from InstanceName1 and InstanceName2 into one packet
Packet1 should be like this,
var packet1 = new Packet
{
Id = new Guid("2e08bd98-68eb-4358-8efb-9f2adedfb034"),
Results = new Result
{
ResultName = "ResultName1",
Instances = new List<Instance>
{
new Instance
{
InstanceName = "InstanceName1",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "N1", Value = "V1"},
}
},
new Instance
{
InstanceName = "InstanceName2",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "N1", Value = "V3"},
}
}
}
}
};
and similarly packet2.
I have tried below, but this will split on InstanceData as well and giving 4 packets.
var packets = dataPacket.Results
.Instances
.SelectMany(x =>
x.InstanceDatas.Select(y => new Packet()
{
Id = dataPacket.Id,
Results = new Result()
{
ResultName = dataPacket.Results.ResultName,
Instances = new List<Instance>()
{
new Instance()
{
InstanceDatas = new List<InstanceData>() {y},
InstanceName = x.InstanceName
}
}
}
}));
You can write a helper method which finds the possible names as keys and iterate over the keys. Then you build new object instances for each key you are checking. The source code can look like this:
private static IList<Packet> SplitByName(Packet packet) {
IList<string> names = packet.Results.Instances
.SelectMany(it => it.InstanceDatas)
.Select(it => it.Name)
.Distinct()
.ToList();
IList<Packet> result = new List<Packet>();
foreach (string name in names)
{
List<Instance> newInstances = packet.Results.Instances
.Select(it => new Instance {
InstanceName = it.InstanceName,
InstanceDatas = it.InstanceDatas
.Where(it => it.Name == name)
.ToList()
})
.Where(it => it.InstanceDatas.Any())
.ToList();
Result newResult = new Result {
ResultName = packet.Results.ResultName,
Instances = newInstances
};
result.Add(new Packet {
Id = packet.Id,
Results = newResult
});
}
return result;
}
For each name you are filtering the InstanceData instances for each Instance object. Depending on your needs you might want to add .Where(it => it.InstanceData.Any()) so you don't have any "empty" instances.

All the Model properties are binded as string and it throws "The value XX is not valid" in ModelState validation

I am getting value XX is not valid. But I am binding the correct datatype to the Model and I am still getting this error. Please find the error in . My controller is considering all datatype besides string to be not valid. Even the StartData and EndDate is throwing the same exception though I am binding the correct datatype.
I am not sure am I missing anything here. The worse part here is if I try to implement same (file) in another sample project it is working fine.
Following is my Model
public class Dept_User_Link
{
public Dept_User_Link()
{
StartDate = DateTime.Now;
EndDate = DateTime.Now;
}
private List<Dept_User_Link> deptUserLink = new List<Dept_User_Link>();
public int ID { get; set; }
[Required]
public int DeptID { get; set; }
[Required]
public int UserID { get; set; }
[Required]
public Guid Dummy { get; set; }
[Required]
public DateTime StartDate { get; set; }
[Required]
[DateRange(StartDateEditFieldName = "StartDate")]
public DateTime EndDate { get; set; }
}
and following is my controller
public ActionResult GridVwPartial()
{
var model = new Dept_User_Link().GetDeptUsersLink();
ViewData["Departments"] = new Department().GetDepartments().Select(x => new { DeptID = x.ID, Name = x.Name }).ToList();
ViewData["Users"] = new Users().GetUsers().Select(x => new { UserID = x.ID, Name = x.Name }).ToList();
ViewData["GuidVals"] = new GuidVal().GuidValData();
return PartialView("GridVwPartial", model);
}
public ActionResult AddNew(Dept_User_Link data) {
// Add 'data' values to the underlying datasource
// ...
var model = new Dept_User_Link().GetDeptUsersLink();
ViewData["Departments"] = new Department().GetDepartments().Select(x => new { DeptID = x.ID, Name = x.Name }).ToList();
ViewData["Users"] = new Users().GetUsers().Select(x => new { UserID = x.ID, Name = x.Name }).ToList();
return GridVwPartial();
}
and following is my View
#using ROCKtree.CCTVWeb.Models
#model IList<Dept_User_Link>
#{
Html.DevExpress().GridView<Dept_User_Link>(settings =>
{
settings.Name = "cascadingExample";
settings.CallbackRouteValues = new { Controller = "Grid", Action = "GridVwPartial" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Grid", Action = "AddNew" };
settings.CommandColumn.Visible = true;
settings.CommandColumn.ShowNewButtonInHeader = true;
settings.SettingsEditing.Mode = GridViewEditingMode.EditForm;
settings.KeyFieldName = "ID";
settings.Columns.Add(m => m.DeptID, column =>
{
column.EditorProperties().ComboBox(x =>
{
x.TextField = "Name";
x.ValueField = "DeptID";
x.DataSource = ViewData["Departments"];
x.ClientSideEvents.SelectedIndexChanged = "OnSelectedDeptChanges";
x.ValidationSettings.CausesValidation = true;
//x.ClientSideEvents.SelectedIndexChanged = "";
});
});
settings.Columns.Add(m => m.UserID, column =>
{
column.EditorProperties().ComboBox(x =>
{
x.TextField = "Name";
x.ValueField = "UserID";
//x.DataSource = ViewData["Users"];
x.LoadDropDownOnDemand = true;
x.CallbackRouteValues = new { Controller = "Grid", Action = "UserCallback" };
x.ClientSideEvents.BeginCallback = "UserComboBox_BeginCallback";
// x.ClientSideEvents.SelectedIndexChanged = "";
});
});
settings.Columns.Add(m => m.Dummy, column =>
{
column.EditorProperties().ComboBox(cmb =>
{
cmb.TextField = "Name";
cmb.ValueField = "ID";
cmb.DataSource = ViewData["GuidVals"];
});
});
settings.Columns.Add(m => m.StartDate, column =>
{
column.EditorProperties().DateEdit(clm =>
{
clm.TimeSectionProperties.Visible = true;
clm.DisplayFormatString = "dd-MMM-yy HH:mm";
clm.DisplayFormatInEditMode = true;
clm.TimeSectionProperties.TimeEditProperties.EditFormatString = "HH";
clm.TimeSectionProperties.TimeEditProperties.EditFormat = EditFormat.Custom;
clm.UseMaskBehavior = true;
clm.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
clm.ValidationSettings.Display = Display.Dynamic;
clm.ValidationSettings.CausesValidation = true;
clm.ValidationSettings.SetFocusOnError = true;
});
//column.SetEditItemTemplateContent(c =>
//{
// ViewContext.Writer.Write("<div class='form-group'><div class='input-group date' id='datetimepicker1'><input type='text' class=\"form-control\" /><span class=\"input-group-addon\">");
// ViewContext.Writer.Write("<span class=\"glyphicon glyphicon-calendar\"></span></span></div></div>");
//});
});
settings.Columns.Add(m => m.EndDate, column =>
{
column.EditorProperties().DateEdit(clm =>
{
clm.TimeSectionProperties.Visible = true;
clm.DisplayFormatString = "dd-MMM-yy HH:mm";
clm.DisplayFormatInEditMode = true;
clm.TimeSectionProperties.TimeEditProperties.EditFormatString = "HH";
clm.TimeSectionProperties.TimeEditProperties.EditFormat = EditFormat.Custom;
clm.UseMaskBehavior = true;
clm.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
clm.ValidationSettings.Display = Display.Dynamic;
clm.ValidationSettings.CausesValidation = true;
clm.ValidationSettings.SetFocusOnError = true;
});
//column.SetEditItemTemplateContent(c =>
//{
// ViewContext.Writer.Write("<div class='form-group'><div class='input-group date' id='datetimepicker1'><input type='text' class=\"form-control\" /><span class=\"input-group-addon\">");
// ViewContext.Writer.Write("<span class=\"glyphicon glyphicon-calendar\"></span></span></div></div>");
//});
});
}).Bind(Model).GetHtml();
}
Data for the Dummy Property
public IList<GuidVal> GuidValData()
{
if (guidVal == null || guidVal.Count() == 0)
{
//List<Department> deptList = new List<Department>();
List<string> deptValues = File.ReadLines(path).ToList();
foreach (string data in deptValues)
{
if (!string.IsNullOrEmpty(data))
{
string[] str = data.Split(separators, StringSplitOptions.None);
GuidVal deptLnk = new GuidVal();
deptLnk.ID = Guid.Parse(str[0]);
deptLnk.Name = str[1];
this.guidVal.Add(deptLnk);
}
}
}
return guidVal;
}

C# 6.0 List that is getting syntax Error , ' , '

I am parsing a webpage, the issue I am coming across is that ["www.abc.com/"] and ["www.def.com/"] = new List() is getting a "syntax error,',' expected." I made a class that set property for the HtmlTarget, public string Id { get; set; } public Action<HtmlElement> Action { get; set; }, anybody have any suggestions ?
public void Spider(string sURL, HtmlDocument doc, int choice)
{
var urlTargets = new Dictionary<string, List<HtmlTarget>>
{
["www.abc.com/"] = new List<HtmlTarget>()
{
new HtmlTarget
{
Id = "search",
Action = e => e.SetAttribute("value", m_sMfgPartNbr)
},
new HtmlTarget
{
Id = "submit",
Action = e => e.InvokeMember("Click")
}
},
["www.def.com/"] = new List<HtmlTarget>()
{
new HtmlTarget
{
Id = "part",
Action = e => e.SetAttribute("value", m_sMfgPartNbr)
},
new HtmlTarget
{
Id = "submit",
Action = e => e.InvokeMember("Click")
}
}
};
List<HtmlTargets> targets = null;
if (urlTargets.TryGetValue(url, out targets))
{
var inputs = doc.Body.GetElementsByTagName("input");
foreach (HtmlElement element in inputs)
{
var id = element.GetAttribute("id");
foreach(var target in targets)
{
if (target.Id == id)
target.Action(element);
}
}
}
}
The correct syntax prior to C# 6 would be
var urlTargets = new Dictionary<string, List<HtmlTarget>>
{
{ "www.eciaauthorized.com/search", new List<HtmlTarget>()
...
},
{ "www.findchips.com/search", new List<HtmlTarget>()
...
}
}

C# - Filling List with LINQ from another List<>

Here's my main class:
public class Subject
{
public struct Class
{
public byte Day { get; set; }
public DateTime Time { get; set; }
}
public string Name { get; set; }
public List<Class> Data { get; set; }
}
For example,
List<Subject> subjects = new List<Subject>
{
new Subject()
{
Name = "Math",
Data = new List<Class>()
{
new Class { Day = 2, Time = Convert.ToDateTime("8:30") },
new Class { Day = 2, Time = Convert.ToDateTime("10:25") }
}
},
new Subject()
{
Name = "Astronomy",
Data = new List<Class>()
{
new Class { Day = 2, Time = Convert.ToDateTime("12:30") },
new Class { Day = 4, Time = Convert.ToDateTime("14:30") }
}
},
new Subject()
{
Name = "Chemistry",
Data = new List<Class>()
{
new Class { Day = 3, Time = Convert.ToDateTime("8:30") }
}
},
new Subject()
{
Name = "Physics",
Data = new List<Class>()
{
new Class { Day = 3, Time = Convert.ToDateTime("10:25") },
new Class { Day = 4, Time = Convert.ToDateTime("12:30") }
}
}
};
The data above is filling up by parsing JSON.
But now I need to do next:
1.Select all distinct Day (in this case: 2, 3, 4);
2. Fill this days with subject (Name and Time).
I created this:
public class Schedule
{
public struct Subject
{
public string Name { get; set; }
public DateTime Time { get; set; }
}
public struct Day
{
public byte DayOfWeek { get; set; }
public List<Subject> Subjects { get; set; }
}
public List<Day> Days { get; set; }
}
so I except to do something like this:
Schedule schedule = new Schedule();
schedule.Days = new List<Schedule.Day>()
{
new Schedule.Day()
{
DayOfWeek = 2,
Subjects = new List<Schedule.Subject>()
{
new Schedule.Subject() { Name = "Math", Time = Convert.ToDateTime("8:30") },
new Schedule.Subject() { Name = "Math", Time = Convert.ToDateTime("10:25") },
new Schedule.Subject() { Name = "Astronomy", Time = Convert.ToDateTime("12:30") }
}
},
new Schedule.Day()
{
DayOfWeek = 3,
Subjects = new List<Schedule.Subject>()
{
new Schedule.Subject() { Name = "Chemistry", Time = Convert.ToDateTime("8:30") },
new Schedule.Subject() { Name = "Physics", Time = Convert.ToDateTime("10:25") },
}
},
new Schedule.Day()
{
DayOfWeek = 4,
Subjects = new List<Schedule.Subject>()
{
new Schedule.Subject() { Name = "Physics", Time = Convert.ToDateTime("12:30") },
new Schedule.Subject() { Name = "Astronomy", Time = Convert.ToDateTime("14:30") }
}
}
};
The question is How I can select data to Schedule from List<Subjects> with LINQ (I don't wanna use loops).
var result = subjects
.SelectMany(s => s.Data.Select(x => new { s.Name, x.Day, x.Time }))
.GroupBy(x => x.Day)
.Select(g => new Schedule.Day
{
DayOfWeek = g.Key,
Subjects = g.Select(item => new Schedule.Subject
{
Name = item.Name,
Time = item.Time
})
.OrderBy(item => item.Time)
.ToList()
})
.OrderBy(gItem => gItem.DayOfWeek)
.ToList();
And then....
Schedule schedule = new Schedule();
schedule.Days = result;
It's also weird to put the List<Day> inside the schedule class.
Out of fun I've rewritten the solution to promote the Query-Expression Syntax.
IEnumerable<Schedule.Day> scheduledDays =
from subj in subjList
from cl in subj.Data
select new { Class = cl, SubjectName = subj.Name } into classWithSubject
group classWithSubject by classWithSubject.Class.Day into classesByDay
orderby classesByDay.Key
select new Schedule.Day()
{
DayOfWeek = classesByDay.Key,
Subjects = (from cl in classesByDay
orderby cl.Class.Time
select new Schedule.Subject() { Name = cl.SubjectName, Time = cl.Class.Time }).ToList()
};
Schedule sched = new Schedule() { Days = scheduledDays.ToList() };
If I right understood, You can use ForEach LINQ:
schedule.Days.ForEach(x => x.Subjects.ForEach(y => Console.WriteLine($"{y.Name}, {y.Time}")));
Instead of
Console.WriteLine($"{y.Name}, {y.Time}")
You can write this info into some variables.
P.S. ForEach will pass all elements of list.
Try this:
var newQuery = subjects.SelectMany(y => y.Data.Select(x=> new {x.Day,x.Time,y.Name }));
var newQuery2 = newQuery.OrderBy(x=>x.Day).OrderBy(x=>x.Time).GroupBy(x => x.Day);
var newQuery3 = newQuery2.Select(x => new Schedule.Day
{
DayOfWeek = x.Key,
Subjects = x.Select(y => new Schedule.Subject
{
Time = y.Time,
Name = y.Name
}).ToList()
});

C# - How to search into the ObservableCollection?

I am developing a app in windows phone 7. I have a list box with items of observable collection. Now i want to search into that list box items. I want filter the items which is typed in the Text Box. If i type 'a' mean the list box items should shows the items which is start with 'a'. If i type 'az' mean it should show the items start with 'az'.
public class SortingExampleViewModel : ReactiveObject
{
public string _SearchText = "";
public string SearchText
{
get { return _SearchText; }
set { this.RaiseAndSetIfChanged(x => x.SearchText, value); }
}
public static ObservableCollection<items> _sordtedList;
public ObservableCollection<items> sordtedList
{
get { return _sordtedList; }
set { this.RaiseAndSetIfChanged(x => x.sordtedList, value); }
}
public static ObservableCollection<items> _tempSordtedList;
public ObservableCollection<items> tempSordtedList
{
get { return _tempSordtedList; }
set { this.RaiseAndSetIfChanged(x => x.tempSordtedList, value); }
}
public ReactiveAsyncCommand ExecuteSearch { get; set; }
public SortingExampleViewModel()
{
ObservableCollection<items> myData = new ObservableCollection<items>()
{
new items(){firstName = "Vijay Dhas",age=27},
new items(){firstName = "Ramaraj",age=28},
new items(){firstName = "Arun",age=29},
new items(){firstName = "Prabhu",age=30},
new items(){firstName = "Pranesh",age=31},
new items(){firstName = "Testing",age=32}
};
sordtedList = new ObservableCollection<items>(from i in myData orderby i.firstName select i);
var canConfirm = this.WhenAny(x => x.SearchText, (search) => SearchMethod(search.Value));
ExecuteSearch = new ReactiveAsyncCommand(canConfirm, 0);
}
public Boolean SearchMethod(String searchValue)
{
var col = (ObservableCollection<items>)(sordtedList.Where(p => p.firstName.Contains(searchValue)));
foreach (items objTest in col)
{
tempSordtedList.Add(objTest);
}
sordtedList = tempSordtedList;
return true;
}
}
public class items
{
public string firstName { get; set; }
public int age { get; set; }
}
But here i am getting Error in this line:
var col = (ObservableCollection<items>)(sordtedList.Where(p => p.firstName.Contains(searchValue)));
It showing Unknown error.
Please help me to search in the listbox.
I got the solution.
public SortingExampleViewModel()
{
ObservableCollection<items> myData = new ObservableCollection<items>()
{
new items(){firstName = "Vijay Dhas",age=27},
new items(){firstName = "Ramaraj",age=28},
new items(){firstName = "Arun",age=29},
new items(){firstName = "Prabhu",age=30},
new items(){firstName = "Pranesh",age=31},
new items(){firstName = "Testing",age=32}
};
sordtedList = new ObservableCollection<items>(from i in myData orderby i.firstName select i);
temp = sordtedList;
var canConfirm = this.WhenAny(x => x.SearchText, (search) => SearchMethod(search.Value));
ExecuteSearch = new ReactiveAsyncCommand(canConfirm, 0);
}
public Boolean SearchMethod(String searchValue)
{
ObservableCollection<items> tempList = new ObservableCollection<items>();
tempList = temp;
tempSordtedList = new ObservableCollection<items>();
foreach (items items in tempList)
{
if (items.firstName.ToLower().StartsWith(searchValue.ToLower()))
{
tempSordtedList.Add(items);
}
}
sordtedList = tempSordtedList;
return true;
}
You are casting an IEnumerable (result of the Linq query) to an ObservableCollection.
Use this instead:
var col = sordtedList.Where(p => p.firstName.Contains(searchValue));
Since you only use the variable col to iterate over it, you do not need to cast it.

Categories

Resources