using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using Linx2.Common.Framework.Components;
using Linx2.Common.Framework.Configuration;
using Linx2.Common.Framework.Encryption;
using Linx2.Common.Framework.Enum;
using Linx2.Common.Framework.Interface.WcfService;
using Linx2.Common.Framework.TitleConversion;
using Linx2.Common.Framework.Utility;
using MXLocalTools.QtxStxConverter.DataImporters;
using MXLocalTools.QtxStxConverter.DataStructures;
using MXLocalTools.QtxStxConverter.Utilities;
using NHibernate.Exceptions;
using Cursors = System.Windows.Forms.Cursors;
namespace MXLocalTools.QtxStxConverter.View
public partial class QtxStxConverterView : Form
protected static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected static readonly ILog ResultLog = LogManager.GetLogger(Converter.ResultLogName);
private static bool _consoleMode;
private static bool _validVersion;
private const string Log4NetConfigFilename = "QtxStxConverter.exe.log4net";
public static bool RunComplete { get; set; }
private List<FileInfo> _linx2FileInfos;
private List<FileInfo> _specAgentFileInfos;
private List<FileInfo> _wordFileInfos;
private readonly IWindsorContainer _container;
public QtxStxConverterView()
LoggingHelper.ConfigureLogging(this, Log4NetConfigFilename);
if (!WordDocConverter.WordInstalled)
Log.Error("Cannot detect a valid Microsoft Word version. Word is necessary for conversion. Install Word then try again.");
MessageBox.Show(this, "Cannot detect a valid Microsoft Word version. Word is necessary for conversion. Install Word then try again.", "Microsoft Word Required", MessageBoxButtons.OK, MessageBoxIcon.Error);
lblCurrentSection.Text = "Setting up DI / IoC.";
_container = new WindsorContainer();
var diSetup = new ConverterDiSetup(_container);
var configProvider = new AppConfigDatabaseConfigurationProvider(_container.Resolve<IEncryptionProvider>());
var message = String.Format("Database connection info: Server={0}, DB name={1}, DB user={2}, DB type={3}, Connection string=\"{4}\"",
configProvider.ServerName, configProvider.DatabaseName, configProvider.UserName,
StringValueAttribute.GetStringValue(configProvider.DatabaseType),
configProvider.ConnectionString);
ResultLog.InfoFormat(message);
var dbVersionChecker = _container.Resolve<DatabaseVersionChecker>();
_validVersion = dbVersionChecker.IsDatabaseVersionCorrect();
diSetup.RegisterComponents();
catch (GenericADOException)
catch (InvalidOperationException)
var datetimeNow = DateTime.Now;
Log.Error(datetimeNow + " Exception: " + exc.Message);
ResultLog.Error(datetimeNow + " Exception: " + exc.Message);
if (exc.InnerException != null)
Log.Error(datetimeNow + "\tInner exception: " + exc.InnerException.Message);
ResultLog.Error(datetimeNow + "\tInner exception: " + exc.InnerException.Message);
MessageBox.Show("Exception Thrown: " + exc.Message);
lblCurrentSection.Text = string.Empty;
public void QtxStxConverterView_Load(object sender, EventArgs e)
public void InitializeView(bool inConsoleMode)
_consoleMode = inConsoleMode;
lblLinx2Directory.Text = Properties.Settings.Default.LastDirectory;
lblSpecAgentDirectory.Text = Properties.Settings.Default.LastSpecAgentDirectory;
lblWordDirectory.Text = Properties.Settings.Default.LastWordDirectory;
rbLoggingOn.Checked = Properties.Settings.Default.LoggingOn;
rbLoggingOff.Checked = !Properties.Settings.Default.LoggingOn;
rbInitializeDatabaseOn.Checked = Properties.Settings.Default.InitializeDatabase;
rbInitializeDatabaseOff.Checked = !Properties.Settings.Default.InitializeDatabase;
rbAddTestProjectsOn.Checked = Properties.Settings.Default.AddTestDataOn;
rbAddTestProjectsOff.Checked = !Properties.Settings.Default.AddTestDataOn;
rbBreakOnErrorOn.Checked = Properties.Settings.Default.BreakOnError;
rbBreakOnErrorOff.Checked = !Properties.Settings.Default.BreakOnError;
rbShowVisualizersOn.Checked = Properties.Settings.Default.ShowVisualizers;
rbShowVisualizersOff.Checked = !Properties.Settings.Default.ShowVisualizers;
var configProvider = new AppConfigDatabaseConfigurationProvider(_container.Resolve<IEncryptionProvider>());
tbServer.Text = configProvider.ServerName;
tbDatabase.Text = configProvider.DatabaseName;
tbDbType.Text = StringValueAttribute.GetStringValue(configProvider.DatabaseType);
var endpoints = AppSettingsInterface.GetServiceEndpoints();
lvEnpoints.Items.Clear();
var listViewItem = new ListViewItem(new[] { x.Key, x.Value });
lvEnpoints.Items.Add(listViewItem);
private bool ValidateDirectories()
var linx2DirectoryInfo = new DirectoryInfo(lblLinx2Directory.Text);
if (!linx2DirectoryInfo.Exists)
lblLinx2Directory.Text = Application.StartupPath;
var specAgentDirectoryInfo = new DirectoryInfo(lblSpecAgentDirectory.Text);
if (!specAgentDirectoryInfo.Exists)
lblSpecAgentDirectory.Text = Application.StartupPath;
var wordDirectoryInfo = new DirectoryInfo(lblWordDirectory.Text);
if (!wordDirectoryInfo.Exists)
lblWordDirectory.Text = Application.StartupPath;
private void UpdateListView()
Cursor = Cursors.WaitCursor;
lvLinxFiles.Items.Clear();
var linx2DirectoryInfo = new DirectoryInfo(lblLinx2Directory.Text);
_linx2FileInfos = LoadFolderFiles(linx2DirectoryInfo.FullName, ".stx");
int stxCount = _linx2FileInfos.Count;
lblSTXCount.Text = stxCount.ToString();
var qtxList = LoadFolderFiles(linx2DirectoryInfo.FullName, ".qtx");
_linx2FileInfos.AddRange(qtxList);
int qtxCount = qtxList.Count;
lblQTXCount.Text = qtxCount.ToString();
_linx2FileInfos.ForEach(x => lvLinxFiles.Items.Add(x.Name));
lvSpecAgentFiles.Items.Clear();
var specAgentDirectoryInfo = new DirectoryInfo(lblSpecAgentDirectory.Text);
_specAgentFileInfos = LoadFolderFiles(specAgentDirectoryInfo.FullName, ".stx");
int specAgentCount = _specAgentFileInfos.Count;
lblSpecAgentCount.Text = specAgentCount.ToString();
_specAgentFileInfos.ForEach(x => lvSpecAgentFiles.Items.Add(x.Name));
lvWordFiles.Items.Clear();
var wordDirectoryInfo = new DirectoryInfo(lblWordDirectory.Text);
_wordFileInfos = LoadFolderFiles(wordDirectoryInfo.FullName, ".doc", ".DOC", ".Doc");
int wordCount = _wordFileInfos.Count;
lblWordFileCount.Text = wordCount.ToString();
_wordFileInfos.ForEach(x => lvWordFiles.Items.Add(x.Name));
lblTotalCount.Text = (stxCount + qtxCount + wordCount + specAgentCount).ToString();
private List<FileInfo> LoadFolderFiles(string folder, params string[] validExtensions)
var list = new List<FileInfo>();
var directoryInfo = new DirectoryInfo(folder);
foreach (FileInfo info in directoryInfo.GetFiles())
foreach (var extension in validExtensions)
if (info.Name.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
if (chkLoadChildFolders.Checked)
foreach (var info in directoryInfo.GetDirectories())
list.AddRange(LoadFolderFiles(info.FullName, validExtensions));
private void OnChangeDirectoryClick(object sender, EventArgs e)
var browserDialog = GetFolderBrowserDialog(lblLinx2Directory.Text);
DialogResult result = browserDialog.ShowDialog(this);
if (result == DialogResult.OK)
Cursor = Cursors.WaitCursor;
Properties.Settings.Default.LastDirectory = browserDialog.SelectedPath;
Properties.Settings.Default.Save();
lblLinx2Directory.Text = browserDialog.SelectedPath;
private FolderBrowserDialog GetFolderBrowserDialog(string path)
var browserDialog = new FolderBrowserDialog();
var fileInfo = new FileInfo(path);
browserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
browserDialog.SelectedPath = fileInfo.FullName;
browserDialog.Description = "Select the target directory ...";
browserDialog.ShowNewFolderButton = false;
private void OnConvertButtonClick(object sender, EventArgs e)
public void StartConverter()
if (!ValidateDirectories())
Cursor = Cursors.WaitCursor;
conversionTimer.Tick += OnConversionTimerTick;
progressBar.Style = ProgressBarStyle.Continuous;
ResultLog.InfoFormat("Altarix QtxStxConverter Started: {0}\r\n", DateTime.Now);
ResultLog.InfoFormat("STX file path: {0}", lblLinx2Directory.Text);
ResultLog.InfoFormat("SpecAgent STX file path: {0}", lblSpecAgentDirectory.Text);
ResultLog.InfoFormat("Word Doc file path: {0}\r\n", lblWordDirectory.Text);
ResultLog.InfoFormat("File counts: stx({0}) qtx({1}) specagent({2}) word({3})\r\n"
, lblSTXCount.Text, lblQTXCount.Text, lblSpecAgentCount.Text, lblWordFileCount.Text);
if (rbInitializeDatabaseOn.Checked || !_validVersion)
EntityConverter.CurrentSectionName = "Initializing the database";
var dbCreator = new DbCreator(new AppConfigDatabaseConfigurationProvider(new Linx2EncryptionProvider()));
var dataImportController = _container.Resolve<DataImportController>();
dataImportController.Import();
var projectService = _container.Resolve<IProjectService>();
using (var session = _container.Resolve<ISession>())
projectService.OpenFirmProject(session);
EntityConverter.CurrentSectionName = "Compiling file list...";
var files = new List<string>();
foreach (object item in lvLinxFiles.Items)
files.Add(lblLinx2Directory.Text + Path.DirectorySeparatorChar + ((ListViewItem)item).Text);
ProjectImportInfo projectImportInfo = CheckForProjectImportInfo();
if (projectImportInfo != null)
ISectionService sectionService = _container.Resolve<ISectionService>();
Thread converterThread = new Thread(RunConverter);
{ _linx2FileInfos, rbLoggingOn.Checked, projectImportInfo
, rbAddTestProjectsOn.Checked, sectionService, _specAgentFileInfos
, rbAddTestNotesOn.Checked, lblLinx2Directory.Text, _wordFileInfos
, _container.Resolve<TitleConverter>(), _container.Resolve<ISessionFactory>()
converterThread.Start(param);
private void SetGuiEnabled(bool enable)
btnLoadTestPop.Enabled = enable && _validVersion;
btnConvert.Enabled = enable;
btnChangeDirectory.Enabled = enable;
btnChangeSpecAgentDirectory.Enabled = enable;
btnChangeWordDirectory.Enabled = enable;
chkLoadChildFolders.Enabled = enable;
rbLoggingOn.Enabled = enable;
rbLoggingOff.Enabled = enable;
rbAddTestNotesOn.Enabled = enable;
rbAddTestNotesOff.Enabled = enable;
rbAddTestProjectsOff.Enabled = enable;
rbAddTestProjectsOn.Enabled = enable;
rbInitializeDatabaseOn.Enabled = enable;
rbInitializeDatabaseOff.Enabled = enable;
rbInitializeDatabaseOn.Checked = true;
rbInitializeDatabaseOn.Enabled = false;
rbInitializeDatabaseOff.Enabled = false;
lblVersionWarning.Visible = true;
rbBreakOnErrorOn.Enabled = enable;
rbBreakOnErrorOff.Enabled = enable;
rbShowVisualizersOn.Enabled = enable;
rbShowVisualizersOff.Enabled = enable;
private static void RunConverter(object param)
var paramArray = (object[])param;
var linxFiles = (List<FileInfo>)paramArray[0];
var logFilePerSection = (bool)paramArray[1];
var projectImportInfo = (ProjectImportInfo)paramArray[2];
var createTestProject = (bool)paramArray[3];
var sectionService = (ISectionService)paramArray[4];
var specAgentFiles = (List<FileInfo>)paramArray[5];
var createTestNotes = (bool)paramArray[6];
var directory = (string)paramArray[7];
var wordDocFiles = (List<FileInfo>)paramArray[8];
var titleConverter = (TitleConverter)paramArray[9];
var sessionFactory = (ISessionFactory)paramArray[10];
var container = (IWindsorContainer)paramArray[11];
EntityConverter.ImportSourceFilesIntoDatabase(linxFiles, specAgentFiles, wordDocFiles, logFilePerSection
, projectImportInfo, createTestProject, createTestNotes, sectionService, directory
, titleConverter, sessionFactory, container);
BinaryFileConverter.CreateZipfile();
Console.WriteLine(e.Message);
MessageBox.Show(e.Message);
ApplicationSettings.ExitAltarixWithErrorCode(ApplicationExitCode.ConverterThreadFailed);
ResultLog.InfoFormat("\r\nAltarix QtxStxConverter Ended: {0}", DateTime.Now);
public void OnConversionTimerTick(object sender, EventArgs e)
lblCurrentSection.Text = EntityConverter.CurrentSectionName;
lblCurrentProgress.Text = EntityConverter.CurrentSectionStatus + " [" + EntityConverter.CurrentInstructionCount + "]";
lblCurrent.Text = EntityConverter.CurrentSectionCount.ToString();
lblTotal.Text = EntityConverter.SectionTotalCount.ToString();
var outputA = string.Format("({0} / {1}) Section {2}",
EntityConverter.CurrentSectionCount,
EntityConverter.SectionTotalCount,
EntityConverter.CurrentSectionName);
var outputB = string.Format("[{0}:{1}]",
EntityConverter.CurrentSectionStatus,
EntityConverter.CurrentInstructionCount);
Console.WriteLine(outputA);
Console.WriteLine(outputB);
if (EntityConverter.FileLoadComplete)
progressBar.Maximum = EntityConverter.SectionTotalCount;
progressBar.Value = EntityConverter.CurrentSectionCount;
progressBar.Maximum = EntityConverter.SectionTotalCount;
progressBar.Value = EntityConverter.CurrentSectionCount;
if (EntityConverter.ConversionComplete)
if (EntityConverter.FailedToParse.Count + EntityConverter.FailedToSaveToDatabase.Count == 0)
const string message = "Conversion complete.";
Console.WriteLine(message);
MessageBox.Show(this,message, "Complete");
string output = "Sections failed, stop the debugger?";
if (EntityConverter.FailedToParse.Count > 0)
output += "\n\n\nThe following files failed to parse:\n";
foreach (var pair in EntityConverter.FailedToParse)
output += pair.First + ", ";
if (EntityConverter.FailedToSaveToDatabase.Count > 0)
output += "\n\n\nThe following sections failed to save to DB:\n";
foreach (var pair in EntityConverter.FailedToSaveToDatabase)
output += pair.First + ", ";
Console.WriteLine(output);
DialogResult result = MessageBox.Show(output, "Failed Imports", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
if (result == DialogResult.Yes)
Debug.Assert(EntityConverter.FailedToParse.Count + EntityConverter.FailedToSaveToDatabase.Count == 0, "For your debugging pleasure.");
private ProjectImportInfo CheckForProjectImportInfo()
FileInfo projectImportInfoFile = null;
var directory = new DirectoryInfo(lblLinx2Directory.Text);
foreach (var file in directory.GetFiles())
if (file.Name == ProjectImportInfo.ProjectImportInfoFileName)
projectImportInfoFile = file;
var projectImportInfo = new ProjectImportInfo(projectImportInfoFile);
return projectImportInfo;
catch (ProjectImportInfoException e)
MessageBox.Show(e.Message, e.Caption, MessageBoxButtons.OK);
if (e.InnerException == null)
ResultLog.ErrorFormat("Problem regarding the projectImportInfo file: Exception is: {0}\n\r", e.Message);
ApplicationSettings.ExitAltarixWithErrorCode(ApplicationExitCode.NoProjectImportInfo);
private void OnLoggingChanged(object sender, EventArgs e)
Properties.Settings.Default.LoggingOn = rbLoggingOn.Checked;
Properties.Settings.Default.Save();
private void OnAddTestDataChanged(object sender, EventArgs e)
Properties.Settings.Default.AddTestDataOn = rbAddTestProjectsOn.Checked;
Properties.Settings.Default.Save();
private void OnInitializeDbChanged(object sender, EventArgs e)
Properties.Settings.Default.InitializeDatabase = rbInitializeDatabaseOn.Checked;
Properties.Settings.Default.Save();
private void OnBreakOnErrorChanged(object sender, EventArgs e)
EntityConverter.DebuggerBreakOnError = rbBreakOnErrorOn.Checked;
Properties.Settings.Default.BreakOnError = rbBreakOnErrorOn.Checked;
Properties.Settings.Default.Save();
private void OnShowVisualizersChanged(object sender, EventArgs e)
EntityConverter.ShowVisualizers = rbShowVisualizersOn.Checked;
ContentComparer.ShowVisualizers = rbShowVisualizersOn.Checked;
Properties.Settings.Default.ShowVisualizers = rbShowVisualizersOn.Checked;
Properties.Settings.Default.Save();
private void btnChangeSpecAgentDirectory_Click(object sender, EventArgs e)
var browserDialog = GetFolderBrowserDialog(lblSpecAgentDirectory.Text);
DialogResult result = browserDialog.ShowDialog(this);
if (result == DialogResult.OK)
Cursor = Cursors.WaitCursor;
Properties.Settings.Default.LastSpecAgentDirectory = browserDialog.SelectedPath;
Properties.Settings.Default.Save();
lblSpecAgentDirectory.Text = browserDialog.SelectedPath;
private void chkLoadChildFolders_CheckedChanged(object sender, EventArgs e)
private void QtxStxConverterView_FormClosing(object sender, FormClosingEventArgs e)
private void btnChangeWordDirectory_Click(object sender, EventArgs e)
var browserDialog = GetFolderBrowserDialog(lblWordDirectory.Text);
DialogResult result = browserDialog.ShowDialog(this);
if (result == DialogResult.OK)
Cursor = Cursors.WaitCursor;
Properties.Settings.Default.LastWordDirectory = browserDialog.SelectedPath;
Properties.Settings.Default.Save();
lblWordDirectory.Text = browserDialog.SelectedPath;
private void btnLoadTestPop_Click(object sender, EventArgs e)
var loadTestPop = new LoadTestView();
loadTestPop.ShowDialog(this);
if (loadTestPop.DialogResult == DialogResult.OK)
var worker = new BackgroundWorker();
worker.DoWork += (o, ex) =>
using (var sessionFactory = _container.Resolve<ISessionFactory>())
using (var session = _container.Resolve<ISession>())
var generator = new EntityConverterTestInfoGenerator(session, sessionFactory);
if (loadTestPop.cbPopulateOfficeMaster.Checked)
generator.PopulateOfficeMasterProject(
Convert.ToInt32(loadTestPop.tbOMSectionsToInclude.Text),
Convert.ToInt32(loadTestPop.tbOMCustomSections.Text),
loadTestPop.cbOMAutoPublish.Checked,
loadTestPop.cbOMExcludeSections.Checked,
loadTestPop.cbOMVaryPublish.Checked);
if (loadTestPop.cbPopulateProjects.Checked)
generator.CreateTestProjects(
Convert.ToInt32(loadTestPop.tbProjectToInclude.Text),
Convert.ToInt32(loadTestPop.tbProjectSectionMin.Text),
Convert.ToInt32(loadTestPop.tbprojectSectionMax.Text),
Convert.ToInt32(loadTestPop.tbProjectCustomSections.Text),
loadTestPop.cbProjectUseOM.Checked,
Convert.ToInt32(loadTestPop.tbParticipantsMin.Text),
Convert.ToInt32(loadTestPop.tbParticipantsMax.Text),
loadTestPop.cbProjectUseOM.Checked);
worker.RunWorkerCompleted += (o, ex) =>
MessageBox.Show("Load test population complete.");