I have an Silverlight 5 application which is using the Silverlight Toolkit. Now, the Silverlight Toolkit chart control doesnt always show X axis values when there is only one result in the resultset that returns from my webserivce.
The first image shows that my chart is loaded properly when selecting a big enough resultset.
The second image shows that it doesn't when the resultset exists of 1 item.
This is my implementation:
TimeSpan monthSpan = TimeSpan.FromDays(30.0);
TimeSpan daySpan = TimeSpan.FromDays(1.0);
TimeSpan hourSpan = TimeSpan.FromHours(1.0);
foreach (TagValueResult res in e.NewItems)
{
if (res != null)
{
LineSeries lineSeries = new LineSeries()
{
Title = string.Format("{0}" + Environment.NewLine + " {2} ({1})", res.Name, res.Attributes["UOM"], res.Attributes["Description"]),
ItemsSource = res.Values,
DependentValueBinding = new System.Windows.Data.Binding("Value"),
IndependentValueBinding = new System.Windows.Data.Binding("Key"),
Tag = res,
PolylineStyle = Resources["thinLineStyle"] as Style,
//DataPointStyle = Resources["dataPointStyle"] as Style
};
if (res.Values.Any() && chart.Series.Any() == false)
{
TimeSpan graphSpan = res.Values.ToList().Last().Key - res.Values.ToList().First().Key;
lineSeries.IndependentAxis = new DateTimeAxis
{
Minimum = res.Values.ToList().First().Key,
Maximum = res.Values.ToList().Last().Key,
Interval = 1,
Orientation = AxisOrientation.X,
Location = AxisLocation.Bottom
};
if (graphSpan > monthSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 5;
}
else if (graphSpan > daySpan && graphSpan < monthSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
else if (graphSpan > hourSpan && graphSpan < daySpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Hours;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
else if (graphSpan < hourSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Minutes;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 15;
}
else
{
//sometimes all comparisons fail, just back up to a safe interval of 1 day.
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
}
chart.Series.Add(lineSeries);
}
}
Do you have any idea's? I'm out of possible solutions.
A collection with one item will have incorrect behavior in several places of your code.
Here graphSpan will equal zero:
TimeSpan graphSpan = res.Values.ToList().Last().Key - res.Values.ToList().First().Key;
And here Maximum and Minimum will be the same:
lineSeries.IndependentAxis = new DateTimeAxis
{
Minimum = res.Values.ToList().First().Key,
Maximum = res.Values.ToList().Last().Key,
I suggest that you add another if-block and construct a different axis for the special case when the collection has only 1 item.
var values = res.Values.ToList();
TimeSpan graphSpan = values.Last().Key - values.First().Key;
if (graphSpan == TimeSpan.Zero)
{
lineSeries.IndependentAxis = new DateTimeAxis
{
Orientation = AxisOrientation.X,
Location = AxisLocation.Bottom
};
}
else
{
lineSeries.IndependentAxis = new DateTimeAxis
{
Minimum = values.First().Key,
Maximum = values.Last().Key,
Orientation = AxisOrientation.X,
Location = AxisLocation.Bottom
};
if (graphSpan > monthSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 5;
}
else if (graphSpan > daySpan && graphSpan < monthSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
else if (graphSpan > hourSpan && graphSpan < daySpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Hours;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
else if (graphSpan < hourSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Minutes;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 15;
}
else
{
//sometimes all comparisons fail, just back up to a safe interval of 1 day.
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
}
Related
I am trying to display points from 7 files. Each file corresponds to a day, and I am trying to add a button where it takes the last 7 created files and displays them as x=dateTime and y= value. what this code currently does is that only displays the x axis on the left and right side.
private void button1_Click(object sender, EventArgs e)
{
chart1.Titles.Clear();
chart1.Series.Clear();
xAxis.Clear();
yAxis.Clear();
var Series1 = new Series
{
Name = comboBox2.Text,
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Area
};
this.chart1.Series.Add(Series1);
double measur = 0;
//clear graph
string Folder = #"\\Engineer\DI-808\outlooktest\";
var files = new DirectoryInfo(Folder).GetFiles("*_*");
string latestfile = "";
DateTime lastModified = DateTime.MinValue;
List<string> filesD = new List<string>();
DateTime endDate=DateTime.Now;
DateTime startDate= DateTime.Now.AddDays(-3);
DateTime dateToCheck;
Console.WriteLine(startDate + " " + endDate);
foreach (FileInfo file in files)
{
//Console.WriteLine(file.Name+"before");
string edited = file.Name.Remove(0, 6);
//Console.WriteLine(edited+"during");
char[] csv = { '.', 'c', 's', 'v'};
edited = edited.TrimEnd(csv);
//Console.WriteLine(edited + "after CSV");
edited = edited.Remove(10, 9);
// Console.WriteLine(edited+"after");
dateToCheck = Convert.ToDateTime(edited);
Console.WriteLine(dateToCheck+" date to check");
Console.WriteLine(startDate+" start");
Console.WriteLine(endDate+ " end" );
// if ( DateTime.Compare(dateToCheck,startDate)>=0dateToCheck >= startDate && dateToCheck <= endDate);
if (DateTime.Compare(dateToCheck, startDate)>=0 && DateTime.Compare(dateToCheck, endDate)<=0)
{
latestfile = file.Name;
filesD.Add(latestfile);
Console.WriteLine(latestfile+" dweeb");
}
}
Console.WriteLine(filesD.Count());
for (int i = 0; i < filesD.Count(); i++)
Console.WriteLine(files[i]);
string lineData;
try
{
for (int i=0;i<filesD.Count();i++) {
readData = new StreamReader(#"\\egvfps1.egv.mapes.local\Engineer\DI-808\outlooktest\" + filesD[i]);
for (int k = 0; k < 21; k++)
readData.ReadLine();
while ((lineData = readData.ReadLine()) != null)
{
if (Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) <= 0.001)
measur = 0;
else
{
measur = Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) * 110;
xAxis.Add(Convert.ToDateTime(lineData.Split(',')[1]));
yAxis.Add(measur);
}
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
readData.Close();
this.chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
this.chart1.Titles.Add(comboBox2.Text + "(" + xAxis[0].ToString("MM/dd/yyyy") + ")");
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
for (int i = 0; i < xAxis.Count(); i++)
{
chart1.Series[comboBox2.Text].Points.AddXY(xAxis[i], yAxis[i]);
}
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
chart1.Series[0].XValueType = ChartValueType.DateTime;
}
enter image description here
I know its somewhere in the Xaxis interval type part,but I don't know what values to put in.
Any suggestions helps!
I have a DevExpress gridview with a description column that has column header filters enabled. The problem is that having these filters enabled makes it so an entry is added to the drop down for every data item in the list which isn't really desirable because the entries are generally paragraphs of text. Instead I would like to restrict the options to just All, Blanks, and Non blanks but I haven't been able to find a clear example of how this might be accomplished. Thanks for the help!
ANSWER:
settings.HeaderFilterFillItems = (sender, e) =>
{
if (e.Column.FieldName == "Description")
{
e.Values.Clear();
e.AddShowAll();
e.Values.Insert(1, FilterValue.CreateShowBlanksValue(e.Column, "(Blanks)"));
e.Values.Insert(2, FilterValue.CreateShowNonBlanksValue(e.Column, "(Non Blanks)"));
}
};
This question is similar than yours https://www.devexpress.com/Support/Center/Question/Details/Q477323/gridview-how-to-customize-header-filter-items
And here in the view you have the custom filter items, using settings.HeaderFilterFillItems https://demos.devexpress.com/MVCxGridViewDemos/Filtering/Filtering
#Html.DevExpress().GridView(
settings => {
settings.Name = "gvFiltering";
settings.CallbackRouteValues = new { Controller = "Filtering", Action = "FilteringPartial", EnableCheckedListMode = ViewBag.EnableCheckedListMode };
settings.Width = Unit.Percentage(100);
settings.Columns.Add("CompanyName");
settings.Columns.Add("Country");
settings.Columns.Add("City");
settings.Columns.Add("UnitPrice").PropertiesEdit.DisplayFormatString = "c";
settings.Columns.Add("Quantity");
settings.Columns.Add("Discount").PropertiesEdit.DisplayFormatString = "p0";
settings.Columns.Add(column => {
column.FieldName = "Total";
column.PropertiesEdit.DisplayFormatString = "c";
column.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
column.UnboundExpression = "UnitPrice * Quantity * (1 - Discount)";
});
settings.Settings.ShowHeaderFilterButton = true;
settings.SettingsPopup.HeaderFilter.Height = 200;
var headerFilterMode = ViewBag.EnableCheckedListMode ? GridHeaderFilterMode.CheckedList : GridHeaderFilterMode.List;
foreach(GridViewDataColumn column in settings.Columns)
column.SettingsHeaderFilter.Mode = headerFilterMode;
settings.HeaderFilterFillItems = (sender, e) => {
ASPxGridView grid = (ASPxGridView)sender;
if(e.Column.FieldName == "Total") {
e.Values.Clear();
if(e.Column.SettingsHeaderFilter.Mode == GridHeaderFilterMode.List)
e.AddShowAll();
int step = 100;
for(int i = 0; i < 10; i++) {
double start = step * i;
double end = start + step - 0.01;
e.AddValue(string.Format("from {0:c} to {1:c}", start, end), string.Empty, string.Format("[Total] >= {0} and [Total] <= {1}", start, end));
}
e.AddValue(string.Format("> {0:c}", 1000), string.Empty, "[Total] > 1000");
} else if(e.Column.FieldName == "Quantity") {
int max = 0;
for(int i = 0; i < e.Values.Count; i++) {
int value;
if(!int.TryParse(e.Values[i].Value, out value))
continue;
if(value > max)
max = value;
}
e.Values.Clear();
if(e.Column.SettingsHeaderFilter.Mode == GridHeaderFilterMode.List)
e.AddShowAll();
int step = 10;
for(int i = 0; i < max / step + 1; i++) {
int start = step * i;
int end = start + step - 1;
e.AddValue(string.Format("from {0} to {1}", start, end), string.Empty, string.Format("[Quantity] >= {0} and [Quantity] <= {1}", start, end));
}
}
};
}).Bind(Model).GetHtml()
I am querying for report module to show a pivot table, some of the columns are dynamic, so i am creating a dictionary object to construct my object, so let say i have 1 user_applications table with around 40k records, and this table also referenced by other tables.
i do this :
//masters
var master_genders = CTX.translate_value_ms.Where(a => a.PSF_type == "SEX").OrderBy(o => o.translate_value_id).ToList();
var master_edus = CTX.education_lvl_ms.OrderBy(o => o.education_lvl_id).ToList();
var master_stats = CTX.app_status_ms.OrderBy(o => o.status_order).ToList();
var master_criteria = CTX.criteria_suggestion_templates.OrderBy(o => o.criteria_suggestion_template_id).ToList();
//
//load mapping
Dictionary<int, int> Gender_Map = new Dictionary<int, int>();
int start = 0;
foreach (var m in master_genders)
{
Gender_Map.Add(m.translate_value_id, start);
start++;
}
Dictionary<int, int> Edu_Map = new Dictionary<int, int>();
start = 0;
foreach (var e in master_edus)
{
Edu_Map.Add(e.education_lvl_id, start);
start++;
}
Dictionary<string, int> Stat_Map = new Dictionary<string, int>();
start = 0;
var first = master_stats.GroupBy(g => g.status_web).OrderBy(o => o.FirstOrDefault().status_order);
foreach (var s in first)
{
Stat_Map.Add(s.Key, start);
start++;
}
Dictionary<int, int> Criteria_Map = new Dictionary<int, int>();
start = 0;
foreach (var m in master_criteria)
{
Criteria_Map.Add(m.criteria_suggestion_template_id, start);
start++;
}
//
var idx = 0;
var cur_age = 0;
int int_jobfair = 0;
int total = 0;
user_address address_dom = null;
string key = "";
bool check = false;
ReportSubObject obj = null;
user_edu user_last_edu = null;
user_test last_test = null;
criteria_suggestion checkcrit = null;
var usertest = CTX.user_tests;
var testcriteria = CTX.criteria_suggestions;
double total_a = 0;
double total_b = 0;
double total_c = 0;
double total_d = 0;
double total_e = 0;
double total_f = 0;
var addresses = CTX.user_addresses.Where(a => a.address_type == 0).ToList();
foreach (var itm in apps.ToList())
{
var a_begin = DateTime.Now;
total = 0;
address_dom = null;
key = "";
check = false;
obj = null;
user_last_edu = null;
last_test = null;
checkcrit = null;
address_dom = addresses.Where(a => a.user_id == itm.user_id).FirstOrDefault();
var a_end = DateTime.Now;
DateTime b_begin = DateTime.Now;
DateTime b_end = DateTime.Now;
DateTime c_begin = DateTime.Now;
DateTime c_end = DateTime.Now;
DateTime d_begin = DateTime.Now;
DateTime d_end = DateTime.Now;
DateTime e_begin = DateTime.Now;
DateTime e_end = DateTime.Now;
DateTime f_begin = DateTime.Now;
DateTime f_end = DateTime.Now;
b_begin = DateTime.Now;
int_jobfair = 0;
if (itm.manager_id != null)
int_jobfair = 1;
key = int_jobfair + " - " + itm.applied_date.Value.Month + " - " + itm.posting.job_id + " - " + itm.posting.location_id + " - " + itm.posting.job_cat_id + " - " + itm.posting.office_cat_id + " - " + (address_dom != null && address_dom.state_id != null ? address_dom.state_id.ToString() : "0");
check = SubmissionObj.ContainsKey(key);
if (!check)
{
obj = new ReportSubObject();
obj.Source = (itm.manager_id != null ? "Job Fair" : "Website");
obj.Job = myTI.ToTitleCase(itm.posting.job_m.PSF_Desc.ToLower());
obj.Location = myTI.ToTitleCase(itm.posting.job_location_m.PSF_Desc.ToLower());
obj.JobCat = myTI.ToTitleCase(itm.posting.job_category_m.PSF_Desc.ToLower());
obj.OfficeCat = myTI.ToTitleCase(itm.posting.office_category_m.PSF_Desc.ToLower());
obj.ApplyProv = (address_dom != null && address_dom.state_id != null ? address_dom.state_m.state_desc : "");
obj.from = (DateTime)itm.applied_date;
obj.Total = total += 1;
#region gender
obj.KeyPairGender = new List<int>();
master_genders.ForEach(b => obj.KeyPairGender.Add(0));
if (itm.user_list.gender_id != null)
{
idx = Gender_Map[(int)itm.user_list.gender_id];
//obj.KeyPairGender[idx] = new KeyValuePair<string, int>(obj.KeyPairGender[idx].Key, obj.KeyPairGender[idx].Value + 1);
obj.KeyPairGender[idx] += 1;
}
#endregion
#region edu
obj.KeyPairEdu = new List<int>();
master_edus.ForEach(b => obj.KeyPairEdu.Add(0));
user_last_edu = itm.user_list.user_edus.OrderByDescending(o => o.edu_lvl_id).FirstOrDefault();
if (user_last_edu != null)
{
idx = Edu_Map[(int)user_last_edu.edu_lvl_id];
obj.KeyPairEdu[idx] += 1;
}
#endregion
b_end = DateTime.Now;
c_begin = DateTime.Now;
#region Age
obj.AgeRange = new int[5];
for (int i = 0; i < 5; i++)
{
obj.AgeRange[i] = 0;
}
cur_age = itm.applied_date.Value.Year - itm.user_list.birthday.Value.Year;
if (itm.user_list.birthday > ((DateTime)itm.applied_date).AddYears(-cur_age)) cur_age--;
if (cur_age >= 18 && cur_age <= 21)
obj.AgeRange[0] += 1;
else if (cur_age >= 22 && cur_age <= 24)
obj.AgeRange[1] += 1;
else if (cur_age >= 25 && cur_age <= 27)
obj.AgeRange[2] += 1;
else if (cur_age >= 28 && cur_age <= 30)
obj.AgeRange[3] += 1;
else if (cur_age > 30)
obj.AgeRange[4] += 1;
#endregion
#region appstatus
obj.KeyPairAppStat = new List<int>();
foreach (var loop in first)
{
obj.KeyPairAppStat.Add(0);
}
if (itm.app_status_id != null)
{
idx = Stat_Map[itm.app_status_m.status_web];
obj.KeyPairAppStat[idx] += 1;
}
#endregion
#region criteria
obj.KeyPairCriteria = new List<int>();
master_criteria.ForEach(b => obj.KeyPairCriteria.Add(0));
if (itm.online_test_id != null)
{
last_test = usertest.Where(a => a.user_id == itm.user_id && a.package_id == itm.online_test.package_id).OrderByDescending(o => o.date_score).FirstOrDefault();
if (last_test != null)
{
if (last_test.total_score != null)
{
checkcrit = testcriteria.Where(a => a.package_id == last_test.package_id &&
(last_test.total_score >= a.score_from && last_test.total_score <= a.score_to)
).FirstOrDefault();
if (checkcrit != null)
{
idx = Criteria_Map[(int)checkcrit.criteria_opt_id];
obj.KeyPairCriteria[idx] += 1;
}
}
}
}
#endregion
SubmissionObj.Add(key, obj);
c_end = DateTime.Now;
}
else
{
d_begin = DateTime.Now;
var tmp = SubmissionObj[key];
tmp.Total++;
if (tmp.to < itm.applied_date)
tmp.to = (DateTime)itm.applied_date;
#region gender
if (itm.user_list.gender_id != null)
{
idx = Gender_Map[(int)itm.user_list.gender_id];
tmp.KeyPairGender[idx] += 1;
}
#endregion
d_end = DateTime.Now;
e_begin = DateTime.Now;
#region edu
user_last_edu = itm.user_list.user_edus.OrderByDescending(o => o.edu_lvl_id).FirstOrDefault();
if (user_last_edu != null)
{
idx = Edu_Map[(int)user_last_edu.edu_lvl_id];
tmp.KeyPairEdu[idx] += 1;
}
#endregion
#region age
cur_age = itm.applied_date.Value.Year - itm.user_list.birthday.Value.Year;
if (itm.user_list.birthday > ((DateTime)itm.applied_date).AddYears(-cur_age)) cur_age--;
if (cur_age >= 18 && cur_age <= 21)
tmp.AgeRange[0] += 1;
else if (cur_age >= 22 && cur_age <= 24)
tmp.AgeRange[1] += 1;
else if (cur_age >= 25 && cur_age <= 27)
tmp.AgeRange[2] += 1;
else if (cur_age >= 28 && cur_age <= 30)
tmp.AgeRange[3] += 1;
else if (cur_age > 30)
tmp.AgeRange[4] += 1;
#endregion
#region appstatus
if (itm.app_status_id != null)
{
idx = Stat_Map[itm.app_status_m.status_web];
tmp.KeyPairAppStat[idx] += 1;
}
#endregion
e_end = DateTime.Now;
f_begin = DateTime.Now;
#region criteria
if (itm.online_test_id != null)
{
last_test = usertest.Where(a => a.user_id == itm.user_id && a.package_id == itm.online_test.package_id).OrderByDescending(o => o.date_score).FirstOrDefault();
if (last_test != null)
{
if (last_test.date_score != null)
{
checkcrit = testcriteria.Where(a => a.package_id == last_test.package_id &&
(last_test.total_score >= a.score_from && last_test.total_score <= a.score_to)
).FirstOrDefault();
if (checkcrit != null)
{
idx = Criteria_Map[(int)checkcrit.criteria_opt_id];
tmp.KeyPairCriteria[idx] += 1;
}
}
}
}
#endregion
f_end = DateTime.Now;
}
total_a += (a_end - a_begin).TotalSeconds;
total_b += (b_end - b_begin).TotalSeconds;
total_c += (c_end - c_begin).TotalSeconds;
total_d += (d_end - d_begin).TotalSeconds;
total_e += (e_end - e_begin).TotalSeconds;
total_f += (f_end - f_begin).TotalSeconds;
}
as u notice in above code, i have a few sub queries inside foreach loop, and i put a few variables to count which part took most time in seconds, and its true that the sub queries part took the longest, overall it took around 2 minutes for those codes to be executed, so i tried to move all sub queries outside foreach loop, i do this :
var customapp = apps.Select(x => new
{
dom_address = x.user_list.user_addresses.Where(a => a.address_type == 0).FirstOrDefault(),
manager_id = x.manager_id,
applied_date = x.applied_date,
job_id = x.posting.job_id,
job_desc = x.posting.job_m.PSF_Desc,
location_id = x.posting.location_id,
loc_desc = x.posting.job_location_m.PSF_Desc,
job_cat_id = x.posting.job_cat_id,
job_cat_desc = x.posting.job_category_m.PSF_Desc,
office_cat_id = x.posting.office_cat_id,
office_cat_desc = x.posting.office_category_m.PSF_Desc,
gender_id = x.user_list.gender_id,
birthday = x.user_list.birthday,
edu = x.user_list.user_edus.OrderByDescending(o => o.edu_lvl_id).FirstOrDefault(),
status_PSF_id = x.app_status_id,
status_from_PSF = x.app_status_m.status_web,
online_test_id = x.online_test_id,
last_test = x.user_tests.Where(a => a.user_id == x.user_id && a.package_id == x.online_test.package_id).OrderByDescending(o => o.date_score).FirstOrDefault()
});
DateTime end_z = DateTime.Now;
double total_z = (end_z - begin_z).TotalSeconds;
foreach (var itm in customapp.ToList())
{
//logic to construct my dictionary as before, but without sub queries.
}
the second code it does not improve the speed, instead it took longer than previous one, can u tell me what can i do to optimize my query?
The problem is that you are doing extra db calls for each subquery for each application.
This is how you can avoid it:
// Plain query, not doing subqueries. Unfortunately brings extra rows in memory.
var q =
from app in ctx.Applications
join s in ctx.SubObjectsOne on app.Id equals s.AppId into joinedSubObjectOne
from subObjectOne in joinedSubObjectOne.DefaultIfEmpty()
where subObjectOne.SomeProperty == 0 // additional sub object criteria
select new { app, subObjectOne };
var l = q.ToList();
// From now on objects are materialized, doing the rest in memory:
var translated =
from i in l
group i by i.app.Id into g
select new
{
app = g.First().app,
// This is expensive too, but not doing separate db requests.
SubObjectOneByMaxProperty = g.Select(i => i.subObjectOne).OrderByDescending(s => s.SomeOrder).FirstOrDefault()
};
var translatedList = translated.ToList();
You can use this approach if your sub-object counts are not very high.
If you can figure out how to compute a needed value using sql aggregates, it would be even better. For example,
subObjects.Where(..).OrderByDescencing(..).First(..) would turn into subObjects.Max(s=>s.SomeProp), if you need just a max value, not an entire object. It would compute directly in db without extra db calls.
And an even better approach would be to avoid computations at the time of building a report. You can denormalize your data slightly, for example - store the ids of needed objects in an aggregation table, and update the table when related data changes:
table aggregated_data(app_id, address_id, max_edu_lvl_id, max_score_test_id)
I have looked at "similar" questions but can't actually find anything that applies, surprisingly. I calculate how many data points I would like to create on my Mschart Line Chart with a sum using imported converted data. Using the result of this, I divide it by another number that varies and this is the space I want to have between each datapoint. 124 is constant.
300 (varies) / 124 (X-Axis) = 2.419354838709677 (this is the space I want between each point)
I thought about creating a for loop like so
for (double i = 1; i < samples_hd; i++)
{
// distribute data points evenly here
}
A file is going to be read through into the chart, so far I have manually added data points as I'm not sure at all how to add them like above ^.
var sn = new System.Windows.Forms.DataVisualization.Charting.Series(English.Sam_Num);
sn.ChartType = SeriesChartType.Line;
sn.Points.Add(new DataPoint(9, 30));
sn.Points.Add(new DataPoint(150, 28));
sn.XAxisType = AxisType.Primary;
Chart_Line.Series.Add(sn);
Chart_Line.ChartAreas[0].AxisX.Minimum = 0;
Chart_Line.ChartAreas[0].AxisX.Maximum = 124;
Chart_Line.ChartAreas[0].AxisX.Interval = 15;
Chart_Line.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
It took such a long time to get it working, but it works :) My graph actually has 3 series, but for the example I will just show the 2 series.
private void Main(byte[] rec_arr)
{
var series1 = new Series("series1");
series1 .ChartType = SeriesChartType.Line;
series1 .MarkerStyle = MarkerStyle.Circle;
series1 .MarkerSize = 3;
series1 .YAxisType = AxisType.Primary;
series1 .Color = Color.Navy;
var series2 = new Series("series2");
series2 .ChartType = SeriesChartType.Line;
series2 .MarkerStyle = MarkerStyle.Triangle;
series2 .MarkerSize = 3;
series2 .YAxisType = AxisType.Primary;
series2 .Color = Color.Crimson;
foreach (var series in Chart1.Series)
{
series.Points.Clear();
}
double interval1 = 0;
double interval2 = File_Details.time / (double)124;
int Offset2 = 502;
int Offset3 = 750;
float data1, data2;
if (File_Details.time == 0)
{
Label_Error_Graph.Visible = true;
Chart1.ChartAreas[0].AxisX.Maximum = 0;
Chart1.ChartAreas[0].AxisX.Minimum = 0;
Chart1.Series[0].Points.Add(0);
Chart1.Series[1].Points.Add(0);
}
else
{
Label_Error_Graph.Visible = false;
}
for (interval1 = 0; interval1 < File_Details.time; interval1 += interval2)
{
data1 = DecodeSingle(rec_arr, Offset3);
if (Chart1.Series.IndexOf("series1") == -1)
{
Chart1.Series.Add(series1);
}
Offset3 = Offset3 + 2;
if (data1 < 300)
{
Chart1.Series[0].Points.AddXY(interval1, supply);
}
else
{
Chart1.Series[0].Points.AddXY(interval1, 300);
}
}
for (interval1 = 0; interval1 < File_Details.time; interval1 += interval2)
{
data2 = DecodeSingle(rec_arr, Offset2) / (float)100;
if (Chart1.Series.IndexOf("series2") == -1)
{
Chart1.Series.Add(series2);
}
Offset2 = Offset2 + 2;
if (data2 < 150)
{
Chart1.Series[1].Points.AddXY(interval1, data2);
}
else
{
Chart1.Series[1].Points.AddXY(interval1, 150);
}
}
}
I have a list that has some records which is bind with a datagridview.This list contains some properties like pageno , pagebreak, rowno etc. Now I am adding some new row to the Datagridview, when the grid is at page no 1 ,the row which i add inserted at right location but when i move to second page or third page of Datagridview and add a new row it insert at very top of the datagridview. I have done some code for inserting the row at right location and i am also attaching a image for better understanding my problem..
foreach (RowType Itemm in box9.SelectedItems)
{
FRReportRow newrow = new FRReportRow();
name = Itemm.TypeName;//box9.Text.ToString();
var ro = FixedSpecial.Where(x => x.TypeName == name).SingleOrDefault();
newrow.Item = name;
newrow.RowType = ro.IndexType;
if (newrow.RowType == 7)
PageBreaker = 1;
newrow.RowInfo = GetRowInfo(newrow.RowType);
if (newrow.RowInfo == string.Empty)
{
newrow.RowInfo = M3.FWL.UI.LayoutUc.EnumRowInfo.F.ToString();
}
ListRow.Add(newrow);
//To manage items added with page breaker
if (PageBreaker == 1 && newrow.RowType != 7)
AfterPageBreak.Add(newrow);
}
}
int prevpage;
List<FRReportRow> ListToBeAdded = new List<FRReportRow>();
if (IsValidationRequired)
ListToBeAdded = IsMultipleItemAlreadyExist(ListRow);
else
ListToBeAdded = ListRow;
if (ListToBeAdded.Count > 0)
{
groupBox1.Enabled = true;
var pagebreak = lstnewRow.Where(x => x.RowType == 7).ToList();
ListToBeAdded.ForEach(x => x.Pageno = Convert.ToInt32(nudpage.Value));
//Check Items after pagebreaker to change page no
if (AfterPageBreak.Count > 0)
{
foreach (FRReportRow item in ListToBeAdded)
{
int count = AfterPageBreak.Where(x => x == item).Count();
if (count > 0)
item.Pageno = item.Pageno + 1;
}
}
int rowNo = 0;
if (!PageBreakExist)
rowNo = gvlayoutload.SelectedRows[0].Index;//gvlayoutload.Rows.Count;
else
PageBreakExist = false;
int AfterPageRowNo = 0;
foreach (FRReportRow item in ListToBeAdded)
{
#region Determine the Rowno of the Item
int count = 0;
if (AfterPageBreak.Count > 0)
{
count = AfterPageBreak.Where(x => x == item).Count();
if (count > 0)
AfterPageRowNo = AfterPageRowNo + 1;
}
if (count > 0) //When item added after pagebreak in one go.
rowNo = AfterPageRowNo;
else
rowNo = rowNo + 1;
#endregion
item.RowNo = rowNo;
item.size = 8;
item.AlignText = 0;
item.AlignData = 2;
item.Indent = 0.1;
item.Loadas = 0;
item.fNegativeFormat = 0;
item.Format = 0;
// lstnewRow.Add(item);
mRowIndex = gvlayoutload.SelectedRows[0].Index;
lstnewRow.Add(item);
else if (mRowIndex >= 0 && mRowIndex < lstnewRow.Count) // other than first and last row
{
lstnewRow.Insert(mRowIndex + 1, item);
}
for (int i = 0; i < lstnewRow.Count; i++)
{
lstnewRow[i].RowNo = i + 1;
//lstnewRow[i].isUpdated = true;
}
}
if (AfterPageBreak.Count > 0)
{
pagebreak = lstnewRow.Where(x => x.RowType == 7).ToList();
PageBreaker = 0;
}
var newlst = lstnewRow.ToList();
this.fRReportRowBindingSource.DataSource = newlst;