singlevaluecontrol_user_con.../SingleValueControl/SingleValueControl.cs
2024-10-09 13:53:22 +02:00

646 lines
22 KiB
C#

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 AppRes = Eugen.ESystem.Windows.Forms.Properties.AppResources;
using System.Xml.Linq;
namespace Eugen.ESystem.Windows.Forms
{
public partial class SingleValueControl : UserControl
{
#region Version und Copyright
// Key und Copyright
static string dllName = 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
/// <summary>
/// Contains the name of the dll file.
/// </summary>
public static string DllName { private set; get; }
/// <summary>
/// Contains the version of the dll file.
/// </summary>
public static string DllVersion { private set; get; }
/// <summary>
/// Contains the copyright notice.
/// </summary>
public static string Copyright { private set; get; }
/// <summary>
/// Contains the name-, version- and copyright-information of the dll file.
/// </summary>
public static string[] DllInfo { private set; get; }
private static void SetDllInfo()
{
//Name, Key und Copyright setzen
DllName = dllName;
DllVersion = dllVersion;
Copyright = copyright;
}
#endregion
static SingleValueControl()
{
SetDllInfo(); //Name, Key und Copyright der DLL setzen
}
/// <summary>
/// Creates a control with which the values in an XML file can be edited
/// </summary>
public SingleValueControl()
{
InitializeComponent();
InitialDirectory = @"C:\";
Topic = "Topic";
StandardValue = 0;
}
#region Public values
/// <summary>
/// The password used for encryption. An empty value disables the Encrypt values switch
/// </summary>
public string Password
{
get { return password; }
set
{
password = value;
checkBoxEncryptValues.Enabled = !String.IsNullOrEmpty(Password);
}
}
/// <summary>
/// Defines or read the initial directory
/// </summary>
public string InitialDirectory { set; get; }
/// <summary>
/// XML file name. Must be specified mandatory
/// </summary>
public string XMLfileName { set; get; }
/// <summary>
/// Adjusts the labeling of the values control. An empty value forces the default labeling
/// </summary>
public string ValueControlName
{
get { return groupBoxValueControl.Text; }
set
{
groupBoxValueControl.Text = value;
groupBoxValueControl.Refresh();
}
}
/// <summary>
/// Defines the Topic. An empty value forces the default labeling
/// </summary>
public string Topic { set; get; }
/// <summary>
/// Adjusts the labeling of the group designation. An empty value forces the default labeling
/// </summary>
public string GroupName
{
get { return labelGroup.Text; }
set { labelGroup.Text = value; }
}
/// <summary>
/// Adjusts the name of the group attribute used in the XML file. Required by the Load function
/// </summary>
public string Group { set; get; }
/// <summary>
/// Adjusts the labeling of the key designation. An empty value forces the default labeling
/// </summary>
public string KeyName
{
get { return labelKey.Text; }
set { labelKey.Text = value; }
}
/// <summary>
/// Adjusts the name of the key attribute used in the XML file. Required by the Load function
/// </summary>
public string Key { set; get; }
/// <summary>
/// Adjusts the labeling of the table header designation. An empty value forces the default labeling
/// </summary>
public string TableHeaderName
{
get { return dataGridViewValues.Columns[0].HeaderText; }
set { dataGridViewValues.Columns[0].HeaderText = value; }
}
/// <summary>
/// Adjusts the labeling of the encrypt value checkBox. An empty value forces the default labeling
/// </summary>
public string CheckBoxEncryptValueText
{
get { return checkBoxEncryptValues.Text; }
set
{
checkBoxEncryptValues.Text = value;
checkBoxEncryptValues.Enabled = !String.IsNullOrEmpty(Password);
}
}
/// <summary>
/// Controls whether values are always encrypted. An empty value forces the default value (false)
/// </summary>
public bool AlwaysEncrypted
{
get { return alwaysEncrypted; }
set
{
alwaysEncrypted = value;
checkBoxEncryptValues.Enabled = !alwaysEncrypted;
checkBoxEncryptValues.Checked = alwaysEncrypted;
}
}
/// <summary>
/// Adjusts the labeling of the default checkBox. An empty value forces the default labeling
/// </summary>
public string CheckBoxDefaultText
{
get { return checkBoxDefaultValue.Text; }
set
{
checkBoxDefaultValue.Text = value;
}
}
#endregion
#region Private values
private string password;
private bool alwaysEncrypted = false;
private bool standardValueSet = false;
private int selectedRow = 0;
private int rowIndexColored = 0;
private int StandardValue { get; set; }
#endregion
private void textBoxGroup_TextChanged(object sender, EventArgs e)
{
Group = textBoxGroup.Text;
buttonSave.Enabled = (!String.IsNullOrEmpty(textBoxGroup.Text) & !String.IsNullOrEmpty(textBoxKey.Text));
}
private void textBoxKey_TextChanged(object sender, EventArgs e)
{
Key = textBoxKey.Text;
buttonSave.Enabled = (!String.IsNullOrEmpty(textBoxGroup.Text) & !String.IsNullOrEmpty(textBoxKey.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);
}
}
if (StandardValue != 0)
{
dataGridViewValues.Rows[StandardValue - 1].DefaultCellStyle.ForeColor = Color.LightSeaGreen; //Standardwert noch einmal markiere, weil die Markierung manchmal zurückgesetzt wird
}
}
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();
}
}
else
{
SaveXML();
}
}
private void dataGridViewValues_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
if (dataGridViewValues.Rows.Count != 0)
{
checkBoxDefaultValue.Enabled = true; //Standardwert freischalten, sobald es einen Wert gibt
}
}
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)
{
if (dataGridViewValues.Rows.Count <=1)
{
checkBoxDefaultValue.Enabled = false;
}
//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
}
}
private void checkBoxDefaultValue_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxDefaultValue.Checked)
{
StandardValue = dataGridViewValues.SelectedCells[0].RowIndex + 1; //Zeile die als Standard ausgewählt wurde
standardValueSet = true; //Es gibt einen Standardwert
if (rowIndexColored != 0)
{
dataGridViewValues.Rows[rowIndexColored - 1].DefaultCellStyle.ForeColor = Color.Empty; //Wenn schon eine Zelle umgefärbt war, dann diese zurücksetzten
}
dataGridViewValues.Rows[dataGridViewValues.SelectedCells[0].RowIndex].DefaultCellStyle.ForeColor = Color.LightSeaGreen;
rowIndexColored = dataGridViewValues.SelectedCells[0].RowIndex + 1; //Die Zeile merken die umgefärbt wurde
}
else
{
if (standardValueSet & StandardValue == dataGridViewValues.SelectedCells[0].RowIndex + 1)
{
StandardValue = 0; //Es gibt keine ausgewählte Standardzeile
standardValueSet = false; //es gibt keinen Standardwert
dataGridViewValues.Rows[rowIndexColored - 1].DefaultCellStyle.ForeColor = Color.Empty; //Die ausgewählte Zelle umfärben
rowIndexColored = 0; //Es gibt keine umgefärbte Zeile
}
}
}
private void dataGridViewValues_RowEnter(object sender, DataGridViewCellEventArgs e)
{
SetStandard();
}
public void SetBasicValues()
{
if (!String.IsNullOrEmpty(Group))
{
textBoxGroup.Text = Group;
}
if (!String.IsNullOrEmpty(Key))
{
textBoxKey.Text = Key;
}
if (File.Exists(XMLfileName))
{
if (!String.IsNullOrEmpty(Group) && !String.IsNullOrEmpty(Key))
{
LoadXML();
}
}
if (StandardValue != 0)
{
dataGridViewValues.Rows[StandardValue - 1].DefaultCellStyle.ForeColor = Color.LightSeaGreen; //Standardwert noch einmal markiere, weil die Markierung manchmal zurückgesetzt wird
}
}
private void SetStandard()
{
try
{
if (StandardValue == dataGridViewValues.SelectedCells[0].RowIndex + 1)
{
checkBoxDefaultValue.Checked = true; //Wenn die ausgewählte Zeile den Standardwert enthält, dann die CheckBox anwählen
dataGridViewValues.Rows[dataGridViewValues.SelectedCells[0].RowIndex].DefaultCellStyle.ForeColor = Color.LightSeaGreen;
}
else
{
checkBoxDefaultValue.Checked = false; //Wenn die ausgewählte Zeile keinen Standardwert enthält, dann die CheckBox abwählen
dataGridViewValues.Rows[rowIndexColored + 1].DefaultCellStyle.ForeColor = Color.Empty;
}
}
catch (Exception)
{
//Nur die falsche Reihe ausgewählt, z.B. die Kopfzeile
}
}
private void LoadXML()
{
checkBoxEncryptValues.Checked = false;
var loadXML = new LoadXML();
loadXML.FileName = XMLfileName;
loadXML.Topic = Topic;
loadXML.Key = Key;
loadXML.Group = Group;
//loadXML.LoadAllValues = LoadXML.LoadAll.No;
//Wenn es schon Einträge in der Liste gibt, dann diese leeren
if (dataGridViewValues.RowCount != 1)
{
DialogResult result = MessageBox.Show(AppRes.msgBoxTxt002, AppRes.msgBoxCapt002, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.No)
{
return;
}
//Wenn es schon Werte gibt, dann diese löschen
dataGridViewValues.Rows.Clear();
}
loadXML.Load();
string[] values = new string[loadXML.Values.Length];
for (int i = 0; i < loadXML.Values.Length; i++)
{
values[i] = loadXML.Values[i];
}
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(values[i]); //Werte in die Tabelle schreiben
if (i == loadXML.Standard - 1)
{
StandardValue = loadXML.Standard; //Standardwert setzen
dataGridViewValues.Rows[i].DefaultCellStyle.ForeColor = Color.LightSeaGreen;
}
}
dataGridViewValues.Refresh();
textBoxKey.Text = loadXML.Key; //Key setzen
textBoxGroup.Text = loadXML.Group; //Gruppe setzen
SetStandard();
}
private void SaveXML()
{
if (!Directory.Exists(Path.GetDirectoryName(XMLfileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(XMLfileName)); //Wenn das Verzeichnis nicht existiert, dann erzeugen
}
int dgvLength = dataGridViewValues.RowCount - 1;
string value = "";
string[] values = new string[dgvLength];
for (int i = 0; i < dgvLength; i++)
{
if (checkBoxEncryptValues.Checked)
{
value = Encrypt(dataGridViewValues[0, i].Value.ToString(), Password); //Verschlüsselt
}
else
{
value = dataGridViewValues[0, i].Value.ToString(); //Unverschlüsselt
}
values[i] = value;
}
//Speichern
var saveXML = new SaveXML();
saveXML.FileName = XMLfileName;
//saveXML.MultiGroupFile = SaveXML.multigroupFile.No; //'No' muss nicht zwingend angegeben werden, ist der Standardwert
saveXML.Topic = "NX-Portal"; //z.B. "NX-Portal"
saveXML.Group = textBoxGroup.Text; //z.B. "NX"
//saveXML.GroupStandard = String.Concat(Group, "-", textBoxKey.Text); //z.B. "NX-Key"
saveXML.Key = textBoxKey.Text; //z.B. "Key"
saveXML.Values = values; //z.B. "NX 1953"
saveXML.Standard = StandardValue; //z.B. "2"
saveXML.Save();
}
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);
}
/// <summary>
/// Sets a customer width of the user control
/// </summary>
/// <param name="width">The width. Min=316, Max=800</param>
public void SetDialogWidth(int width)
{
if (width >= this.MinimumSize.Width && width <= this.MaximumSize.Width)
{
this.Width = width;
}
}
/// <summary>
/// Gets the values stored in the XML file
/// </summary>
/// <returns>An string array</returns>
public string[] GetValues()
{
checkBoxEncryptValues.Checked = false;
var loadXML = new LoadXML();
loadXML.FileName = XMLfileName;
loadXML.Topic = Topic;
loadXML.Key = Key;
loadXML.Group = Group;
loadXML.Load();
if (loadXML.Values == null)
{
return null;
}
else
{
string[] values = new string[loadXML.Values.Length];
for (int i = 0; i < loadXML.Values.Length; i++)
{
values[i] = loadXML.Values[i];
}
for (int i = 0; i < values.Length; i++)
{
if (values[i].StartsWith("$$$$"))
{
values[i] = Decrypt(values[i], Password);
}
}
return values;
}
}
}
}