tbf/DeviceTest/LocalSettings.cs
2017-01-13 18:35:08 +01:00

122 lines
3.2 KiB
C#

using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace DeviceTest
{
/// <summary>
/// Class to be serialized to an XML file...
/// </summary>
[XmlRootAttribute("DeviceTest")]
public class LocalSettings
{
public string ParentClassName;
public string ParentName;
public string ParentSettings;
public string ComponentClassName;
public string ComponentName;
public string ComponentParentName;
public string ComponentSettings;
public string Component2ClassName;
public string Component2Name;
public string Component2ParentName;
public string Component2Settings;
public LocalSettings()
{
}
/// <summary>
/// Load public fields of this class from the XML file.
/// </summary>
/// <returns>LocalSettings object or null when Load() fails</returns>
public static LocalSettings Load(string fileName)
{
try
{
using (TextReader reader = new StreamReader(fileName))
{
LocalSettings ls = (new XmlSerializer(typeof(LocalSettings))).Deserialize(reader) as LocalSettings;
// Copy the settings just in case De-serialize() completes OK
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
{
using (TextWriter writer = new StreamWriter(Program.LocalSettingsFileName))
{
(new XmlSerializer(typeof(LocalSettings))).Serialize(writer, this);
}
}
catch (Exception e)
{
string msg = e.Message;
}
}
/// <summary>
/// Updates history stored in a string array by a new latest string.
/// </summary>
/// <param name="lastStrValue">Last entered string</param>
/// <returns>true = updated and saved</returns>
public bool UpdateHistory(string lastStrValue, ref string[] history)
{
const int MaxHistoryLen = 10;
if (string.IsNullOrEmpty(lastStrValue)) return false;
int currentHistoryLength = (history != null) ? history.Length : 0;
int match = -1;
for (int i = 0; i < currentHistoryLength; i++)
{
if (history[i] == lastStrValue)
{
match = i;
break;
}
}
if (match >= 0 || currentHistoryLength >= MaxHistoryLen)
{
/// History does not have to be extended (because of a match) or should not be extended (because of the lenght)
if (match < 0) match = currentHistoryLength - 1;
for (int j = match; j > 0; j--)
{
history[j] = history[j - 1];
}
history[0] = lastStrValue;
}
else
{
/// History will be extended, new item inserted at the beginning
string[] newHistory = new string[currentHistoryLength + 1];
newHistory[0] = lastStrValue;
for (int j = 1; j <= currentHistoryLength; j++)
{
newHistory[j] = history[j - 1];
}
history = newHistory;
}
Save();
return true;
}
}
}