tbf/TBF/LocalSettings.cs

457 lines
16 KiB
C#
Raw Normal View History

///
/// Copyright (c) 2013-2019 Sensus Slovensko a.s.
///
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;
namespace TBF
{
/// <summary>
/// Class to be serialized to an XML file...
/// Public members are local settings.
/// These settings are modified by dialogs invoked by menu items
/// Edit->Preferences ... PreferencesDlg ... S1.1(language, etc. local settings), and
/// Edit->Advanced settings ... AdvancedSettingsDlg ... S1.2(spec. where bench settings are stored)
/// </summary>
[XmlRootAttribute("TestBenchFramework")]
public class LocalSettings
{
static XmlSerializer serializer = XmlSerializer.FromTypes(new[] { typeof(LocalSettings) })[0];
static byte[] cryptoKey = new byte[] { 235, 7, 236, 58, 24, 225, 97, 102, 231, 1, 121, 12, 177, 145, 87, 200,
102, 85, 152, 73, 230, 203, 101, 169, 242, 213, 228, 219, 239, 157, 245, 156 };
static byte[] cryptoIV = new byte[] { 189, 23, 137, 56, 204, 241, 242, 118, 28, 89, 9, 198, 224, 111, 186, 125 };
/// <summary>
/// User interface language (used as CultureInfo(..) constructor argument).
/// </summary>
public string Language = "en";
/// <summary>
/// Names and database settings of test benches.
/// </summary>
[XmlArrayAttribute("TestBenches")]
public Config.DatabaseSettings[] TestBenches;
[XmlIgnore]
public int BenchesCount { get { return (TestBenches != null) ? TestBenches.GetLength(0) : 0; } }
/// <summary>
/// Login method: UserName, FullName or Number
/// </summary>
public Users.Entities.LoginMethod LoginMethod;
/// <summary>
/// Currently selected bench name (local or remote) or null (= no selection done).
/// </summary>
[XmlElementAttribute("LastBench")]
public string LastBenchName;
/// <summary>
/// Currently selected procedure name or null (= no selection done yet).
/// </summary>
[XmlElementAttribute("LastProcedure")]
public string LastProcedureName;
public Users.Entities.DBKind LastProcedureDB;
public int LastProcedureNr;
public int BatchNr;
public double RealDensity; /// water density [kg/m3]
public double AtTemperature; /// measured at temperature [degree C]
public int RightPaneHorizSplitterDistance;
public int TopPaneVerticalSplitterDistance;
/// MainWnd
public bool MainWndMaximized;
public int MainWndLeft;
public int MainWndTop;
public int MainWndWidth;
public int MainWndHeight;
/// Components
public bool ComponentsDlgMaximized;
public int ComponentsDlgLeft;
public int ComponentsDlgTop;
public int ComponentsDlgWidth;
public int ComponentsDlgHeight;
/// Pop-up results
public int PopupResultsLeft;
public int PopupResultsTop;
public int PopupResultsWidth;
public int PopupResultsHeight;
public Config.Entities.CameraDisplayResolution Resolution;
[XmlArrayAttribute("Counters")]
public int[] Counters;
[XmlArrayAttribute("ComponentsColumnWidths")]
public int[] ComponentsColumnWidths;
[XmlIgnore]
public int ComponentsColumnCount { get { return (ComponentsColumnWidths != null) ? ComponentsColumnWidths.Length : 0; } }
/// Paths
public bool PathsDlgMaximized;
public int PathsDlgLeft;
public int PathsDlgTop;
public int PathsDlgWidth;
public int PathsDlgHeight;
/// iPerlCommunicationsForm
public int iPerlCommunicationsFormLeft;
public int iPerlCommunicationsFormTop;
public long iPerlCommunicationsFormCheckboxes;
[XmlArrayAttribute("FeedingColumnWidths")]
public int[] FeedingColumnWidths;
[XmlIgnore]
public int FeedingColumnCount { get { return (FeedingColumnWidths != null) ? FeedingColumnWidths.Length : 0; } }
[XmlArrayAttribute("BenchColumnWidths")]
public int[] BenchColumnWidths;
[XmlIgnore]
public int BenchColumnCount { get { return (BenchColumnWidths != null) ? BenchColumnWidths.Length : 0; } }
[XmlArrayAttribute("OutputColumnWidths")]
public int[] OutputColumnWidths;
[XmlIgnore]
public int OutputColumnCount { get { return (OutputColumnWidths != null) ? OutputColumnWidths.Length : 0; } }
[XmlArrayAttribute("MetersColumnWidths")]
public int[] MetersColumnWidths;
[XmlIgnore]
public int MetersColumnCount { get { return (MetersColumnWidths != null) ? MetersColumnWidths.Length : 0; } }
[XmlArrayAttribute("HeatMetersColumnWidths")]
public int[] HeatMetersColumnWidths;
[XmlIgnore]
public int HeatMetersColumnCount { get { return (HeatMetersColumnWidths != null) ? HeatMetersColumnWidths.Length : 0; } }
/// Transitions
public bool TransitionsDlgMaximized;
public int TransitionsDlgLeft;
public int TransitionsDlgTop;
public int TransitionsDlgWidth;
public int TransitionsDlgHeight;
[XmlArrayAttribute("TransitionsColumnWidths")]
public int[] TransitionsColumnWidths;
[XmlIgnore]
public int TransitionsColumnCount { get { return (TransitionsColumnWidths != null) ? TransitionsColumnWidths.Length : 0; } }
/// Metrology
public bool MetrologyDlgMaximized;
public int MetrologyDlgLeft;
public int MetrologyDlgTop;
public int MetrologyDlgWidth;
public int MetrologyDlgHeight;
/// Procedures
public bool ProceduresDlgMaximized;
public int ProceduresDlgLeft;
public int ProceduresDlgTop;
public int ProceduresDlgWidth;
public int ProceduresDlgHeight;
[XmlArrayAttribute("ProceduresColumnWidths")]
public int[] ProceduresColumnWidths;
[XmlIgnore]
public int ProceduresColumnCount { get { return (ProceduresColumnWidths != null) ? ProceduresColumnWidths.Length : 0; } }
/// OneProcedure
public bool OneProcedureDlgMaximized;
public int OneProcedureDlgLeft;
public int OneProcedureDlgTop;
public int OneProcedureDlgWidth;
public int OneProcedureDlgHeight;
public int PrintOrderLeft;
public int PrintOrderTop;
[XmlArrayAttribute("HistoryColumnWidths")]
public int[] HistoryColumnWidths;
[XmlIgnore]
public int HistoryColumnCount { get { return (HistoryColumnWidths != null) ? HistoryColumnWidths.Length : 0; } }
2016-12-07 16:19:01 +00:00
/// Endurance test cycle steps
public int EnduranceDlgLeft;
public int EnduranceDlgTop;
public int EnduranceDlgWidth;
public int EnduranceDlgHeight;
/// Serial numbers
public string[] LastSNTexts;
[XmlIgnore]
public int LastSNTextsCount { get { return (LastSNTexts != null) ? LastSNTexts.Length : 0; } }
public string[] LastMainSNTexts;
[XmlIgnore]
public int LastMainSNTextsCount { get { return (LastMainSNTexts != null) ? LastMainSNTexts.Length : 0; } }
public string[] LastAuxSNTexts;
[XmlIgnore]
public int LastAuxSNTextsCount { get { return (LastAuxSNTexts != null) ? LastAuxSNTexts.Length : 0; } }
public string LastText1;
public string LastText2;
public string LastText3;
public string LastRemark;
/// Purchase order history
public string[] PurchaseOrderHistory;
[XmlIgnore]
public int PurchaseOrderHistoryCount { get { return (PurchaseOrderHistory != null) ? PurchaseOrderHistory.Length : 0; } }
/// Prefix history
public string[] PrefixHistory;
[XmlIgnore]
public int PrefixHistoryCount { get { return (PrefixHistory != null) ? PrefixHistory.Length : 0; } }
/// Remarks history
public string[] RemarkHistory;
[XmlIgnore]
public int RemarksHistoryCount { get { return (RemarkHistory != null) ? RemarkHistory.Length : 0; } }
/// Tester history
public string[] TesterHistory;
[XmlIgnore]
public int TesterHistoryCount { get { return (TesterHistory != null) ? TesterHistory.Length : 0; } }
public bool PrintOrderOnlyGoodResult;
public bool PrintOrderOnlyLastResult;
/// Legalizator history
public string[] LastLegalizators;
[XmlIgnore]
public int LastLegalizatorsCount { get { return (LastLegalizators != null) ? LastLegalizators.Length : 0; } }
2015-01-12 14:09:09 +00:00
/// Configuration of results
public Config.Entities.MetersArrangement ResultsConfigMeters;
public Config.Entities.TestsArrangement ResultsConfigTests;
public int ResultsConfigMetersInOneGroup;
public int ResultsConfigMinWidth;
public int ResultsConfigMinHeight;
public string[] RsltItems_Screen_SingleWM;
public string[] RsltItems_Screen_CombinedWM;
public string[] RsltItems_Screen_HeatM;
/// Configuration of graphs
public bool Graph1_On;
public bool Graph2_On;
public bool Graph3_On;
public bool Graph4_On;
public bool Graph5_On;
public bool Graph6_On;
public bool Graph7_On;
public bool Graph8_On;
public GraphLib.PlotterGraphPaneEx.LayoutMode GraphsLayoutMode;
[XmlArrayAttribute("RsltsClmnWidths")]
public int[] RsltsClmnWidths;
[XmlIgnore]
public int RsltsClmnCount { get { return (RsltsClmnWidths != null) ? RsltsClmnWidths.Length : 0; } }
[XmlIgnore]
public readonly bool AlwaysAskPasswdWhenUnlocking;
[XmlIgnore]
public readonly bool RestoreUserWhenLeavingDialog;
public LocalSettings()
{
AlwaysAskPasswdWhenUnlocking = false;
RestoreUserWhenLeavingDialog = true;
}
/// <summary>
/// Load public fields of this class from the XML file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>
/// LocalSettings object or null when Load() fails
/// </returns>
public static LocalSettings Load(string fileName)
{
try
{
bool isEncrypted = true;
using (StreamReader reader = new StreamReader(fileName))
{
isEncrypted = !reader.ReadLine().StartsWith("<?xml version=");
reader.Close();
}
2017-11-16 13:25:58 +00:00
if (isEncrypted)
{
int length = (int)(new FileInfo(fileName).Length);
Stream stream = File.OpenRead(fileName);
using (BinaryReader binaryReader = new BinaryReader(stream))
{
/// Load encrypted binary data into an array
byte[] encrypted = new byte[length];
int bytesRead = binaryReader.Read(encrypted, 0, length);
if (bytesRead != length) return null;
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = myRijndael.CreateDecryptor(cryptoKey, cryptoIV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(encrypted))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
TextReader txtReader = new StringReader(srDecrypt.ReadToEnd());
LocalSettings ls = serializer.Deserialize(txtReader) as LocalSettings;
ls.UpdateResultsOutputData();
return ls;
}
}
}
}
}
}
else
{
using (StreamReader reader = new StreamReader(fileName))
{
LocalSettings ls = serializer.Deserialize(reader) as LocalSettings;
ls.UpdateResultsOutputData();
return ls;
}
}
}
catch (Exception e)
{
string msg = e.Message;
return null;
}
}
/// <summary>
/// Save public fields of this class to the XML file.
/// </summary>
public void Save()
{
try
{
UpdateResultsOutputData();
#if PUCHONG_200
/// Write settings to an unencrypted file
using (TextWriter writer = new StreamWriter(Program.LocalSettingsFileName))
{
serializer.Serialize(writer, this);
}
#else
/// Write settings to a string
StringBuilder plain = new StringBuilder();
using (TextWriter writer = new StringWriter(plain))
{
serializer.Serialize(writer, this);
}
/// Encrypt and write to a file
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
/// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = myRijndael.CreateEncryptor(cryptoKey, cryptoIV);
/// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
/// Write all data to the stream.
swEncrypt.Write(plain);
}
Stream stream = File.OpenWrite(Program.LocalSettingsFileName);
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(msEncrypt.ToArray());
}
}
}
}
#endif
}
catch (Exception e)
{
string msg = e.Message;
}
}
/// <summary>
/// To be able to have RealDensity and AtTemperatire in reports.
/// </summary>
void UpdateResultsOutputData()
2017-11-16 13:25:58 +00:00
{
Results.WMeterRsltItemSpec.RealDensity = this.RealDensity;
Results.WMeterRsltItemSpec.AtTemperature = this.AtTemperature;
2017-11-16 13:25:58 +00:00
}
/// <summary>
/// Updates history stored in a string array by a new latest string.
/// </summary>
/// <param name="lastStrValue">Lste entered string</param>
/// <returns>true = updated and saved</returns>
public bool UpdateHistory(string lastStrValue, ref string[] history, int maxHistoryLen = 10)
{
if (string.IsNullOrEmpty(lastStrValue)) return false;
int currentHistoryCount = (history != null) ? history.Length : 0;
int match = -1;
for (int i = 0; i < currentHistoryCount; i++)
{
if (history[i] == lastStrValue)
{
match = i;
break;
}
}
if (match >= 0 || currentHistoryCount >= maxHistoryLen)
{
/// History does not have to be (because of a match) or should not be extended (because of the lenght)
if (match < 0) match = currentHistoryCount - 1;
for (int j = match; j > 0; j--)
{
history[j] = history[j - 1];
}
history[0] = lastStrValue;
}
else
{
/// History wiil be extended, new item inserted at the beginning
string[] newHistory = new string[currentHistoryCount + 1];
newHistory[0] = lastStrValue;
for (int j = 1; j <= currentHistoryCount; j++)
{
newHistory[j] = history[j - 1];
}
history = newHistory;
}
Save();
return true;
}
}
}