tbf/ProductionTracing/ProductionTracingWnd.cs

644 lines
27 KiB
C#
Raw Permalink Normal View History

///
/// Copyright (c) 2016-2022 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Common;
using Common.Forms;
using SharedDatabase;
using SharedDatabase.Entities;
using NHibernate;
using NHibernate.Criterion;
using ProductionTracing.Resources;
using System.Globalization;
namespace ProductionTracing
{
public partial class ProductionTracingWnd : Form
{
const string OpenFileDlg_SaveFileDlg_Filter = "{0} (*.que)|*.que|{1} (*.*)|*.*";
ModelessForm modelessForm;
string[] args;
FiltersConfig filtersConfig; /// Serializable configuration of filters and displayed results
QueryResults currentQR;
GroupBox[] groupBoxes;
CheckBox[] checkBoxes;
ComboBox[] comboBoxes;
public ProductionTracingWnd(string[] args = null)
{
try
{
string culture = Program.LocalSettings.Language.Replace('_', '-');
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(culture);
}
catch (Exception)
{
MessageBox.Show("Selected language is not supported.\nUsing English.",
"Warning", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
System.Threading.Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo("en");
}
InitializeComponent();
/// enum Filter values 0 1 2 3 4 5 6 7 8
groupBoxes = new GroupBox[] { groupBox1, groupBox2, groupBox3, groupBox4, groupBox5, groupBox6, groupBox7, groupBox8, groupBox9 };
checkBoxes = new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6, checkBox7, checkBox8, checkBox9 };
comboBoxes = new ComboBox[] { comboBox1, comboBox2, null, comboBox4, comboBox5, comboBox6, comboBox7, comboBox8, comboBox9 };
LocalSettings.PrepareCombo(comboBox1, Program.LocalSettings.Combo1History);
LocalSettings.PrepareCombo(comboBox2, Program.LocalSettings.Combo2History);
LocalSettings.PrepareCombo(comboBox4, Program.LocalSettings.Combo4History);
LocalSettings.PrepareCombo(comboBox5, Program.LocalSettings.Combo5History);
LocalSettings.PrepareCombo(comboBox6, Program.LocalSettings.Combo6History);
LocalSettings.PrepareCombo(comboBox7, Program.LocalSettings.Combo7History);
LocalSettings.PrepareCombo(comboBox8, Program.LocalSettings.Combo8History);
LocalSettings.PrepareCombo(comboBox9, Program.LocalSettings.Combo9History);
for (int i = 0; i < Math.Min(groupBoxes.Length, checkBoxes.Length); i++)
{
ManageCheckGroupBox(checkBoxes[i],groupBoxes[i]);
}
this.args = args;
filtersConfig = new FiltersConfig();
}
private void ProductionTracingWnd_Load(object sender, EventArgs e)
{
LocalSettings ls = Program.LocalSettings;
Width = (ls.MainWndWidth > 0) ? ls.MainWndWidth : 1000;
Height = (ls.MainWndHeight > 0) ? ls.MainWndHeight : 750;
Left = (ls.MainWndLeft != 0) ? ls.MainWndLeft : 50;
Top = (ls.MainWndTop != 0) ? ls.MainWndTop : 50;
Localize();
if (args != null && args.Length == 1 && args[0].IndexOf(".que") == args[0].Length - 4)
LoadConfigFromFile(args[0]);
else if (!string.IsNullOrEmpty(Program.LocalSettings.LastConfigFileName))
LoadConfigFromFile(Program.LocalSettings.LastConfigFileName);
else
Text = string.Format("{0} ver.{1}", Strings.Production_Tracing, Program.Version);
}
/// <summary>
/// Localize strings
/// </summary>
void Localize()
{
filtersGroupBox.Text = Strings.Filters;
itemsGroupBox.Text = Strings.Items;
settingsBtn.Text = Strings.Settings;
loadConfigBtn.Text = Strings.Load_configuration;
saveConfigBtn.Text = Strings.Save_configuration;
executeQueryBtn.Text = Strings.Execute_query;
formatOfResultsBtn.Text = Strings.Format_of_results;
exportQueryResultsBtn.Text = Strings.Export_query_results;
printQueryResultsBtn.Text = Strings.Print_query_results;
statisticsBtn.Text = Strings.Statistics;
}
/// <summary>
/// Open 'Settings' dialog and update UI
/// </summary>
private void settingsBtn_Click(object sender, EventArgs e)
{
if (new Forms.SettingsDlg(Program.LocalSettings).ShowDialog() == DialogResult.OK)
{
/// TODO (connection string might have changed)
}
}
/// <summary>
/// Load configuration from a file
/// </summary>
private void loadConfigBtn_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = string.Format(OpenFileDlg_SaveFileDlg_Filter, Strings.Query_files, Strings.All_files);
if (dlg.ShowDialog() == DialogResult.OK)
{
LoadConfigFromFile(dlg.FileName);
}
}
/// <summary>
/// Load configuration from a file and apply it
/// </summary>
/// <param name="fileName">Configuration file name</param>
void LoadConfigFromFile(string fileName)
{
FiltersConfig localFiltersConfig = FiltersConfig.Load(fileName);
if (localFiltersConfig != null)
{
filtersConfig = localFiltersConfig;
/// TODO
}
Program.LocalSettings.LastConfigFileName = fileName;
Program.LocalSettings.Save();
Text = string.Format("{0} ver.{1} ({2})", Strings.Production_Tracing, Program.Version, Program.LocalSettings.LastConfigFileName);
}
private void saveConfigBtn_Click(object sender, EventArgs e)
{
/// Save the file
SaveFileDialog dlg = new SaveFileDialog();
if (!string.IsNullOrEmpty(Program.LocalSettings.LastConfigFileName))
{
dlg.FileName = Program.LocalSettings.LastConfigFileName;
}
dlg.Filter = string.Format(OpenFileDlg_SaveFileDlg_Filter, Strings.Query_files, Strings.All_files);
if (dlg.ShowDialog() == DialogResult.OK)
{
filtersConfig.Save(dlg.FileName);
Program.LocalSettings.LastConfigFileName = dlg.FileName;
Program.LocalSettings.Save();
Text = string.Format("{0} ver.{1} ({2})", Strings.Production_Tracing, Program.Version, Program.LocalSettings.LastConfigFileName);
}
}
void UpdateAndSaveHistory()
{
LocalSettings ls = Program.LocalSettings;
if (checkBox1.Checked) ls.UpdateHistory(comboBox1.Text, ref ls.Combo1History);
if (checkBox2.Checked) ls.UpdateHistory(comboBox2.Text, ref ls.Combo2History);
if (checkBox4.Checked) ls.UpdateHistory(comboBox4.Text, ref ls.Combo4History);
if (checkBox5.Checked) ls.UpdateHistory(comboBox5.Text, ref ls.Combo5History);
if (checkBox6.Checked) ls.UpdateHistory(comboBox6.Text, ref ls.Combo6History);
if (checkBox7.Checked) ls.UpdateHistory(comboBox7.Text, ref ls.Combo7History);
if (checkBox8.Checked) ls.UpdateHistory(comboBox8.Text, ref ls.Combo8History);
if (checkBox9.Checked) ls.UpdateHistory(comboBox9.Text, ref ls.Combo9History);
ls.Save();
}
private void executeQueryBtn_Click(object sender, EventArgs e)
{
UpdateAndSaveHistory();
modelessForm = new ModelessForm(Strings.searching);
Thread thread = new Thread(() => Application.Run(modelessForm));
thread.CurrentCulture = CultureInfo.CurrentCulture;
thread.CurrentUICulture = CultureInfo.CurrentUICulture;
thread.Start();
string currentConnStr = Program.LocalSettings.ConnectionString;
string[] elems = currentConnStr.Split(new char[] { '=', ';' });
string description = string.Format("{1}/{2}", tabControl.TabPages.Count + 1, (elems.Length > 1 ? elems[1] : "-"), (elems.Length > 3 ? elems[3] : "-"));
currentQR = new QueryResults(currentConnStr, description);
ISession session = null;
try
{
/// Load query result items
IList<ItemSpec> items = ItemSpec.FromStrArray(filtersConfig.ResultItems);
items.Insert(0, new ItemSpec(ItemSpecID.RefRecordId, Strings.RefRecordId, ItemCaps.RefRecord, (x, f, p, w) => ((int)x).ToString()));
/// New database session
using (session = TracingDB.CreateSession(currentConnStr))
{
currentQR.Results = DoOneQuery(session, items);
currentQR.ProjectedItems = items;
session.Close();
}
}
catch (Exception exc)
{
if (session != null && session.IsOpen) session.Close();
if (modelessForm != null) modelessForm.CloseForm();
MessageBox.Show(exc.Message,
Strings.Error,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return;
}
currentQR.EndTime = DateTime.Now;
TabPage newTabPage = CreateTabPage(currentQR);
tabControl.TabPages.Add(newTabPage);
tabControl.SelectTab(newTabPage);
if (modelessForm != null) modelessForm.CloseForm();
}
/// <summary>
/// Execute a chain of all filters once (without a loop)
/// </summary>
/// <param name="items">Result items</param>
IList<object[]> DoOneQuery(ISession session, IList<ItemSpec> items)
{
ReferenceRecord refRecord = null;
IQueryOver<ReferenceRecord, ReferenceRecord> query = session.QueryOver<ReferenceRecord>(() => refRecord);
int ix;
ix = (int)Idx.Code1; if (checkBoxes[ix].Checked) query = query.Where(x => x.Code1 == comboBoxes[ix].Text);
ix = (int)Idx.Code2; if (checkBoxes[ix].Checked) query = query.Where(x => x.Code2 == comboBoxes[ix].Text);
ix = (int)Idx.Code3; if (checkBoxes[ix].Checked) query = query.Where(x => x.Code3 == comboBoxes[ix].Text);
ix = (int)Idx.Code4; if (checkBoxes[ix].Checked) query = query.Where(x => x.Code4 == comboBoxes[ix].Text);
ix = (int)Idx.Order; if (checkBoxes[ix].Checked) query = query.Where(x => x.POName == comboBoxes[ix].Text);
ix = (int)Idx.Name1; if (checkBoxes[ix].Checked) query = query.Where(x => x.Name1 == comboBoxes[ix].Text);
ix = (int)Idx.Name2; if (checkBoxes[ix].Checked) query = query.Where(x => x.Name2 == comboBoxes[ix].Text);
ix = (int)Idx.Workflow; if (checkBoxes[ix].Checked) query = query.Where(x => x.Workflow == comboBoxes[ix].Text);
ix = (int)Idx.DateTime; if (checkBoxes[ix].Checked)
{
DateTime from;
DateTime to;
GetDateRange(Selection.Other, fromDateTimePicker.Value.Date,
toDateTimePicker.Value.Date.AddDays(1).AddTicks(-1), out from, out to);
query = query.WhereRestrictionOn(rr => rr.Timestamp).IsBetween(from).And(to);
}
Record record = null;
StepRecord stepRecord = null;
ProjectionList projections = ItemSpec.GetProjections(items, refRecord, stepRecord, record);
IList<object[]> result = query.Select(projections).List<object[]>();
return result;
}
/// <summary>
/// Create a new Tab page with and fill it with query results
/// </summary>
/// <param name="results">Query results</param>
/// <returns>A new tab page</returns>
TabPage CreateTabPage(QueryResults results)
{
///
/// Prepare a new list view control with query results
///
Common.Forms.ListViewEx listView = new Common.Forms.ListViewEx();
listView.Dock = System.Windows.Forms.DockStyle.Fill;
listView.FullRowSelect = true;
listView.GridLines = true;
listView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Clickable;
listView.Location = new System.Drawing.Point(3, 16);
listView.Name = results.Description;
listView.Size = new System.Drawing.Size(411, 144);
listView.TabIndex = 0;
listView.UseCompatibleStateImageBehavior = false;
listView.View = System.Windows.Forms.View.Details;
listView.DoubleClick += new System.EventHandler(listView_DoubleClick);
listView.ColumnClick += new ColumnClickEventHandler(listView_ColumnClick);
RedrawResults(results, listView);
///
/// Create a new tab page and add the just created list view control into it
///
TabPage newTabPage = new TabPage(string.Format("{0} ({1})", results.Description, results.Results.Count));
newTabPage.Controls.Add(listView);
newTabPage.Tag = results;
return newTabPage;
}
private void formatOfResultsBtn_Click(object sender, EventArgs e)
{
Forms.TracingConfigDlg dlg = new Forms.TracingConfigDlg();
dlg.Compound = false;
dlg.SelectedItems = ItemSpec.FromStrArray(filtersConfig.ResultItems);
dlg.AvailableItems = new List<ItemSpec>();
foreach (var v in ItemSpec.AllItems) dlg.AvailableItems.Add(v);
if (dlg.ShowDialog() == DialogResult.OK)
{
filtersConfig.ResultItems = ItemSpec.ToStrArray(dlg.SelectedItems);
}
}
/// <summary>
/// Displays obtained results as configured by result items in the ListView
/// </summary>
void RedrawResults(QueryResults results, ListView listView)
{
IList<ItemSpec> items = results.ProjectedItems;
listView.Clear();
if (results == null || results.Results == null || results.Results.Count == 0 || items == null || items.Count == 0) return;
try
{
if (items.Count >= 2)
{
/// 1st item (=item[0]) is ref. record ID and it is not displayed, it is copied to lvi.tag
for (int i = 1; i < items.Count; i++)
{
listView.Columns.Add(items[i].Caption, (filtersConfig.ResultsClmnCount > i) ? filtersConfig.ResultsClmnWidths[i] : 70);
}
foreach (var resItems in results.Results)
{
ListViewItem lvi = new ListViewItem(items[1].Print(resItems[1]));
for (int i = 2; i < items.Count; i++) lvi.SubItems.Add(items[i].Print(resItems[i]));
lvi.Tag = resItems[0];
listView.Items.Add(lvi);
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, Strings.Error_displaying_results, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void exportQueryResultsBtn_Click(object sender, EventArgs e)
{
if (currentQR == null || currentQR.Results == null || currentQR.Results.Count == 0
|| currentQR.ProjectedItems == null || currentQR.ProjectedItems.Count == 0)
{
return;
}
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
IList<ItemSpec> items = currentQR.ProjectedItems;
try
{
using (TextWriter writer = new StreamWriter(dlg.FileName, false, Encoding.UTF8))
{
for (int i = 1; i < items.Count; i++)
{
writer.Write(items[i].Caption);
if (i == items.Count - 1)
writer.WriteLine();
else
writer.Write(";");
}
foreach (var resItems in currentQR.Results)
{
for (int i = 1; i < items.Count; i++)
{
writer.Write(items[i].Export(resItems[i]));
if (i == items.Count - 1)
writer.WriteLine();
else
writer.Write(";");
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, Strings.Error_exporting_results, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
private void printQueryResultsBtn_Click(object sender, EventArgs e)
{
// if (referenceRecords == null || referenceRecords.Count == 0) return;
/// TODO: Reimplement
//foreach (var wm in referenceRecords)
//{
// new Results.Output.Printers.Munich.MunichPrintDocument("", wm, Config.Entities.PageOrientation.Portrait).Print();
//}
}
private void statisticsBtn_Click(object sender, EventArgs e)
{
if (currentQR == null || currentQR.Results == null || currentQR.Results.Count == 0
|| currentQR.ProjectedItems == null || currentQR.ProjectedItems.Count == 0)
{
MessageBox.Show("Žiadne výsledky vyhľadávania", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
///
/// Enter options
///
Forms.StatisticsOptionsDlg dlg = new Forms.StatisticsOptionsDlg(currentQR.ProjectedItems);
if (dlg.ShowDialog() != DialogResult.OK) return;
///
/// Calculate statistics
///
Forms.StatisticsDlg statisticsDlg = new Forms.StatisticsDlg(currentQR, dlg.TwoDim, dlg.RowItemIx, dlg.ColumnItemIx, dlg.FilterEnabled, dlg.FilteredItemIx, dlg.FilteredValue);
statisticsDlg.Show();
}
private void ProductionTracingWnd_FormClosing(object sender, FormClosingEventArgs e)
{
LocalSettings ls = Program.LocalSettings;
ls.MainWndMaximized = (WindowState == FormWindowState.Maximized);
if (WindowState == FormWindowState.Normal)
{
ls.MainWndLeft = Location.X;
ls.MainWndTop = Location.Y;
ls.MainWndWidth = Size.Width;
ls.MainWndHeight = Size.Height;
}
else
{
/// Maximized or minimized (when restarted, minimized window is restored as normal)
ls.MainWndLeft = RestoreBounds.Left;
ls.MainWndTop = RestoreBounds.Top;
ls.MainWndWidth = RestoreBounds.Width;
ls.MainWndHeight = RestoreBounds.Height;
}
ls.Save();
}
private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
{
currentQR = tabControl.SelectedTab.Tag as QueryResults;
}
private void listView_DoubleClick(object sender, EventArgs e)
{
ListView resultsListView = sender as ListView;
/// Double click works when just one item is selected
if (resultsListView != null && resultsListView.SelectedIndices.Count == 1)
{
int ix = resultsListView.SelectedIndices[0];
int refRecordID = (int)resultsListView.Items[ix].Tag;
if (refRecordID == 0) return;
using (ISession session = TracingDB.CreateSession(Program.LocalSettings.ConnectionString))
{
new Forms.MoreInfoDlg(refRecordID, session).ShowDialog();
session.Close();
}
}
}
private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
{
Common.Forms.ListViewEx listViewEx = sender as Common.Forms.ListViewEx;
if (listViewEx == null) return;
if (e.Column == listViewEx.SortColumn)
{
listViewEx.SortOrder = (listViewEx.SortOrder == MySortOrder.Ascending) ? MySortOrder.Descending : MySortOrder.Ascending;
}
else
{
/// Clicked on another column header => set sortOrder to SortOrder.Ascending
listViewEx.SortColumn = e.Column;
listViewEx.SortOrder = MySortOrder.Ascending;
}
listViewEx.ListViewItemSorter = new LviTextColumnComparer(listViewEx.SortColumn, listViewEx.SortOrder);
ListViewExtensions.SetSortIcon(listViewEx, listViewEx.SortColumn, listViewEx.SortOrder);
listViewEx.Sort();
}
void GetDateRange(Selection selection, DateTime uiFrom, DateTime uiTo, out DateTime from, out DateTime to)
{
DateTime now = DateTime.Now.Date;
if (selection == Selection.Today)
{
from = now.Date;
to = from.AddDays(1).AddTicks(-1);
}
else if (selection == Selection.Yesterday)
{
from = now.Date.AddDays(-1);
to = from.AddDays(1).AddTicks(-1);
}
else if (selection == Selection.ThisWeek)
{
from = now.Date.AddDays(-GetDayOfWeek0(now));
to = from.AddDays(7).AddTicks(-1);
}
else if (selection == Selection.LastWeek)
{
from = now.Date.AddDays(-GetDayOfWeek0(now) - 7);
to = from.AddDays(7).AddTicks(-1);
}
else if (selection == Selection.ThisMonth)
{
from = now.Date.AddDays(1 - now.Day);
to = now.Date.AddDays(1).AddTicks(-1);
}
else if (selection == Selection.LastMonth)
{
int daysLastMonth = (now.Month > 1) ? DateTime.DaysInMonth(now.Year, now.Month - 1)
: DateTime.DaysInMonth(now.Year - 1, 12);
from = now.Date.AddDays(1 - now.Day - daysLastMonth);
to = from.AddDays(daysLastMonth).AddTicks(-1);
}
else if (selection == Selection.ThisYear)
{
from = new DateTime(now.Year, 1, 1);
to = now.Date.AddDays(1).AddTicks(-1);
}
else if (selection == Selection.LastYear)
{
from = new DateTime(now.Year - 1, 1, 1);
to = new DateTime(now.Year, 1, 1).AddTicks(-1);
}
else /// Values for Selection.Other
{
from = uiFrom;
to = uiTo;
}
//int Offset = 0;
//from = from.AddHours(Offset);
//to = to.AddHours(Offset);
}
int GetDayOfWeek0(DateTime dateTime)
{
switch (dateTime.DayOfWeek)
{
default:
case DayOfWeek.Monday: return 0;
case DayOfWeek.Tuesday: return 1;
case DayOfWeek.Wednesday: return 2;
case DayOfWeek.Thursday: return 3;
case DayOfWeek.Friday: return 4;
case DayOfWeek.Saturday: return 5;
case DayOfWeek.Sunday: return 6;
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox1, groupBox1); }
private void checkBox2_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox2, groupBox2); }
private void checkBox3_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox3, groupBox3); }
private void checkBox4_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox4, groupBox4); }
private void checkBox5_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox5, groupBox5); }
private void checkBox6_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox6, groupBox6); }
private void checkBox7_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox7, groupBox7); }
private void checkBox8_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox8, groupBox8); }
private void checkBox9_CheckedChanged(object sender, EventArgs e) { ManageCheckGroupBox(checkBox9, groupBox9); }
private void ManageCheckGroupBox(CheckBox chk, GroupBox grp)
{
/// Make sure the CheckBox isn't in the GroupBox. This will only happen the first time.
if (chk.Parent == grp)
{
grp.Parent.Controls.Add(chk); /// Reparent the CheckBox so it's not in the GroupBox.
chk.Location = new Point(chk.Left + grp.Left, chk.Top + grp.Top); /// Adjust the CheckBox's location.
chk.BringToFront(); /// Move the CheckBox to the top of the stacking order.
}
/// Enable or disable the GroupBox.
grp.Enabled = chk.Checked;
}
}
enum Idx
{
Order, /// 0 = checkBox1, comboBox1
Workflow, /// 1 = checkBox2, comboBox2
DateTime, /// 2 = checkBox3
Code1, /// 3 = checkBox4, comboBox4
Code2, /// 4 = checkBox5, comboBox5
Code3, /// 5 = checkBox6, comboBox6
Code4, /// 6 = checkBox7, comboBox7
Name1, /// 7 = checkBox8, comboBox8
Name2, /// 8 = checkBox9, comboBox9
}
enum Selection
{
Today,
Yesterday,
ThisWeek,
LastWeek,
ThisMonth,
LastMonth,
ThisYear,
LastYear,
Other,
}
}