using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Collections;
using System.Xml.Serialization;
using System.Reflection;
using System.Globalization;
using log4net;
using uk.org.aspellclark.common;
namespace uk.org.aspellclark.common
{
/// <summary>
/// <name>PreferencesXml</name>
/// <namespace>uk.org.aspellclark.todolist.engine</namespace>
/// <version>1.0</version>
/// <author>Andy Aspell-Clark</author>
/// <description>This class holds preferences for the application
/// </description>
/// <history>
/// <historyitem> 6 Aug 2004 1.0 ARA Initial Version.</historyitem>
/// </history>
/// </summary>
[ XmlRoot("preferences") ]
public class PreferencesXml
{
// Create a logger for use in this class
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static PreferencesXml prefObj = null;
public static PreferencesXml GetPreferences(Assembly asm)
{
log.Info("Assembly for preferences ["+asm.ToString()+"]");
if (prefObj==null)
{
prefObj=new PreferencesXml(asm);
}
return prefObj;
}
public static PreferencesXml Preferences
{
get
{
return prefObj;
}
}
[XmlElement("Filename")]
private string m_sFileName = "preferences.xml";
[ XmlElement("FileCreation") ]
private DateTime m_dtFileCreationTime;
[ XmlElement("Preferences") ]
private Hashtable m_htPrefs = new Hashtable();
[ XmlElement("PrefsDirectory") ]
private string m_sPrefsDirectory;
//[ XmlElement("ExecutingAssembly") ]
//private Assembly asm = Assembly.GetExecutingAssembly();
/// <summary>
///
/// </summary>
private PreferencesXml(Assembly asm)
{
log.Info(String.Format("Constructions for [{0}]",asm.FullName));
CultureInfo ci = asm.GetName().CultureInfo;
m_sFileName = asm.GetName().ToString();
int indexOf = m_sFileName.IndexOf(",");
m_sFileName = m_sFileName.Substring(0, indexOf);
m_sFileName += "-prefs.xml";
log.Info(String.Format("preferences filename [{0}]", m_sFileName));
m_sPrefsDirectory = System.IO.Path.Combine(SystemInfo.MyDocumentsPath, ".aspellclark");
m_sPrefsDirectory = SystemInfo.MyDocumentsPath + System.IO.Path.DirectorySeparatorChar + ".aspellclark";
log.Info(String.Format("preferences directory [{0}]", m_sPrefsDirectory));
if (!File.Exists(m_sPrefsDirectory))
{
Directory.CreateDirectory(m_sPrefsDirectory);
}
if (!File.Exists(m_sPrefsDirectory+System.IO.Path.DirectorySeparatorChar +m_sFileName))
{
this.writeToFile();
}
DirectoryInfo dir = new DirectoryInfo(m_sPrefsDirectory);
log.Info(String.Format("looking for file [{0}] in directory [{1}]", m_sFileName, m_sPrefsDirectory));
foreach (FileInfo f in dir.GetFiles(m_sFileName))
{
log.Info(String.Format("found preference file [{0}]", f.FullName));
m_dtFileCreationTime = f.CreationTime;
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="psName"></param>
/// <returns></returns>
public string getPreference(string psName)
{
if (m_htPrefs.ContainsKey(psName))
{
return (string)m_htPrefs[psName];
}
else
{
return "";
}
}
/// <summary>
///
/// </summary>
/// <param name="psName"></param>
/// <param name="psValue"></param>
/// <returns></returns>
public void setPreference(string psName, string psValue)
{
if (m_htPrefs.ContainsKey(psName))
{
m_htPrefs[psName] = psValue;
}
else
{
m_htPrefs.Add(psName, psValue);
}
writeToFile();
}
/// <summary>
///
/// </summary>
/// <param name="psName"></param>
/// <returns></returns>
public void DeletePreference(string psName)
{
if (m_htPrefs.ContainsKey(psName))
{
m_htPrefs.Remove(psName);
}
}
/// <summary>
///
/// </summary>
public void readFromFile()
{
String fullFilename = String.Format("{0}{1}{2}", m_sPrefsDirectory, System.IO.Path.DirectorySeparatorChar, m_sFileName);
log.Info(String.Format("Reading file [{0}]", fullFilename));
XmlTextReader reader = null;
try
{
// Load the file with an XmlTextReader
log.Info(String.Format("Reading file [{0}]",fullFilename));
reader = new XmlTextReader (fullFilename);
log.Info(String.Format("File [{0}] read sucessfully", fullFilename));
// Process the supplied XML file
log.Info("Processing ...");
FormatXml(reader, m_sFileName);
}
catch (Exception e)
{
string sMsg = e.Message;
log.Info (String.Format("Failed to read the file [{0}]", m_sFileName));
log.Info (String.Format("Exception: [{0}]", sMsg));
}
finally
{
log.Info(String.Format("Processing of the file [{0}] complete", m_sFileName));
// Finished with XmlTextReader
if (reader != null)
{
reader.Close();
}
}//finally
}
private void FormatXml (XmlReader reader, String filename)
{
int declarationCount = 0;
int piCount = 0;
int docCount = 0;
int commentCount = 0;
int elementCount = 0;
int attributeCount = 0;
int textCount = 0;
int whitespaceCount = 0;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.XmlDeclaration:
//Format (reader, "XmlDeclaration");
declarationCount++;
break;
case XmlNodeType.ProcessingInstruction:
//Format (reader, "ProcessingInstruction");
piCount++;
break;
case XmlNodeType.DocumentType:
//Format (reader, "DocumentType");
docCount++;
break;
case XmlNodeType.Comment:
//Format (reader, "Comment");
commentCount++;
break;
case XmlNodeType.Element:
//Format (reader, "Element");
elementCount++;
string sName = "";
string sValue = "";
if (reader.Name == "Item")
{
if (reader.HasAttributes)
{
attributeCount += reader.AttributeCount;
while (reader.MoveToNextAttribute())
{
if (reader.Name == "Name")
{
sName = reader.Value;
}
else if (reader.Name == "Value")
{
sValue = reader.Value;
}
}
}
m_htPrefs.Add(sName, sValue);
}
break;
case XmlNodeType.Text:
//Format (reader, "Text");
textCount++;
break;
case XmlNodeType.Whitespace:
whitespaceCount++;
break;
}
}
// Display the Statistics for the file.
// Console.WriteLine ();
// Console.WriteLine("Statistics for {0} file", filename);
// Console.WriteLine ();
// Console.WriteLine("XmlDeclaration: {0}",declarationCount++);
// Console.WriteLine("ProcessingInstruction: {0}",piCount++);
// Console.WriteLine("DocumentType: {0}",docCount++);
// Console.WriteLine("Comment: {0}",commentCount++);
// Console.WriteLine("Element: {0}",elementCount++);
// Console.WriteLine("Attribute: {0}",attributeCount++);
// Console.WriteLine("Text: {0}",textCount++);
// Console.WriteLine("Whitespace: {0}",whitespaceCount++);
}
private void Format(XmlReader reader, String nodeType)
{
// Format the output
// Console.Write(reader.Depth + " ");
// Console.Write(reader.AttributeCount + " ");
// for (int i = 0; i < reader.Depth; i++)
// {
// Console.Write('\t');
// }
//Console.Write(reader.Prefix + nodeType + "<" + reader.Name + ">" + reader.Value);
// Display the attributes values for the current node
// if (reader.HasAttributes)
// {
// Console.Write(" Attributes:");
//
// for (int j = 0; j < reader.AttributeCount; j++)
// {
// Console.Write(" [{0}] " + reader[j], j);
// }
// }
// Console.WriteLine();
}
/// <summary>
///
/// </summary>
public void writeToFile()
{
String fullFilename = String.Format("{0}{1}{2}", m_sPrefsDirectory, System.IO.Path.DirectorySeparatorChar, m_sFileName);
String bakFilename = String.Format("{0}{1}", fullFilename, ".bak");
if (File.Exists(fullFilename) )
{
if (File.Exists(bakFilename))
{
File.Delete(bakFilename);
}
File.Move(fullFilename, bakFilename);
}
log.Info(String.Format("Writing file [{0}]", fullFilename));
XmlTextWriter xmlWriter = new XmlTextWriter(fullFilename, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 4;
xmlWriter.IndentChar = ' ';
xmlWriter.WriteStartDocument();
//write out the root element - Project
xmlWriter.WriteStartElement("Preferences");
xmlWriter.WriteAttributeString("", "FILENAME", "", m_sFileName);
foreach (string str in m_htPrefs.Keys)
{
xmlWriter.WriteStartElement("Item");
xmlWriter.WriteAttributeString("", "Name", "", str);
xmlWriter.WriteAttributeString("", "Value", "", m_htPrefs[str].ToString());
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
}
}//class()
}//namespace()