/// /// Copyright (c) 2019 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Windows.Forms; using NHibernate; using log4net; using Config.Entities; using Common.Forms; using TBF.Rig; using TBF.Rig.GenericDevices; using TBF.Resources; using TBF.UI.Shared; namespace TBF.UI.Bench.TestProfiles { public class TestProfilesCtrl : BaseWithListViewEx, ITabWithListViewEx { static readonly ILog log = LogManager.GetLogger(typeof(TestProfilesCtrl)); /// /// ListViewEx columns /// enum Column { ItemNr, Name, Description, More, ColumnsCount, } readonly int columnsCount = (int)Column.ColumnsCount; TestProfilesDlg parent; Control parentControl; Control[] editors; ISession session; public TestProfilesCtrl() : base() { session = null; } public void Initialize(TestProfilesDlg parent, Control parentControl) { if (Parent == null) return; session = TBF.DB.CreateSession(Common.DBKind.Config); this.parent = parent; this.parentControl = parentControl; SubItemClicked += new SubItemEventHandler(listViewEx_SubItemClicked); SubItemEndEditing += new SubItemEndEditingEventHandler(listViewEx_SubItemEndEditing); /// ListViewEx columns TBF.LocalSettings ls = Program.LocalSettings; Columns.Add(Strings.Nr, (ls.ProfilesColumnCount > 0) ? ls.ProfilesColumnWidths[0] : ( 30 * parent.Dpi / Constants.Dpi100pct)); Columns.Add(Strings.Name, (ls.ProfilesColumnCount > 1) ? ls.ProfilesColumnWidths[1] : (100 * parent.Dpi / Constants.Dpi100pct)); Columns.Add(Strings.DescriptionColHdr, (ls.ProfilesColumnCount > 2) ? ls.ProfilesColumnWidths[2] : (300 * parent.Dpi / Constants.Dpi100pct)); Columns.Add(Strings.More, (ls.ProfilesColumnCount > 3) ? ls.ProfilesColumnWidths[3] : (300 * parent.Dpi / Constants.Dpi100pct)); editors = new Control[columnsCount]; /// editors[(int)Column.ItemNr] = new TextBox(); /// ItemNr editors[(int)Column.Name] = new TextBox(); /// Name editors[(int)Column.Description] = new TextBox(); /// Description editors[(int)Column.More] = null; /// for (int i = 0; i < editors.Length; i++) { if (editors[i] != null) { editors[i].Visible = false; parent.Controls.Add(editors[i]); } } ReloadAndRedrawAll(); } void ReloadAndRedrawAll() { if (session == null) return; try { MyItems = session.QueryOver() .OrderBy(x => x.ItemNr).Asc .List(); } catch (Exception exc) { log.ErrorFormat("Loading Profiles from DB failed: {0}", exc.Message); MyItems = new List(); return; } base.RedrawAll(); } void listViewEx_SubItemClicked(object sender, SubItemEventArgs e) { } void listViewEx_SubItemEndEditing(object sender, SubItemEndEditingEventArgs e) { } public override void DrawOne(object myItem) { Profile entity = (Profile)myItem; StringBuilder tests = new StringBuilder(); foreach (var test in entity.Tests) { tests.Append(test.Name); tests.Append(", "); } ListViewItem lvi = new ListViewItem((entity.ItemNr + 1).ToString()); lvi.SubItems.Add(entity.Name); lvi.SubItems.Add(entity.Description); lvi.SubItems.Add(tests.ToString()); lvi.Tag = entity; Items.Add(lvi); } /// /// Update the entities and save them to the database /// public new void OkBtnClicked() { base.OkBtnClicked(); using (ITransaction transaction = session.BeginTransaction()) { try { foreach (var entity in ToBeRemovedItems) session.Delete(entity); ToBeRemovedItems.Clear(); int itemNr = 0; foreach (var entity in MyItems) { (entity as Profile).ItemNr = itemNr++; session.SaveOrUpdate(entity); } transaction.Commit(); session.Flush(); } catch (Exception exc) { transaction.Rollback(); log.ErrorFormat("Cannot save changes to DB: {0}", exc.Message); MessageBox.Show(Strings.Cannot_save_changes, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } SaveUISettings(); Program.MainWnd.ReloadProcedureComboBoxItems(); } void SaveUISettings() { LocalSettings ls = Program.LocalSettings; /// Compare list view column widths with the saved ones bool anyColumnDiffers = false; if (Columns.Count != ls.ProfilesColumnCount) { anyColumnDiffers = true; } else { for (int i = 0; i < Columns.Count; i++) { if (Columns[i].Width != ls.ProfilesColumnWidths[i]) { anyColumnDiffers = true; break; } } } if (anyColumnDiffers) { /// Update column widths ls.ProfilesColumnWidths = new int[Columns.Count]; for (int i = 0; i < Columns.Count; i++) { ls.ProfilesColumnWidths[i] = Columns[i].Width; } ls.Save(); } } public void AddOne() { /// Find an unused procedure name string newName; for (int nameId = 1; true; nameId++) { newName = Strings.New_profile_name + nameId.ToString(); bool notUsed = true; foreach (var t in MyItems) if (t.Name.ToLower().Equals(newName.ToLower())) notUsed = false; if (notUsed) break; } Profile newProfile = new Profile(newName, MyItems.Count); newProfile.CreationUser = Users.GlobalData.CurrentUser.UserName; newProfile.CreationTime = DateTime.Now; if (new TestProfileDlg(newProfile, GetUsedNames(false), true).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); using(var transaction = session.BeginTransaction()) { try { newProfile.LastChgUser = Users.GlobalData.CurrentUser.UserName; newProfile.LastChgTime = DateTime.Now; base.AddOne(newProfile); session.SaveOrUpdate(newProfile); transaction.Commit(); MessageBox.Show(string.Format(Strings.Profile_0_added, newProfile.Name), Strings.Confirmation, MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exc) { transaction.Rollback(); log.ErrorFormat("Exception when saving Profile '{0}' : {1}", newProfile.Name, exc.Message); } } } } public new void RemoveSelected() { if (MessageBox.Show(Strings.Do_you_want_to_delete_the_procedure, Strings.Question, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { bool lastOneRemoved = base.RemoveSelected(); if (lastOneRemoved && parent != null) { parent.UpdateButtonStates(SharedButtons.SelectedItemPos.None); } /// Update the database using (ITransaction transaction = session.BeginTransaction()) { try { foreach (var entity in ToBeRemovedItems) session.Delete(entity); ToBeRemovedItems.Clear(); int itemNr = 0; foreach (var entity in MyItems) { (entity as Profile).ItemNr = itemNr++; session.SaveOrUpdate(entity); } transaction.Commit(); session.Flush(); } catch (Exception exc) { transaction.Rollback(); log.ErrorFormat("Cannot save changes to DB: {0}", exc.Message); MessageBox.Show(Strings.Cannot_save_changes, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } public void editButton_Click(object sender, EventArgs e) { if (SelectedItems.Count != 1) return; Profile editedProfile = SelectedItems[0].Tag as Profile; IList usedNames = GetUsedNames(false); usedNames.Remove(editedProfile.Name.ToLower()); /// Allow original procedure name /// if (new TestProfileDlg(editedProfile, usedNames).ShowDialog() == DialogResult.OK) { parent.Unlock(); using (var transaction = session.BeginTransaction()) { try { editedProfile.LastChgUser = Users.GlobalData.CurrentUser.UserName; editedProfile.LastChgTime = DateTime.Now; session.SaveOrUpdate(editedProfile); transaction.Commit(); MessageBox.Show(string.Format(Strings.Profile_0_modified, string.Format(" {0} '{1}' ", editedProfile.ItemNr + 1, editedProfile.Name)), Strings.Confirmation, MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exc) { log.ErrorFormat("Exception when saving Profile '{0}' : {1}", editedProfile.Name, exc.Message); transaction.Rollback(); } } session.Flush(); } ReloadAndRedrawAll(); } public void copyButton_Click(object sender, EventArgs e) { if (SelectedItems.Count != 1) return; Profile selectedProfile = (Profile)SelectedItems[0].Tag; /// Make a copy of the selected procedure Profile newProfile = selectedProfile.Clone(); newProfile.Name = selectedProfile.Name + Strings.New_name_copy; newProfile.ItemNr = MyItems.Count; newProfile.CreationUser = Users.GlobalData.CurrentUser.UserName; newProfile.CreationTime = DateTime.Now; if ((new TestProfileDlg(newProfile, GetUsedNames(false), true)).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); using (var transaction = session.BeginTransaction()) { newProfile.LastChgUser = Users.GlobalData.CurrentUser.UserName; newProfile.LastChgTime = DateTime.Now; base.AddOne(newProfile); session.SaveOrUpdate(newProfile); transaction.Commit(); MessageBox.Show(string.Format(Strings.Procedure_0_added, newProfile.Name), Strings.Confirmation, MessageBoxButtons.OK, MessageBoxIcon.Information); } } } public void exportButton_Click(object sender, EventArgs e) { if (SelectedItems.Count != 1) return; Profile selectedProfile = (Profile)SelectedItems[0].Tag; SaveFileDialog dlg = new SaveFileDialog(); if (dlg.ShowDialog() == DialogResult.OK) { selectedProfile.Export(new StreamWriter(dlg.FileName, false, System.Text.Encoding.UTF8)); } } public void importButton_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); if (dlg.ShowDialog() != DialogResult.OK) return; /// Import a procedure from a file Profile newProfile = Profile.Import(new StreamReader(dlg.FileName, System.Text.Encoding.UTF8)); newProfile.Name = newProfile.Name + " imported"; newProfile.ItemNr = MyItems.Count; newProfile.CreationUser = Users.GlobalData.CurrentUser.UserName; newProfile.CreationTime = DateTime.Now; if ((new TestProfileDlg(newProfile, GetUsedNames(false), true)).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); using (var transaction = session.BeginTransaction()) { newProfile.LastChgUser = Users.GlobalData.CurrentUser.UserName; newProfile.LastChgTime = DateTime.Now; base.AddOne(newProfile); session.SaveOrUpdate(newProfile); transaction.Commit(); MessageBox.Show(string.Format(Strings.Procedure_0_added, newProfile.Name), Strings.Confirmation, MessageBoxButtons.OK, MessageBoxIcon.Information); } } } public void compareButton_Click(object sender, EventArgs e) { if (SelectedItems.Count != 1) return; Profile selectedProfile = (Profile)SelectedItems[0].Tag; OpenFileDialog dlg = new OpenFileDialog(); if (dlg.ShowDialog() == DialogResult.OK) { string diff = selectedProfile.Compare(new StreamReader(dlg.FileName, System.Text.Encoding.UTF8)); if (!string.IsNullOrEmpty(diff)) { MessageBox.Show(diff, "Differences", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { MessageBox.Show("No differences found", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } public string GetWarningsBeforeSaving(ref Dictionary renmInfo) { return string.Empty; } public void UpdateRelatedItems(Dictionary renameInfo) { } } }