using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using System.Windows.Markup;
using AppRes = Eugen.ESystem.Windows.Forms.Properties.AppResources;
using System.Windows.Shapes;
namespace Eugen.ESystem.Windows.Forms
{
public partial class DuoMultiValueControl : UserControl
{
#region Version und Copyright
// Keys und Copyright
static string dllName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); //Den Programmnamen auslesen
static string dllVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
static object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
static string copyright = GenerateCopyright();
string icon = Application.StartupPath + "\\Info.bmp";
//Assembly Datum und Zeit
static DateTime value = AssemblyDateTime();
string date = value.ToShortDateString();
string time = value.ToLongTimeString();
private static DateTime AssemblyDateTime()
{
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
var buildDateTime = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * version.Build + TimeSpan.TicksPerSecond * 2 * version.Revision));
//Tage seit dem 1. Januar 2000 und Sekunden seit Mitternacht, (multiplizier mit 2 ergibt das Original)
return buildDateTime;
}
private static string CurrentYear()
{
DateTime dtn = DateTime.Now;
return dtn.Year.ToString();
}
private static string StartYear()
{
string startYear = "";
if (((AssemblyCopyrightAttribute)attributes[0]).Copyright.Contains("Copyright © "))
{
startYear = ((AssemblyCopyrightAttribute)attributes[0]).Copyright.Replace("Copyright © ", "");
while (startYear.StartsWith(" "))
{
startYear = startYear.Remove(0, 1);
}
startYear = startYear.Remove(startYear.IndexOf(" "));
return startYear;
}
else
{
DateTime dtn = DateTime.Now;
return dtn.Year.ToString();
}
}
private static string GenerateCopyright()
{
string startYear = StartYear();
string currentYear = CurrentYear();
if (startYear == currentYear)
{
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
else
{
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright.Replace(startYear, String.Concat(startYear, "-", currentYear));
}
}
#endregion
#region DLL-Info
///
/// Contains the name of the dll file.
///
public static string DllName { private set; get; }
///
/// Contains the version of the dll file.
///
public static string DllVersion { private set; get; }
///
/// Contains the copyright notice.
///
public static string Copyright { private set; get; }
///
/// Contains the name-, version- and copyright-information of the dll file.
///
public static string[] DllInfo { private set; get; }
private static void SetDllInfo()
{
//Name, Keys und Copyright setzen
DllName = dllName;
DllVersion = dllVersion;
Copyright = copyright;
}
#endregion
static DuoMultiValueControl()
{
SetDllInfo(); //Name, Keys und Copyright der DLL setzen
}
///
/// Creates a control with which the values in an XML file can be edited
///
public DuoMultiValueControl()
{
InitializeComponent();
InitialDirectory = @"C:\";
Topic = "Topic";
StandardValue = 0;
}
#region Public values
///
/// The password used for encryption. An empty value disables the Encrypt values switch
///
public string Password
{
get { return password; }
set
{
password = value;
checkBoxEncryptValues.Enabled = !String.IsNullOrEmpty(Password);
}
}
///
/// Defines or read the initial directory
///
public string InitialDirectory { set; get; }
///
/// XML file name. Must be specified mandatory
///
public string XMLfileName { set; get; }
///
/// XML group 1 file name. Must be specified mandatory and defines the XML file in which the groups are stored
///
public string XMLgroup1FileName { set; get; }
///
/// XML group 2 file name. Must be specified mandatory and defines the XML file in which the groups are stored
///
public string XMLgroup2FileName { set; get; }
///
/// Adjusts the labeling of the values control. An empty value forces the default labeling
///
public string ValueControlName
{
get { return groupBoxValueControl.Text; }
set
{
groupBoxValueControl.Text = value;
groupBoxValueControl.Refresh();
}
}
///
/// Defines the Topic. An empty value forces the default labeling
///
public string Topic { set; get; }
///
/// Adjusts the labeling of the group 1 designation. An empty value forces the default labeling
///
public string GroupName1
{
get { return labelGroup1.Text; }
set { labelGroup1.Text = value; }
}
///
/// Adjusts the labeling of the group 2 designation. An empty value forces the default labeling
///
public string GroupName2
{
get { return labelGroup2.Text; }
set { labelGroup2.Text = value; }
}
///
/// Changes the name of the group 1 attribute used in the XML file, which is displayed and must be included in groups. Required for the Load function
///
public string Group1 { set; get; }
///
/// Changes the name of the group 2 attribute used in the XML file, which is displayed and must be included in groups. Required for the Load function
///
public string Group2 { set; get; }
///
/// List of group 1 attribute names. Required for the Load function
///
public string[] Groups1 { set; get; }
///
/// List of group 2 attribute names. Required for the Load function
///
public string[] Groups2 { set; get; }
///
/// Adjusts the name of the key attribute used in the XML file. Required by the Load function
///
public string Key { set; get; }
///
/// Adjusts the labeling of the table header designation for the key. An empty value forces the default labeling
///
public string TableKeyName
{
get { return dataGridViewValues.Columns[0].HeaderText; }
set { dataGridViewValues.Columns[0].HeaderText = value; }
}
///
/// Adjusts the labeling of the table header designation for the value. An empty value forces the default labeling
///
public string TableValueName
{
get { return dataGridViewValues.Columns[1].HeaderText; }
set { dataGridViewValues.Columns[1].HeaderText = value; }
}
///
/// Adjusts the labeling of the encrypt value checkBox. An empty value forces the default labeling
///
public string CheckBoxEncryptValueText
{
get { return checkBoxEncryptValues.Text; }
set
{
checkBoxEncryptValues.Text = value;
checkBoxEncryptValues.Enabled = !String.IsNullOrEmpty(Password);
}
}
///
/// Controls whether values are always encrypted. An empty value forces the default value (false)
///
public bool AlwaysEncrypted
{
get { return alwaysEncrypted; }
set
{
alwaysEncrypted = value;
}
}
///
/// Controls whether values are never encrypted. An empty value forces the default value (false). True always dectivates 'AlwaysEncrypted'
///
public bool NeverEncrypted
{
get { return neverEncrypted; }
set
{
neverEncrypted = value;
}
}
#endregion
#region Private values
private string password;
private bool alwaysEncrypted = false;
private bool neverEncrypted = false;
private bool standardValueSet = false;
private int selectedRow = 0;
private int rowIndexColored = 0;
private int StandardValue { get; set; }
private string XmlFileName { get; set; }
private string OldXMLfileName { get; set; }
private List OldNameData { get; set; }
private List OldValueData { get; set; }
private List NewNameData { get; set; }
private List NewValueData { get; set; }
private bool OldEcryptStatus { get; set; }
private bool NewEcryptStatus { get; set; }
#endregion
private void comboBoxGroup1_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedIndexChanged();
}
private void comboBoxGroup2_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedIndexChanged();
}
private void SelectedIndexChanged()
{
if (comboBoxGroup1.Items.Count != 0)
{
Group1 = comboBoxGroup1.SelectedItem.ToString();
}
if (comboBoxGroup2.Items.Count != 0)
{
Group2 = comboBoxGroup2.SelectedItem.ToString();
}
if (!String.IsNullOrEmpty(Group1) & !String.IsNullOrEmpty(Group2))
{
XmlFileName = String.Concat(XMLfileName.Replace(".xml", ""), "_", Group1, "_", Group2, ".xml");
OldXMLfileName = XmlFileName;
//XMLfileName = String.Concat(InitialDirectory, "\\", Group1, ".xml");
buttonSave.Enabled = (!String.IsNullOrEmpty(comboBoxGroup1.Text)) & (!String.IsNullOrEmpty(comboBoxGroup2.Text));
//OldNameData und OldValueDate schreiben
SetData("new");
if (File.Exists(XmlFileName))
{
if (dataGridViewValues.Rows.Count > 1)
{
//Wurden in der Datagridview Werte geändert, dann speichern
if (HasAnyDataChanged())
{
DialogResult result = MessageBox.Show(AppRes.msgBoxTxt003, AppRes.msgBoxCapt003, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
//Datagridview speichern
SaveXML(OldXMLfileName);
}
}
}
//Datagridview leeren und XML Laden
dataGridViewValues.Rows.Clear();
LoadXML();
}
else
{
if (dataGridViewValues.Rows.Count > 1)
{
//Wurden in der Datagridview Werte geändert, dann speichern
if (HasAnyDataChanged())
{
DialogResult result = MessageBox.Show(AppRes.msgBoxTxt003, AppRes.msgBoxCapt003, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
//Datagridview speichern
SaveXML(OldXMLfileName);
}
}
}
dataGridViewValues.Rows.Clear();
MessageBox.Show(AppRes.msgBoxTxt002, AppRes.msgBoxCapt002, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
//OldNameData und OldValueDate schreiben
SetData("old");
}
}
private void comboBoxGroup1_TextChanged(object sender, EventArgs e)
{
buttonSave.Enabled = (!String.IsNullOrEmpty(comboBoxGroup1.Text));
}
private void comboBoxGroup2_TextChanged(object sender, EventArgs e)
{
buttonSave.Enabled = (!String.IsNullOrEmpty(comboBoxGroup2.Text));
}
private void buttonUp_Click(object sender, EventArgs e)
{
if (dataGridViewValues.SelectedCells.Count > 0)
{
int index = dataGridViewValues.SelectedCells[0].OwningRow.Index;
if (index > 0)
{
int col = dataGridViewValues.SelectedCells[0].OwningColumn.Index;
DataGridViewRowCollection rows = dataGridViewValues.Rows;
DataGridViewRow row = rows[index];
rows.Remove(row);
rows.Insert(index - 1, row);
dataGridViewValues.ClearSelection();
dataGridViewValues.Rows[index - 1].Cells[col].Selected = true;
}
}
}
private void buttonDown_Click(object sender, EventArgs e)
{
if (dataGridViewValues.SelectedCells.Count > 0)
{
int index = dataGridViewValues.SelectedCells[0].OwningRow.Index;
if (index < dataGridViewValues.Rows.Count - 2)
{
int col = dataGridViewValues.SelectedCells[0].OwningColumn.Index;
DataGridViewRowCollection rows = dataGridViewValues.Rows;
DataGridViewRow row = rows[index];
rows.Remove(row);
rows.Insert(index + 1, row);
dataGridViewValues.ClearSelection();
dataGridViewValues.Rows[index + 1].Cells[col].Selected = true;
}
}
}
private void buttonLoad_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(XmlFileName))
{
openFileDialog.Title = AppRes.dlgOpenTitle;
openFileDialog.InitialDirectory = InitialDirectory;
openFileDialog.FileName = "";
openFileDialog.Filter = AppRes.dlgFilter; //"xml files (*.xml)|*.xml|All files (*.*)|*.*"
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
XmlFileName = openFileDialog.FileName;
LoadXML();
}
}
else
{
if (File.Exists(XmlFileName))
{
LoadXML();
}
else
{
MessageBox.Show(AppRes.msgBoxTxt001, AppRes.msgBoxCapt001, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(XmlFileName))
{
saveFileDialog.Title = AppRes.dlgSaveTitle;
saveFileDialog.InitialDirectory = InitialDirectory;
saveFileDialog.Filter = AppRes.dlgFilter; //"xml files (*.xml)|*.xml|All files (*.*)|*.*"
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
SaveXML(XmlFileName);
}
}
else
{
SaveXML(XmlFileName);
}
}
private void buttonCleanup_Click(object sender, EventArgs e)
{
//Alle XML-Dateien auslesen die mit 'XmlFileName' beginnen
List collectedXmlFiles = new List();
collectedXmlFiles.AddRange(CollectAllFiles());
//Alle XML-Dateien aus der Liste auslesen die in 'Groups1' und 'Groups2' vorkommen
List collectedPatternFiles = new List();
collectedPatternFiles.AddRange(CollectPatternFiles(collectedXmlFiles));
//Alle XML-Dateien aus der Liste löschen, die in 'Groups1' und 'Groups2' nicht vorkommen
List filesToDelete= new List();
filesToDelete.AddRange(FilesToDelete(collectedXmlFiles, collectedPatternFiles));
if (filesToDelete.Count != 0)
{
try
{
foreach (string file in filesToDelete)
{
File.Delete(file);
}
MessageBox.Show(AppRes.msgBoxTxt005, AppRes.msgBoxCapt004, MessageBoxButtons.OK);
}
catch (Exception)
{
MessageBox.Show(AppRes.msgBoxTxt004, AppRes.msgBoxCapt002, MessageBoxButtons.OK);
}
}
}
private List CollectAllFiles()
{
//Alle XML-Dateien auslesen die mit 'NXenvironment' beginnen
string path = System.IO.Path.GetDirectoryName(XMLfileName);
string[] origXmlFiles = Directory.GetFiles(path);
List collectedXmlFiles = new List();
for (int i = 0; i < origXmlFiles.Length; i++)
{
//origXmlFiles[i] = Path.GetFileName(origXmlFiles[i]);
if (System.IO.Path.GetFileName(origXmlFiles[i]).StartsWith(System.IO.Path.GetFileNameWithoutExtension(XMLfileName)))
{
collectedXmlFiles.Add(origXmlFiles[i]);
}
}
return collectedXmlFiles;
}
private List CollectPatternFiles(List collectedXmlFiles)
{
//Alle XML-Dateien aus der Liste auslesen die in 'Groups1' und 'Groups2' vorkommen
string tempFile = "";
List tempFoundedFiles = new List();
List foundedFiles = new List();
foreach (string file in collectedXmlFiles)
{
tempFile = (System.IO.Path.GetFileNameWithoutExtension(file)).Replace(System.IO.Path.GetFileNameWithoutExtension(XMLfileName) + "_", "");
foreach (var pattern1 in Groups1)
{
if (tempFile.StartsWith(pattern1))
{
tempFoundedFiles.Add(file); //Wenn der Anfang übereinstimmt, dann die Datei zur Liste hinzufügen
}
}
}
foreach (string file in tempFoundedFiles)
{
foreach (var pattern2 in Groups2)
{
if (System.IO.Path.GetFileNameWithoutExtension(file).EndsWith(pattern2))
{
foundedFiles.Add(file); //Wenn der Anfang übereinstimmt, dann die Datei zur Liste hinzufügen
}
}
}
return foundedFiles;
}
private List FilesToDelete(List collectedXmlFiles, List collectedPatternFiles)
{
List filesToDelete= new List();
filesToDelete.AddRange(collectedXmlFiles);
if (collectedPatternFiles.Count == 0)
{
return collectedXmlFiles;
}
foreach (string pattern in collectedPatternFiles)
{
foreach (string file in collectedXmlFiles)
{
if (file == pattern)
{
filesToDelete.Remove(pattern);
}
}
}
return filesToDelete;
}
private void dataGridViewValues_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
selectedRow = dataGridViewValues.SelectedCells[0].RowIndex + 1; //Wenn die Zeile gelöscht wird, dann die Zeilennummer merken
}
}
private void dataGridViewValues_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
//Wenn die gelöschte Zeile den Standardwert enthielt, dann die WErte zurücksetzten, weil es keinen Standardwert mehr gibt
if (selectedRow == rowIndexColored)
{
StandardValue = 0; //Es gibt keine ausgewählte Standardzeile
standardValueSet = false; //es gibt keinen Standardwert
rowIndexColored = 0; //Es gibt keine umgefärbte Zeile
}
}
public void SetBasicValues()
{
//'Groups1' mit Werten befüllen
Groups1 = ReadGroups(XMLgroup1FileName);
if (Groups1 != null)
{
comboBoxGroup1.Items.Clear();
for (int i = 0; i < Groups1.Length; i++)
{
comboBoxGroup1.Items.Add(Groups1[i]);
}
comboBoxGroup1.SelectedIndex = 0;
}
//'Groups2' mit Werten befüllen
Groups2 = ReadGroups(XMLgroup2FileName);
if (Groups2 != null)
{
comboBoxGroup2.Items.Clear();
for (int i = 0; i < Groups2.Length; i++)
{
comboBoxGroup2.Items.Add(Groups2[i]);
}
comboBoxGroup2.SelectedIndex = 0;
}
// 'checkBoxEncryptValues' entsprechend der übergebenen Parameter setzen
if (neverEncrypted)
{
checkBoxEncryptValues.Visible = !neverEncrypted;
}
else
{
checkBoxEncryptValues.Checked = alwaysEncrypted;
checkBoxEncryptValues.Enabled = !alwaysEncrypted;
}
}
private void LoadXML()
{
checkBoxEncryptValues.Checked = false;
var loadXML = new LoadXML();
loadXML.FileName = String.Concat(XMLfileName.Replace(".xml", ""), "_", Group1, "_", Group2, ".xml");
loadXML.Load();
string[] values = new string[loadXML.Values.Length];
values = loadXML.Values;
if (!String.IsNullOrEmpty(Group1) & !String.IsNullOrEmpty(Group2))
{
loadXML.Group = Group1 + "_" + Group2;
}
for (int i = 0; i < values.Length; i++)
{
if (values[i].StartsWith("$$$$"))
{
values[i] = Decrypt(values[i], Password);
checkBoxEncryptValues.Checked = true; //Wenn ein verschlüsseltes Element gefunden wurde, dann setzen
}
dataGridViewValues.Rows.Add(loadXML.Keys[i], values[i]);
}
dataGridViewValues.Refresh();
comboBoxGroup1.Text = loadXML.Group.Remove(loadXML.Group.LastIndexOf("_")); //Gruppe setzen
comboBoxGroup2.Text = loadXML.Group.Remove(0, loadXML.Group.LastIndexOf("_")); //Gruppe setzen
SetData("old"); //Die geladenen Daten setzten
}
private string[] LoadGroup()
{
string[] values = new string[comboBoxGroup1.Items.Count];
for (int i = 0; i < comboBoxGroup1.Items.Count; i++)
{
values[i] = comboBoxGroup1.Items[i].ToString();
}
for (int i = 0; i < values.Length; i++)
{
if (values[i].StartsWith("$$$$"))
{
values[i] = Decrypt(values[i], Password);
}
}
return values;
}
private void SaveXML(string xmlFileName)
{
if (!Directory.Exists(System.IO.Path.GetDirectoryName(xmlFileName)))
{
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(xmlFileName)); //Wenn das Verzeichnis nicht existiert, dann erzeugen
}
int dgvLength = dataGridViewValues.RowCount - 1;
string[] keys = new string[dgvLength];
string value = "";
string[] values = new string[dgvLength];
for (int i = 0; i < dgvLength; i++)
{
if (checkBoxEncryptValues.Checked)
{
value = Encrypt(dataGridViewValues[1, i].Value.ToString(), Password); //Verschlüsselt
}
else
{
value = dataGridViewValues[1, i].Value.ToString(); //Unverschlüsselt
}
keys[i] = dataGridViewValues[0, i].Value.ToString(); ;
values[i] = value;
}
//Speichern
var saveXML = new SaveXML();
saveXML.FileName = xmlFileName;
saveXML.Topic = Topic; //z.B. "NX-Portal"
saveXML.Group = comboBoxGroup1.Text; //z.B. "NX 1953"
saveXML.Keys = keys; //z.B. "UGII_ENV"
saveXML.Values = values; //z.B. "M:\ug\NX1953_NXTC\global\00_DEFAULTS\UGII\ugii_env.dat"
saveXML.Save();
//OldNameData und OldValueDate schreiben
SetData("old");
}
private string Encrypt(string clearText, string password)
{
var crypt = new Cryption();
return String.Concat("$$$$", crypt.EncryptString(clearText, password));
}
private string Decrypt(string encryptedText, string password)
{
var crypt = new Cryption();
return crypt.DecryptString(encryptedText.Replace("$$$$", ""), password);
}
private void SetData(string stage)
{
int dgvLength = dataGridViewValues.RowCount - 1;
if (stage == "old")
{
//Old Data
List oldNameData = new List();
List oldValueData = new List();
for (int i = 0; i < dgvLength; i++)
{
oldNameData.Add(dataGridViewValues[0, i].Value.ToString());
oldValueData.Add(dataGridViewValues[1, i].Value.ToString());
}
OldNameData = oldNameData;
OldValueData = oldValueData;
OldEcryptStatus = checkBoxEncryptValues.Checked;
}
else
{
//New Data
List newNameData = new List();
List newValueData = new List();
for (int i = 0; i < dgvLength; i++)
{
newNameData.Add(dataGridViewValues[0, i].Value.ToString());
newValueData.Add(dataGridViewValues[1, i].Value.ToString());
}
NewNameData = newNameData;
NewValueData = newValueData;
NewEcryptStatus = checkBoxEncryptValues.Checked;
}
}
private bool HasAnyDataChanged()
{
int dgvLength = dataGridViewValues.RowCount - 1;
bool hasChanged = false;
if (OldNameData.Count != NewNameData.Count)
{
hasChanged = true;
}
else
{
for (int i = 0; i < dgvLength; i++)
{
if (OldNameData[i] != NewNameData[i])
{
hasChanged = true;
}
if (OldValueData[i] != NewValueData[i])
{
hasChanged = true;
}
if (OldEcryptStatus != NewEcryptStatus)
{
hasChanged = true;
}
}
}
return hasChanged;
}
///
/// Reads the groups from a XML file
///
private string[] ReadGroups(string xmlFileName)
{
if (File.Exists(xmlFileName))
{
var sivco = new SingleValueControl();
sivco.XMLfileName = xmlFileName;
sivco.Password = Password;
return sivco.GetValues();
}
else
{
return null;
}
}
///
/// Sets a customer width of the user control
///
/// The width. Min=316, Max=800
public void SetDialogWidth(int width)
{
if (width >= this.MinimumSize.Width && width <= this.MaximumSize.Width)
{
this.Width = width;
int dif = width - 316;
if (dif > 0)
{
dataGridViewValues.Columns[0].Width += dif / 2;
}
}
}
///
/// Sets a customer height of the user control
///
/// The width. Min=227, Max=460
public void SetDialogHeight(int height)
{
if (height >= this.MinimumSize.Height && height <= this.MaximumSize.Height)
{
this.Height = height;
}
}
}
}