using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;
using System.Xml;
using System.Xml.Serialization;
using QC.CorpTest.Libraries.ExcelLibrary;
using QC.CTDS.DM.ApplicationsManager;
using QC.CTDS.DM.DataStructures.LimitDescriptorDataStructure;
using QC.GlobalVariableManager;
using QC.QSPR;
using QC.QsprShared.Config;
using QC.QsprShared.Dialogs;
using QC.QsprShared.GlobalData;
using QC.QsprShared.Trace;
using QC.QsprShared.Utilities;
using QC.QsprTestObjects;
using QC.QsprTestObjects.Loops;
using QC.QsprTestObjects.Parameters;
using QC.QsprTestObjects.Registry;
using QC.QsprTestObjects.TestConditions;
using QC.QsprTestObjects.Tests.Base;
using QC.QsprTestObjects.Tests.DotNet;
using QC.QsprTestObjects.Tests.Hive;
using QC.QsprTestObjects.Tests.LabVIEW;
using QC.QsprTestObjects.Tests.Script;
using QC.QsprTestObjects.Tests.TestCase;
using QC.QTMApplication.Application.TreeView;
using QC.QTMApplication.Dialogs;
using QC.QTMApplication.Utilities;
using QC.QTMApplication.Validation;
using QC.QTMInterface;
using QC.QTMInterface.Business_Objects;
using QC.QTMSecurity;
using QC.QTMTargetHelper;
using QsprMiscShared.Utilities;

namespace QC.QTMApplication;

public partial class TTDWpfTreeView : System.Windows.Controls.UserControl, INotifyPropertyChanged, IComponentConnector, IStyleConnector
{
	private enum NodeState
	{
		Passed,
		Failed,
		Aborted,
		Stopped,
		Running,
		Exception
	}

	public delegate void UpdateWindowNameHandler(string name);

	public delegate void AddRecentFileHandler(string filename);

	public delegate void LinkedFileFoundEventHandler(object sender, string LinkedFileName, string linkedConfigFile);

	private delegate void OnGetTestCasesDelegate(object sender, GetTestCasesEventArgs e);

	public delegate void TestTreeFocusChanged(bool focused);

	public const string COMPRESSED_TREE_FILE_EXTENSION = ".cxtt";

	public const string TREE_FILE_EXTENSION = ".xtt";

	public const string TEMP_TREE_NAME = "qtmTemp";

	public const string DOCKING_TTD_CONFIG_FNAME = "DockingTTD.config";

	public const string CUSTOM_DOCKING_TTD_CONFIG_FNAME = "CustomDockingTTD.config";

	public const string TEST_TREE_DIALOG_FILTER = "QSPR test tree files (*.cxtt, *.xtt)|*.cxtt;*.xtt|All files (*.*)|*.*";

	private const string PARAMETER_VIEW_NAME = "Parameters";

	private const int DEFAULT_PARAM_TAB_WIDTH = 100;

	private const string CTSTEST = "CTSTest";

	private const string ROOT = "ROOT";

	private const string REGISTRY = "Registry";

	private const string FOLDER = "FOLDER";

	private const string SCRIPT = "QC.QTMApplication.QTMScripts";

	private const string UTIL = "Util";

	private const string THISPC = "This PC";

	private const string PATH_SEPARATOR = ".";

	private const string DEFAULT_FOLDERNAME = "Folder";

	private const int ENQUEUE_TEST = 1;

	private const int DEQUEUE_TEST = 0;

	private const string CLIPBOARD_MUTEX_NAME = "TestTreeClipboardMutexName";

	private const string ROOT_IMAGE_URI = "/QSPR;component/Icons/Root.png";

	private const string FOLDER_IMAGE_URI = "/QSPR;component/Icons/folder-closed.png";

	private const string FOLDER_EXPANDED_IMAGE_URI = "/QSPR;component/Icons/folder-open.png";

	internal const string TESTCASE_IMAGE_URI = "/QSPR;component/Icons/TestTreeTestCase.png";

	private const string TEST_IMAGE_URI = "/QSPR;component/Icons/TestTreeTest.png";

	private const string TEST_EXCEPTION_IMAGE_URI = "/QSPR;component/Icons/abort.png";

	private const string QUEUED_IMAGE_URI = "/QSPR;component/Icons/queue.png";

	private const string RUNNING_IMAGE_URI = "/QSPR;component/Icons/running.png";

	private const string PASSED_IMAGE_URI = "/QSPR;component/Icons/passed.png";

	private const string PASSFAILED_IMAGE_URI = "/QSPR;component/Icons/pass-fail.png";

	private const string FAILED_IMAGE_URI = "/QSPR;component/Icons/failed.png";

	private const string BOOKKEEPFAIL_IMAGE_URI = "/QSPR;component/Icons/bookkeepfail.png";

	private const string SKIPPED_IMAGE_URI = "/QSPR;component/Icons/skip.png";

	private const string LOOP_IMAGE_URI = "/QSPR;component/Icons/loop.png";

	private const string COMMENTS_IMAGE_URI = "/QSPR;component/Icons/Comments.png";

	private const string ENABLE_BREAK_POINT_IMAGE_URI = "/QSPR;component/Icons/breakPoint.png";

	private const string DISABLE_BREAK_POINT_IMAGE_URI = "/QSPR;component/Icons/DisableBreakPoint.png";

	private const string LOGGING_DISABLED_IMAGE_URI = "/QSPR;component/Icons/TestTreeLoggingDisabled.png";

	private const string LOGGING_ENABLED_IMAGE_URI = "/QSPR;component/Icons/TestTreeLoggingEnabled.png";

	private const string TOOL_TEST_IMAGE_URI = "/QSPR;component/Icons/TestTreeToolTest.png";

	private const string SETUP_FOLDER_IMAGE_URI = "/QSPR;component/Icons/SetupFolder.png";

	private const string CLEANUP_FOLDER_IMAGE_URI = "/QSPR;component/Icons/CleanupFolder.png";

	private const string IGNORE_SESSION_IMAGE_URI = "/QSPR;component/Icons/IgnoreSessions.png";

	private const string STOP_ON_ERROR_IMAGE_URI = "/QSPR;component/Icons/TestTreeStopOnError.png";

	private const string TREE_MUST_RUN_IMAGE_URI = "/QSPR;component/Icons/TestTreeMustRun.png";

	private const string FOLDER_MUST_RUN_IMAGE_URI = "/QSPR;component/Icons/TestTreeFolderMustRun.png";

	private const string BRANCH_ON_ERROR_IMAGE_URI = "/QSPR;component/Icons/TestTreeBranchOnError.png";

	private const string METADATA_IMAGE_URI = "/QSPR;component/Icons/TestTreeMetadata.png";

	private const string PRE_CONDITION_IMAGE_URI = "/QSPR;component/Icons/TestTreePreCondition.png";

	private const string POST_CONDITION_IMAGE_URI = "/QSPR;component/Icons/TestTreePostCondition.png";

	private const string BOOK_KEEPING_IMAGE_URI = "/QSPR;component/Icons/BookKeeping.png";

	private const string BREAK_CONDITION_IMAGE_URI = "/QSPR;component/Icons/TestTreeBreakCondition.png";

	private const string REGISTRATION_IMAGE_URI = "/QSPR;component/Icons/TestTreeRegistration.png";

	private const string ROOT_STOP_ON_FIRST_FAIL_IMAGE_URI = "/QSPR;component/Icons/Stop.png";

	private const string ROOT_PAUSE_ON_FAIL_IMAGE_URI = "/QSPR;component/Icons/Pause.png";

	private const string REGISTRY_TREE_NAMESPACE_IMAGE_URI = "/QSPR;component/Icons/RegistryNamespace.png";

	private const string REGISTRY_TREE_CLASS_IMAGE_URI = "/QSPR;component/Icons/RegistryClass.png";

	private const string REGISTRY_TREE_LOADED_DLL_IMAGE_URI = "/QSPR;component/Icons/RegistryTreeLoadedDll.png";

	private const string REGISTRY_TREE_UNLOADED_DLL_IMAGE_URI = "/QSPR;component/Icons/RegistryTreeUnloadedDll.png";

	private const string REGISTRY_TREE_LOADED_TEST_IMAGE_URI = "/QSPR;component/Icons/RegistryTreeLoadedTest.png";

	private const string REGISTRY_TREE_UNLOADED_TEST_IMAGE_URI = "/QSPR;component/Icons/RegistryTreeUnloadedTest.png";

	public string TEMP_FOLDER = System.Windows.Forms.Application.UserAppDataPath;

	private string CLIPBOARD_FILE = System.Windows.Forms.Application.UserAppDataPath + "\\tmp_qtmClipboard.xml";

	private string TEMP_TREE_FILE = System.Windows.Forms.Application.UserAppDataPath + "\\tmp_TreeTemp.xml";

	private static string TEMP_DECOMPRESS_TREE_FILE_TEMPLATE_NAME = System.Windows.Forms.Application.UserAppDataPath + "\\tmp_DecompressTree_";

	private bool _bLoadingTree;

	internal Scheduler _scheduler = new Scheduler();

	private BaseTest tempDragNode;

	private TreeViewItem tempDrag;

	protected TreeViewItem rootTreeViewItem;

	public UpdateWindowNameHandler UpdateWindowName;

	public AddRecentFileHandler AddRecentFile;

	private bool treeChanged;

	private bool _paramIsEditable;

	private bool isQSPR2Tree;

	private static string XMLTreeFileName = "";

	private ArrayList dListGlobal = new ArrayList();

	private bool treeChangedDataCollection;

	private TestCaseDragDrop _testCaseDragDrop;

	private TestPlanDragDrop _testPlanDragDrop;

	private TestTreeInfo TTInfo = new TestTreeInfo();

	private Mutex handleClipBoardMutex;

	private bool mutexWasCreated;

	protected WSpaceConfig wsc;

	private ArrayList CopiedNodes;

	private bool checkedSavePath;

	private double imageWidth = 16.0;

	private double imageHeight = 16.0;

	private Thickness treeItemMargin = new Thickness(0.0, 0.0, 0.0, 0.0);

	private BaseTest currBreakPointNode;

	private bool importingTrees;

	public bool bDragFromRegistry;

	protected Dictionary<string, ParamViewPlugIn> ParamPlugInsColl = new Dictionary<string, ParamViewPlugIn>();

	public Dictionary<string, TestCasesPlugin> TestCasesPluginsColl = new Dictionary<string, TestCasesPlugin>();

	protected MenuToolBarManager menuToolBarManager;

	private string currentTabInView = "Parameters";

	private bool paramPluginsLoaded;

	private bool nestedLinkChange;

	private bool linksUpdated;

	private int _testCasePluginsWaiting;

	private int _testCasesUpdatedCount;

	private TabItem selectedParamTab;

	private TestTreeSelectedNode currentTestTreeNodeStatus;

	private bool isDblClicked;

	private bool? nodeExpandedStateBeforeDoubleClick = null;

	private TreeViewItem lastTreeViewItemDragOver;

	private DateTime lastDragOverTime = DateTime.Now;

	public TestTreeFocusChanged OnTestTreeFocusChanged;

	public ArrayList TesterConfigurationList
	{
		get
		{
			return _scheduler.QTMData.TesterConfigurationList;
		}
		set
		{
			_scheduler.QTMData.TesterConfigurationList = value;
		}
	}

	private bool bLoadingTree
	{
		get
		{
			return _bLoadingTree;
		}
		set
		{
			_bLoadingTree = value;
		}
	}

	public RootTest Root
	{
		get
		{
			return _scheduler.RootFolder;
		}
		set
		{
			_scheduler.RootFolder = value;
			_scheduler.RootFolder.Scheduler = _scheduler;
		}
	}

	internal GlobalStatus GlobalStatus => _scheduler.GlobalStatus;

	public QTMRegistry RegistryRoot
	{
		get
		{
			if (_scheduler.Registry == null)
			{
				_scheduler.Registry = new QTMRegistry();
			}
			return _scheduler.Registry;
		}
		set
		{
			_scheduler.Registry = value;
		}
	}

	public bool TreeRegistered
	{
		get
		{
			if (Root.RootProperties.TreeID != -1)
			{
				return true;
			}
			return false;
		}
	}

	public bool DatabaseEnabled => Root.RootProperties.EnableDatabase;

	public bool TreeChanged
	{
		get
		{
			return treeChanged;
		}
		set
		{
			treeChanged = value;
			if (UpdateWindowName != null)
			{
				UpdateWindowName(Caption + " Tree ID: " + Root.RootProperties.TreeStringID);
			}
			if (Root.RootProperties.TreeType != QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan || !(Root.RootProperties is TestPlanProperties))
			{
				return;
			}
			_ = (Root.RootProperties as TestPlanProperties).Dirty;
			if (!bLoadingTree && value)
			{
				if (!_paramIsEditable)
				{
					(Root.RootProperties as TestPlanProperties).SetDirty();
				}
				if (string.IsNullOrWhiteSpace((Root.RootProperties as TestPlanProperties).TestPlanName))
				{
					_ = (Root.RootProperties as TestPlanProperties).TestName;
				}
				else
				{
					_ = (Root.RootProperties as TestPlanProperties).TestPlanName;
				}
			}
		}
	}

	public bool IsQSPR2Tree => isQSPR2Tree;

	public string Caption
	{
		get
		{
			string text = TreeDisplayName;
			if (TreeChanged)
			{
				text += " * ";
			}
			if (IsQSPR2Tree)
			{
				text += " [Compatibility Mode]";
			}
			return text;
		}
	}

	public bool IsTreeRegistered
	{
		get
		{
			try
			{
				if (Root.RootProperties.TreeID != -1)
				{
					return true;
				}
			}
			catch
			{
			}
			return false;
		}
	}

	public string XmlTreeName
	{
		get
		{
			return XMLTreeFileName;
		}
		set
		{
			XMLTreeFileName = value;
		}
	}

	public string TreeDisplayName
	{
		get
		{
			return GlobalStatus.TreeName;
		}
		set
		{
			GlobalStatus.TreeName = value;
		}
	}

	public string TreeName => GlobalStatus.TreeName;

	public bool RegistrationRequired
	{
		get
		{
			if (Root.RootProperties is TestPlanProperties)
			{
				return false;
			}
			bool flag = false;
			if (GlobalStatus.RegistrationStatus.TreeChanged)
			{
				flag = true;
			}
			else if (GlobalStatus.RegistrationStatus.LoopChanged)
			{
				flag = true;
			}
			else if (GlobalStatus.RegistrationStatus.RegistryChanged)
			{
				flag = true;
			}
			else if (GlobalStatus.RegistrationStatus.Synchronized)
			{
				flag = true;
			}
			if (Root.RootProperties.TreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.GoNoGo)
			{
				if (GlobalStatus.RegistrationStatus.LoopRowDeleted)
				{
					flag = true;
				}
				else if (GlobalStatus.RegistrationStatus.ParameterAttributeChanged)
				{
					flag = true;
				}
				else if (GlobalStatus.RegistrationStatus.LoopSelectionChanged)
				{
					flag = true;
				}
				else if (GlobalStatus.RegistrationStatus.LoopValueChanged)
				{
					flag = true;
				}
				else if (GlobalStatus.RegistrationStatus.TreeNodeDeleted)
				{
					flag = true;
				}
				else if (GlobalStatus.RegistrationStatus.TreeSelectionChanged)
				{
					flag = true;
				}
				if (Root.RootProperties.ForceRegistrationOnPlugInChange && GlobalStatus.RegistrationStatus.PluginDataChanged)
				{
					flag = true;
				}
				if (Root.RootProperties.ForceRegistrationOnLinkedTreeChange && GlobalStatus.RegistrationStatus.LinkedTreeChanged)
				{
					flag = true;
				}
			}
			if (flag && Root.Properties.NodeRID != -1)
			{
				return true;
			}
			return false;
		}
	}

	public bool TreeChangedDataCollection
	{
		get
		{
			return treeChangedDataCollection;
		}
		set
		{
			treeChangedDataCollection = value;
		}
	}

	public KeyActionCommand TestTreeContextMenuKeyActionCommand { get; private set; }

	public bool TestCasesLoaded => TestCasesPlugin != null;

	public Dictionary<string, BaseTest> TestNodesColl { get; set; }

	public ObservableCollection<BaseTest> Tests { get; set; }

	public double ImageWidth
	{
		get
		{
			return imageWidth;
		}
		set
		{
			imageWidth = value;
			RaiseOnPropertyChangedEvent("ImageWidth");
		}
	}

	public double ImageHeight
	{
		get
		{
			return imageHeight;
		}
		set
		{
			imageHeight = value;
			RaiseOnPropertyChangedEvent("ImageHeight");
		}
	}

	public Thickness TreeItemMargin
	{
		get
		{
			return treeItemMargin;
		}
		set
		{
			treeItemMargin = value;
			RaiseOnPropertyChangedEvent("TreeItemMargin");
		}
	}

	public TestCasesPlugin TestCasesPlugin
	{
		get
		{
			using (Dictionary<string, TestCasesPlugin>.ValueCollection.Enumerator enumerator = TestCasesPluginsColl.Values.GetEnumerator())
			{
				if (enumerator.MoveNext())
				{
					return enumerator.Current;
				}
			}
			return null;
		}
	}

	public ObservableCollection<QTMRegistry> Registries { get; set; }

	internal TestTreeSelectionManager TestTreeSelectionManager { get; set; }

	internal TestTreeEditor TestTreeEditor { get; set; }

	protected RegistryTreeEditor RegistryTreeEditor { get; set; }

	protected Dictionary<string, object> RegistryNodesColl { get; set; }

	public bool ParamPluginsLoaded
	{
		get
		{
			return paramPluginsLoaded;
		}
		set
		{
			if (paramPluginsLoaded != value)
			{
				paramPluginsLoaded = value;
				RaiseOnPropertyChangedEvent("ParamPluginsLoaded");
			}
		}
	}

	private TestTreeSelectedNode CurrentTestTreeNodeStatus
	{
		get
		{
			return currentTestTreeNodeStatus;
		}
		set
		{
			currentTestTreeNodeStatus = value;
			GlobalStatus.TestTreeNodeStatus = value;
			UpdateToolBar(value);
		}
	}

	public event PropertyChangedEventHandler PropertyChanged;

	public event LinkedFileFoundEventHandler LinkFileFound;

	protected void RaiseOnPropertyChangedEvent(string propertyName)
	{
		if (this.PropertyChanged != null)
		{
			this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}
	}

	public TTDWpfTreeView()
	{
		InitializeComponent();
		base.DataContext = this;
		TestTreeContextMenuKeyActionCommand = new KeyActionCommand(TestTreeKeyCommand_Execute, TestTreeKeyCommand_CanExecute);
		System.Windows.Controls.ContextMenu contextMenu = testTreeView.Resources["testContextMenu"] as System.Windows.Controls.ContextMenu;
		testTreeView.ContextMenu = contextMenu;
		menuToolBarManager = new MenuToolBarManager(contextMenu, null, this);
		Tests = new ObservableCollection<BaseTest>();
		Registries = new ObservableCollection<QTMRegistry>();
		RegistryNodesColl = new Dictionary<string, object>();
		TestNodesColl = new Dictionary<string, BaseTest>();
		InitTree();
		_testCaseDragDrop = new TestCaseDragDrop(this);
		_testPlanDragDrop = new TestPlanDragDrop(this);
		QSecurity.UserAccessLevelChanged += QSecurity_UserAccessLevelChanged;
		TargetHelper.TargetMessageReceived += TargetHelper_TargetMessageReceived;
		GlobalStatus.RegistrationStatus.RegistrationChanged = RegistrationChanged;
		CreateCopyMutex();
	}

	private void RegistrationChanged()
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append(Root.Properties.RealName);
		stringBuilder.Append(Environment.NewLine + Environment.NewLine + Root.Properties.TestName);
		foreach (BaseTest test in Root.TestList)
		{
			stringBuilder.Append(Environment.NewLine + " -- " + test.Properties.TestName);
		}
		stringBuilder.AppendLine(Environment.NewLine + "REGISTRATION INFORMATION");
		stringBuilder.AppendLine("   Tree Changed: " + GlobalStatus.RegistrationStatus.TreeChanged);
		stringBuilder.AppendLine("   Parameter Attribute Changed: " + GlobalStatus.RegistrationStatus.ParameterAttributeChanged);
		stringBuilder.AppendLine("   Tree Node Deleted: " + GlobalStatus.RegistrationStatus.TreeNodeDeleted);
		stringBuilder.AppendLine("   Tree Selection Changed: " + GlobalStatus.RegistrationStatus.TreeSelectionChanged);
		stringBuilder.AppendLine("   Registry Changed: " + GlobalStatus.RegistrationStatus.RegistryChanged);
		stringBuilder.AppendLine("   Tree Syncronized: " + GlobalStatus.RegistrationStatus.Synchronized);
		stringBuilder.AppendLine("   Plugin Data Changed: " + GlobalStatus.RegistrationStatus.PluginDataChanged);
		stringBuilder.AppendLine("   Linked Tree Data Changed: " + GlobalStatus.RegistrationStatus.LinkedTreeChanged);
		stringBuilder.AppendLine("   Loop Changed: " + GlobalStatus.RegistrationStatus.LoopChanged);
		stringBuilder.AppendLine("   Loop Selection Changed: " + GlobalStatus.RegistrationStatus.LoopSelectionChanged);
		stringBuilder.AppendLine("   Loop Row Deleted: " + GlobalStatus.RegistrationStatus.LoopRowDeleted);
		stringBuilder.AppendLine("   Loop Value Changed: " + GlobalStatus.RegistrationStatus.LoopValueChanged);
		stringBuilder.AppendLine("   Tree Config Changed: " + GlobalStatus.RegistrationStatus.TreeConfigChanged);
		Root.TestUserInterfaceProperties.ToolTipText = stringBuilder.ToString();
		if (!_scheduler.QTMData.WConfig.ShowToolTips)
		{
			Root.TestUserInterfaceProperties.ToolTipVisibility = Visibility.Hidden;
		}
		else
		{
			Root.TestUserInterfaceProperties.ToolTipVisibility = Visibility.Visible;
		}
	}

	private void TestTreeKeyCommand_Execute(object parameter)
	{
		string key = parameter as string;
		TestTreeContextMenuMessages(key);
	}

	private bool TestTreeKeyCommand_CanExecute(object parameter)
	{
		return true;
	}

	private void RegistryTreeKeyCommand_Execute(object parameter)
	{
		string key = parameter as string;
		RegistryTreeContextMenuMessages(key);
	}

	private bool RegistryTreeKeyCommand_CanExecute(object parameter)
	{
		return true;
	}

	private void RegistryTreeContextMenuMessages(string key)
	{
		if (!QSecurity.IsTechnician)
		{
			return;
		}
		switch (key)
		{
		case "Add CTS DLL":
			AddContainer(QC.QsprTestObjects.Tests.Base.QTMTestTypes.CTSTest, null);
			break;
		case "Add SUITE DLL":
			AddContainer(QC.QsprTestObjects.Tests.Base.QTMTestTypes.HiveTest, null);
			break;
		case "Add Dot Net DLL":
			AddContainer(QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTest, null);
			break;
		case "Add Script":
			AddContainer(QC.QsprTestObjects.Tests.Base.QTMTestTypes.ScriptTest, null);
			break;
		case "Add LabView VI":
			AddContainer(QC.QsprTestObjects.Tests.Base.QTMTestTypes.LabVIEWTest, null);
			break;
		case "Collapse All":
			CollapseExpandAll(collapse: true);
			break;
		case "Expand All":
			CollapseExpandAll(collapse: false);
			break;
		case "DLL Path(s)":
		{
			DllPaths dllPaths = new DllPaths(_scheduler.QTMData.WConfig);
			if (dllPaths.ShowDialog() != DialogResult.OK)
			{
			}
			break;
		}
		case "Sort":
			SortLibraryTree();
			break;
		case "Load":
			LoadContainerMenu();
			break;
		case "UnLoad":
			UnloadContainerMenu();
			break;
		case "Open File Path":
			OpenScriptPath();
			break;
		case "Delete":
			DeleteContainer();
			break;
		case "Rename":
			RenameContainer();
			break;
		case "Container Options":
			ContainerOptions();
			break;
		case "Add Target":
			break;
		}
	}

	private void SortLibraryTree()
	{
		foreach (QTMTarget item in RegistryRoot.Target)
		{
			List<QTMTestContainer> list = item.TestContainers.OrderBy((QTMTestContainer t) => t.Name).ToList();
			item.TestContainers.Clear();
			foreach (QTMTestContainer item2 in list)
			{
				item.TestContainers.Add(item2);
			}
		}
	}

	private bool ContainerOptions()
	{
		try
		{
			if (treeRegistry.SelectedItem != null && treeRegistry.SelectedItem is QTMTestContainer)
			{
				QTMTestContainer qTMTestContainer = (QTMTestContainer)treeRegistry.SelectedItem;
				qTMTestContainer.Options();
				UpdateContainerTestList(qTMTestContainer);
			}
			return true;
		}
		catch
		{
		}
		return false;
	}

	private void UpdateContainerTestList(QTMTestContainer container)
	{
		try
		{
			AddTestNodesToRegistryTree(container);
		}
		catch
		{
		}
	}

	public void RenameContainer()
	{
		TraceMessage.Write(ToString(), "RenameDLL", TraceMessageType.Trace);
		try
		{
			if (treeRegistry.SelectedItem != null && treeRegistry.SelectedItem is QTMTestContainer)
			{
				QTMTestContainer qTMTestContainer = (QTMTestContainer)treeRegistry.SelectedItem;
				if (!qTMTestContainer.Loaded)
				{
					RegistryTreeEditor.BeginContainerNameEdit(qTMTestContainer);
				}
				else
				{
					AppMessageDialog.Show("UnLoad before renaming.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Information);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "RenameDLL " + ex.Message, TraceMessageType.Exception);
		}
	}

	public bool DeleteContainer()
	{
		try
		{
			if (treeRegistry.SelectedItem != null && treeRegistry.SelectedItem is QTMTestContainer)
			{
				QTMTestContainer qTMTestContainer = (QTMTestContainer)treeRegistry.SelectedItem;
				DialogResult dialogResult = AppMessageDialog.Show(qTMTestContainer.Name + " will be deleted from the QSPR Registry", "QSPR - Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, DialogResult.OK, MessageDialogType.Warning);
				if (dialogResult == DialogResult.OK)
				{
					if (qTMTestContainer.Loaded)
					{
						UnloadContainer(qTMTestContainer);
					}
					RegistryRoot.GetTarget(qTMTestContainer.TargetName).DeleteTestContainer(qTMTestContainer.Name);
					TreeChanged = true;
					GlobalStatus.RegistrationStatus.RegistryChanged = true;
					return true;
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "DeleteDll " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void OpenScriptPath()
	{
		string selectedScriptPath = GetSelectedScriptPath();
		if (!string.IsNullOrEmpty(selectedScriptPath))
		{
			selectedScriptPath = selectedScriptPath.Substring(0, selectedScriptPath.LastIndexOf("\\"));
			Process.Start(selectedScriptPath);
		}
	}

	private string GetSelectedScriptPath()
	{
		if (treeRegistry.SelectedItem != null && treeRegistry.SelectedItem is QTMTestContainer)
		{
			QTMTestContainer qTMTestContainer = treeRegistry.SelectedItem as QTMTestContainer;
			if (File.Exists(qTMTestContainer.Name))
			{
				return qTMTestContainer.Name;
			}
		}
		return string.Empty;
	}

	private bool LoadContainerMenu()
	{
		TraceMessage.Write(ToString(), "LoadMenuDll", TraceMessageType.Trace);
		try
		{
			if (treeRegistry.SelectedItem != null && treeRegistry.SelectedItem is QTMTestContainer)
			{
				QTMTestContainer qTMTestContainer = (QTMTestContainer)treeRegistry.SelectedItem;
				if (!qTMTestContainer.Expanded)
				{
					RegistryTreeBrowser.ExpandAll(qTMTestContainer);
				}
				if (!qTMTestContainer.Loaded)
				{
					if (qTMTestContainer.ContainerType == QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTestEx)
					{
						DialogResult dialogResult = AppMessageDialog.Show("Do you still want to load it as exclusive ?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Question, DialogResult.Yes, MessageDialogType.Warning);
						if (dialogResult == DialogResult.No)
						{
							qTMTestContainer.ContainerType = QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTest;
						}
					}
					LoadContainer(qTMTestContainer, newContainer: false);
					GlobalStatus.RegistryNodeStatus = RegistrySelectedNode.DllLoadedNode;
					return true;
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "LoadContainerMenu " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private bool UnloadContainerMenu()
	{
		TraceMessage.Write(ToString(), "UnloadMenuDll", TraceMessageType.Trace);
		try
		{
			if (treeRegistry.SelectedItem != null && treeRegistry.SelectedItem is QTMTestContainer)
			{
				QTMTestContainer qTMTestContainer = (QTMTestContainer)treeRegistry.SelectedItem;
				if (qTMTestContainer.Loaded)
				{
					UnloadContainer(qTMTestContainer);
					GlobalStatus.RegistryNodeStatus = RegistrySelectedNode.DllUnLoadedNode;
					return true;
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UnloadMenuDll " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void CollapseExpandAll(bool collapse)
	{
		try
		{
			if (Registries.Count <= 0)
			{
				return;
			}
			QTMRegistry qTMRegistry = Registries.FirstOrDefault();
			if (qTMRegistry == null)
			{
				return;
			}
			QTMTarget qTMTarget = qTMRegistry.Target.FirstOrDefault((QTMTarget t) => t.Name == "This PC");
			if (qTMTarget == null)
			{
				return;
			}
			foreach (QTMTestContainer testContainer in qTMTarget.TestContainers)
			{
				if (collapse)
				{
					RegistryTreeBrowser.CollapseAll(testContainer);
				}
				else
				{
					RegistryTreeBrowser.ExpandAll(testContainer);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "CollapseExpandAll " + ex.Message, TraceMessageType.Trace);
		}
	}

	internal bool AddContainer(QC.QsprTestObjects.Tests.Base.QTMTestTypes testType, string[] containerNames)
	{
		TraceMessage.Write(ToString(), "AddContainer " + testType, TraceMessageType.Trace);
		try
		{
			if (containerNames != null && Registries.Count > 0)
			{
				QTMRegistry qTMRegistry = Registries[0];
				foreach (QTMTarget item in qTMRegistry.Target)
				{
					if (item is QTMThisPCTarget)
					{
						item.IsSelected = true;
						break;
					}
				}
			}
			if (treeRegistry.SelectedItem != null)
			{
				object selectedItem = treeRegistry.SelectedItem;
				if (selectedItem is QTMTarget)
				{
					string text = "";
					if (containerNames != null || ((QTMTarget)selectedItem).GetContainerNames(testType, out containerNames))
					{
						for (int i = 0; i < containerNames.Length; i++)
						{
							try
							{
								text = containerNames[i];
								string oldName = "";
								QTMTarget qTMTarget = (QTMTarget)selectedItem;
								if (TestContainerExists(qTMTarget, text, out oldName))
								{
									string containerStringName = QTMTestContainer.GetContainerStringName(testType);
									QTMTestContainer container = qTMTarget.GetContainer(oldName);
									if (container.Loaded && container.ContainerType == QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTest)
									{
										AppMessageDialog.Show(containerStringName + " is already present!\nDotNet DLLs cannot be unloaded and replaced. To replace the DLL, close and reopen QSPR.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
										return false;
									}
									DialogResult dialogResult = AppMessageDialog.Show(containerStringName + " already present! Do you want to replace the old " + containerStringName, "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Question, DialogResult.Yes, MessageDialogType.Warning);
									if (dialogResult != DialogResult.Yes)
									{
										return false;
									}
									if (container.Loaded)
									{
										UnloadContainer(container);
									}
									QTMTestContainer qTMTestContainer = container;
									qTMTarget.DeleteTestContainer(oldName);
									qTMTarget.AddTestContainer(text, testType);
									qTMTestContainer = qTMTarget.GetContainer(text);
									qTMTestContainer.Key = qTMTarget.Name + text;
									LoadContainer(qTMTestContainer, newContainer: true);
									TreeChanged = true;
									GlobalStatus.RegistrationStatus.RegistryChanged = true;
								}
								else
								{
									AddDLLToTarget(testType, text, qTMTarget);
								}
							}
							catch
							{
							}
						}
						return true;
					}
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "AddDll " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public void AddDLLToTarget(QC.QsprTestObjects.Tests.Base.QTMTestTypes testType, string strContainer, QTMTarget Target, bool tryToLoadDLL = true)
	{
		Target.Expanded = true;
		Target.AddTestContainer(strContainer, testType);
		QTMTestContainer container = Target.GetContainer(strContainer);
		container.Key = Target.Name + strContainer;
		RegistryNodesColl[container.Key] = container;
		if (tryToLoadDLL)
		{
			LoadContainer(container, newContainer: true);
		}
		container.Expanded = true;
		TreeChanged = true;
		GlobalStatus.RegistrationStatus.RegistryChanged = true;
	}

	public void LoadContainer(QTMTestContainer containerNode, bool newContainer)
	{
		TraceMessage.Write(ToString(), "LoadContainer " + containerNode.Name, TraceMessageType.Trace);
		try
		{
			containerNode.UserInterfaceProperties.FontColor = Colors.Red.ToString();
			containerNode.UserInterfaceProperties.FontStyle = FontStyles.Normal;
			containerNode.UserInterfaceProperties.NodeImageUri = "/QSPR;component/Icons/RegistryTreeUnloadedDll.png";
			if (!RegistryNodesColl.ContainsKey(containerNode.Key))
			{
				RegistryNodesColl[containerNode.Key] = containerNode;
			}
			RegistryRoot.LoadContainer(containerNode, newContainer);
			containerNode.UserInterfaceProperties.UnloadSupported = containerNode.ContainerType != QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTest;
			containerNode.UserInterfaceProperties.ToolTipText = "";
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "LoadContainer " + ex.Message, TraceMessageType.Exception);
		}
	}

	private bool TestContainerExists(QTMTarget target, string newName, out string oldName)
	{
		oldName = "";
		try
		{
			FileInfo fileInfo = new FileInfo(newName);
			foreach (QTMTestContainer value in target.HashContainers.Values)
			{
				FileInfo fileInfo2 = new FileInfo(value.Name);
				if (fileInfo.Name.Trim().ToUpper() == fileInfo2.Name.Trim().ToUpper())
				{
					oldName = value.Name;
					return true;
				}
			}
		}
		catch
		{
		}
		return false;
	}

	private void UnloadContainer(QTMTestContainer containerNode)
	{
		try
		{
			bool flag = false;
			try
			{
				QTMTarget target = RegistryRoot.GetTarget(containerNode.TargetName);
				target.UnloadContainer(containerNode.ContainerType, containerNode.Name);
				containerNode.Reset();
				flag = false;
			}
			catch (Exception ex)
			{
				flag = true;
				AppMessageDialog.Show(ex.Message, "QSPR - Unload Failed", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			if (!flag)
			{
				containerNode.Loaded = false;
				ChangeNodeAppearancesToUnloaded(containerNode);
			}
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "UnloadContainer " + containerNode.TargetName + " " + ex2.Message, TraceMessageType.Exception);
		}
	}

	private void ChangeNodeAppearancesToUnloaded(object node)
	{
		if (node != null && node is QTMTestContainerItem && ((QTMTestContainerItem)node).Object is QTMTest)
		{
			QTMTestContainerItem qTMTestContainerItem = node as QTMTestContainerItem;
			qTMTestContainerItem.NodeImageUri = "/QSPR;component/Icons/RegistryTreeUnloadedTest.png";
			qTMTestContainerItem.FontColor = Colors.Gray.ToString();
			{
				foreach (QTMTestContainerItem item in qTMTestContainerItem.Items)
				{
					ChangeNodeAppearancesToUnloaded(item);
				}
				return;
			}
		}
		if (node != null && node is QTMTestContainer)
		{
			QTMTestContainer qTMTestContainer = node as QTMTestContainer;
			qTMTestContainer.UserInterfaceProperties.FontColor = Colors.Red.ToString();
			qTMTestContainer.UserInterfaceProperties.FontStyle = FontStyles.Normal;
			qTMTestContainer.UserInterfaceProperties.NodeImageUri = "/QSPR;component/Icons/RegistryTreeUnloadedDll.png";
			{
				foreach (QTMTestContainerItem item2 in qTMTestContainer.UserInterfaceProperties.Items)
				{
					ChangeNodeAppearancesToUnloaded(item2);
				}
				return;
			}
		}
		if (node == null || !(node is QTMTestContainerItem))
		{
			return;
		}
		QTMTestContainerItem qTMTestContainerItem2 = node as QTMTestContainerItem;
		qTMTestContainerItem2.FontColor = Colors.Gray.ToString();
		foreach (QTMTestContainerItem item3 in qTMTestContainerItem2.Items)
		{
			ChangeNodeAppearancesToUnloaded(item3);
		}
	}

	private void TestTreeContextMenuMessages(string key)
	{
		if (!QSecurity.IsTechnician)
		{
			return;
		}
		switch (key)
		{
		case "Run Test":
			RunDebugTests();
			break;
		case "Stop Test":
			StopTest();
			break;
		case "Import Test Tree":
			ImportTestTree(asLink: false, null, "", null, new ImportTestsInfo());
			break;
		case "Collapse All Tests":
			CollapseExpandAllTests(collapse: true);
			break;
		case "Expand All Tests":
			CollapseExpandAllTests(collapse: false);
			break;
		case "Clear All Comments":
			ClearAllComments();
			break;
		case "New Folder":
			AddFolder(Position.First);
			break;
		case "Loop Setup":
			LoopSetup();
			break;
		case "Cut":
			Cut();
			break;
		case "Copy":
			Copy();
			break;
		case "Paste":
			PasteNodes();
			break;
		case "Rename Test":
			if (!QSecurity.LockedQGroup && !(TestTreeSelectionManager.SelectedTests[0] is TestCaseTest))
			{
				TestTreeEditor.BeginTestNameEdit(TestTreeSelectionManager.SelectedTests[0]);
			}
			break;
		case "Create Test Case":
			SendSelectedNodesToTestCasePlugins(TestTreeSelectionManager.SelectedTests);
			break;
		case "Find In Database":
			FindTestCasesInDatabase(TestTreeSelectionManager.SelectedTests);
			break;
		case "Update Test Cases To Latest":
			UpdateTestCases(wasManualUpdateRequest: true, forceUpdate: false);
			break;
		case "Refresh Test Case":
			RevertSelectedTestCases();
			break;
		case "Switch To Draft":
			SwitchTestCaseToDraft();
			break;
		case "DEBUG - Generate TestCase Data":
			GenerateTestCaseData();
			break;
		case "Delete Test":
			DeleteNode();
			break;
		case "Show Parameters":
			ShowParameters();
			break;
		case "Synchronize":
			Synchronize(null);
			break;
		case "Refresh":
			RefreshTree();
			break;
		case "Text View...":
			ShowNodeDetails(TestTreeSelectionManager.SelectedTests[0]);
			break;
		case "Link Tree":
			ImportTestTree(asLink: true, null, "", null, new ImportTestsInfo());
			break;
		case "Unlink Tree":
			UnlinkTree();
			break;
		case "Re-link Tree":
			reLinkTree();
			break;
		case "Update Link(s)":
			UpdateLinkedTrees(TestTreeSelectionManager.SelectedTests[0], reLink: false, openTree: false);
			break;
		case "Toggle BreakPoint":
			ToggleBreakPoint();
			break;
		case "Toggle Logging":
			ToggleLogging();
			break;
		}
	}

	private void FindTestCasesInDatabase(ObservableCollection<BaseTest> selectedNodesCollection)
	{
		List<TestCaseMaster> testCaseList = GetTestCaseProxiesFromSelectedNodes();
		_testCasePluginsWaiting = 0;
		if (testCaseList.Count > 0)
		{
			foreach (TestCasesPlugin plugin in TestCasesPluginsColl.Values)
			{
				WaitCallback callBack = delegate
				{
					plugin.FindTestCasesInDatabase(testCaseList);
				};
				ThreadPool.QueueUserWorkItem(callBack);
				_testCasePluginsWaiting++;
			}
		}
		WaitForTestCasePluginsToFinishWork();
	}

	private void SwitchTestCaseToDraft()
	{
		foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
		{
			if (selectedTest is TestCaseTest)
			{
				(selectedTest as TestCaseTest).TestCaseProperties.Status = ApprovalStates.Draft;
				TrySetTestCaseDirty(selectedTest as TestCaseTest);
				selectedTest.Properties.IsSelected = false;
				selectedTest.Properties.IsSelected = true;
			}
		}
	}

	private bool reLinkTree()
	{
		TraceMessage.Write(ToString(), "Relink Tree", TraceMessageType.Trace);
		try
		{
			FolderTest linkRootFolder;
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
				if (baseTest is FolderTest)
				{
					FolderTest folderTest = (FolderTest)baseTest;
					if (folderTest.FolderProperties.LinkRoot && folderTest.FolderProperties.IsLinkActive == false)
					{
						DialogResult dialogResult = AppMessageDialog.Show("QSPR will Re-link to the latest tree version of '" + folderTest.FolderProperties.LinkLocation + "' on the file system.", "QSPR - Message Center", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Warning);
						if (dialogResult == DialogResult.OK)
						{
							folderTest.FolderProperties.LinkRoot = true;
							folderTest.FolderProperties.IsLinkActive = true;
							UpdateLinkedTrees(baseTest, reLink: true, openTree: false);
							MarkCurrLinkStatus((FolderTest)baseTest, isLink: true, true);
							RefreshTree(testTreeView);
							ResetTestTree(Root);
							RefreshTreeViewList(Root.TestList.ToList());
							return true;
						}
					}
					else if (folderTest.Properties.LinkNode && folderTest.Properties.IsLinkActive == true)
					{
						AppMessageDialog.Show("The selected folder is part of an already linked tree.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
					}
					else
					{
						bool flag = false;
						BaseTest baseTest2 = baseTest;
						while (baseTest2.Parent != null)
						{
							if (baseTest2.Parent.FolderProperties.LinkRoot && baseTest2.Parent.FolderProperties.IsLinkActive == false)
							{
								AppMessageDialog.Show("Please re-link at the root level of the linked tree.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
								flag = true;
								break;
							}
							baseTest2 = baseTest2.Parent;
						}
						if (!flag)
						{
							AppMessageDialog.Show("The selected folder was never linked.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
						}
					}
				}
				else
				{
					BaseTest baseTest3 = baseTest;
					linkRootFolder = baseTest3.GetLinkRootFolder();
					if (linkRootFolder == null)
					{
						goto IL_024f;
					}
					bool? isLinkActive = linkRootFolder.FolderProperties.IsLinkActive;
					if (!isLinkActive.GetValueOrDefault() || !isLinkActive.HasValue || !linkRootFolder.FolderProperties.LinkRoot)
					{
						goto IL_024f;
					}
					AppMessageDialog.Show("The selected test is part of an already linked tree..", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
				}
			}
			goto end_IL_0011;
			IL_024f:
			bool? isLinkActive2 = linkRootFolder.FolderProperties.IsLinkActive;
			if (!isLinkActive2.GetValueOrDefault() && isLinkActive2.HasValue && linkRootFolder.FolderProperties.LinkRoot)
			{
				AppMessageDialog.Show("Please re-link at the root level of the linked tree.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			else
			{
				AppMessageDialog.Show("Only unlinked folders can be re-linked.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			end_IL_0011:;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Relink Node " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void UpdateLinkedTrees(BaseTest pNode, bool reLink, bool openTree)
	{
		TraceMessage.Write(ToString(), "UpdateLinkedTrees", TraceMessageType.Trace);
		UpdateLinkedTrees(pNode, reLink, openTree, userChangedLink: false);
	}

	private void UpdateLinkedTrees(BaseTest pNode, bool reLink, bool openTree, bool userChangedLink)
	{
		TraceMessage.Write(ToString(), "UpdateLinkedTrees(UltraTreeNode pNode, bool reLink, bool openTree, bool userChangedLink)", TraceMessageType.Trace);
		nestedLinkChange = false;
		linksUpdated = false;
		if (pNode == null)
		{
			pNode = Root;
		}
		UpdateLinkNode(pNode, reLink);
		UpdateTreeLinks(pNode, reLink, repeat: false, openTree, userChangedLink);
	}

	private void UpdateTreeLinks(BaseTest pNode, bool reLink, bool repeat, bool openTree, bool userChangedLink)
	{
		TraceMessage.Write(ToString(), "UpdateTreeLinks", TraceMessageType.Trace);
		if (!(pNode is FolderTest))
		{
			return;
		}
		for (int i = 0; i < ((FolderTest)pNode).TestList.Count; i++)
		{
			BaseTest baseTest = ((FolderTest)pNode).TestList[i];
			if (baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count > 0)
			{
				UpdateTreeLinks(baseTest, reLink, repeat: true, openTree, userChangedLink);
			}
			UpdateLinkNode(baseTest, reLink);
			if (!repeat && !linksUpdated && baseTest is FolderTest && i == ((FolderTest)baseTest).TestList.Count - 1 && !openTree && !userChangedLink)
			{
				AppMessageDialog.Show("All Linked Tree(s) is/are up to date with their latest version on the file system.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Information);
			}
		}
	}

	private void UpdateLinkNode(BaseTest tNode, bool reLink)
	{
		TraceMessage.Write(ToString(), "UpdateLinkNode", TraceMessageType.Trace);
		if (!(tNode is FolderTest))
		{
			return;
		}
		FolderTest folderTest = (FolderTest)tNode;
		if (!folderTest.FolderProperties.LinkRoot || folderTest.FolderProperties.IsLinkActive != true)
		{
			return;
		}
		if (folderTest.FolderProperties.LinkLocation == TreeDisplayName)
		{
			linksUpdated = true;
			AppMessageDialog.Show("There exists a circular reference." + Environment.NewLine + "Please open the linked tree separately to resolve the issue if it is unintended.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.CritialError);
		}
		bool flag = false;
		string text = folderTest.FolderProperties.LinkLocation;
		if (text.ToLower().EndsWith(".cxtt"))
		{
			string decompressedFileName = GetDecompressedFileName(text);
			FileCompressionUtility.DecompressFile(text, decompressedFileName);
			text = decompressedFileName;
		}
		if (!string.IsNullOrEmpty(text) && Path.GetExtension(text) != ".xtt")
		{
			string text2 = Path.GetDirectoryName(text) + "\\" + Path.GetFileNameWithoutExtension(text) + ".xtt";
			if (File.Exists(text2))
			{
				DialogResult dialogResult = AppMessageDialog.Show("Newer version of the Linked Tree " + text2 + " is available. Do you want to update the link ?", "QTM - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Question, DialogResult.No, MessageDialogType.Warning);
				if (dialogResult == DialogResult.Yes)
				{
					folderTest.FolderProperties.LinkLocation = text2;
				}
				else
				{
					flag = true;
				}
			}
			else
			{
				flag = true;
			}
			if (text.ToLower().EndsWith(".cxtt"))
			{
				string decompressedFileName2 = GetDecompressedFileName(text);
				File.Delete(decompressedFileName2);
			}
		}
		byte[] array = new byte[0];
		string text3 = folderTest.FolderProperties.LinkLocation;
		if (flag)
		{
			if (!ConvertTree(text3, out var _, out var newTreeName, out var _))
			{
				AppMessageDialog.Show("Cannot update linked tree to current version.", DialogResult.OK, MessageDialogType.Error);
				return;
			}
			text3 = newTreeName;
		}
		string source = PathUtils.ConvertToAbsolute(TreeName, text3);
		array = LinkedTree.GetFileHash(source);
		if (array.Length == 0)
		{
			linksUpdated = true;
			DialogResult dialogResult2 = AppMessageDialog.Show("Can not find the linked tree xml file: " + Environment.NewLine + "'" + folderTest.FolderProperties.LinkLocation + "'" + Environment.NewLine + "Would you like to browse for the file ?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, DialogResult.No, MessageDialogType.Error);
			if (dialogResult2 == DialogResult.Yes)
			{
				OpenFileDialog openFileDialog = new OpenFileDialog();
				openFileDialog.Filter = "QSPR test tree files (*.cxtt, *.xtt)|*.cxtt;*.xtt|All files (*.*)|*.*";
				openFileDialog.FilterIndex = 1;
				openFileDialog.RestoreDirectory = true;
				dialogResult2 = openFileDialog.ShowDialog();
				if (dialogResult2 == DialogResult.OK)
				{
					folderTest.FolderProperties.LinkLocation = openFileDialog.FileName;
					array = LinkedTree.GetFileHash(folderTest.FolderProperties.LinkLocation);
				}
				else
				{
					AppMessageDialog.Show("Last updated version of the linked tree will be used.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Warning);
					array = folderTest.FolderProperties.LinkChecksum;
				}
			}
			else
			{
				dialogResult2 = AppMessageDialog.Show("Do you want to use the last updated version of the linked tree ?" + Environment.NewLine + "Caution: The linked tree will be deleted otherwise.", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Question, DialogResult.Yes, MessageDialogType.Warning);
				if (dialogResult2 != DialogResult.Yes)
				{
					if (tNode is FolderTest)
					{
						deleteLinkedFolder(((FolderTest)tNode).TestList.ToList());
					}
					if (tNode.Parent != null)
					{
						tNode.Parent.Remove(tNode);
					}
					RefreshTree(testTreeView);
					return;
				}
				array = folderTest.FolderProperties.LinkChecksum;
			}
		}
		if (!LinkedTree.AreChecksumsEqual(folderTest.FolderProperties.LinkChecksum, array))
		{
			LinkedTreeHasChanged(tNode, reLink, folderTest);
		}
		else if (Root.RootProperties.RegisteredLinkedTreeOnly && folderTest.FolderProperties.LinkTreeStringID == "-1")
		{
			AppMessageDialog.Show($"Linked tree {folderTest.FolderProperties.LinkLocation} must be a registered tree.  Please open the tree separately and register to resolve.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
		}
		else
		{
			try
			{
				LinkedTree.checkConfig(folderTest.FolderProperties);
			}
			catch (Exception)
			{
				LinkedTree.updateConfig(folderTest.FolderProperties.LinkLocation);
			}
		}
		if (this.LinkFileFound != null)
		{
			this.LinkFileFound(this, folderTest.FolderProperties.LinkLocation, folderTest.FolderProperties.ConfigLocation);
		}
	}

	private void LinkedTreeHasChanged(BaseTest tNode, bool reLink, FolderTest fTest)
	{
		linksUpdated = true;
		if (fTest.Properties.LinkNode && fTest.Properties.IsLinkActive == true)
		{
			if (!nestedLinkChange)
			{
				AppMessageDialog.Show("Nested Link has changed. Please open the linked tree separately if you wish to resolve.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Warning);
				nestedLinkChange = true;
			}
			return;
		}
		DialogResult dialogResult = DialogResult.Yes;
		if (!reLink)
		{
			dialogResult = (Root.RootProperties.AutoUpdateLinkedTree ? DialogResult.Yes : AppMessageDialog.Show("The Linked tree file '" + fTest.FolderProperties.LinkLocation + "' has changed on the file system." + Environment.NewLine + "Do you want QSPR to update the linked tree ?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, DialogResult.No, MessageDialogType.Warning));
		}
		if (dialogResult != DialogResult.Yes)
		{
			return;
		}
		if (!LinkedTree.CanLinkTree(fTest.FolderProperties.LinkLocation, Root.RootProperties.RegisteredLinkedTreeOnly))
		{
			AppMessageDialog.Show("The tree '" + fTest.FolderProperties.LinkLocation + "' has lost its registration and hence can not be updated." + Environment.NewLine + "QSPR will link back to the last updated version of the tree. Please open the tree separately and register to resolve.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			return;
		}
		FolderTest folderTest = null;
		if (dialogResult == DialogResult.Yes)
		{
			folderTest = new FolderTest(fTest.Properties.TestName);
			fTest.FolderProperties.Copy(folderTest.FolderProperties);
		}
		FolderTest parent = tNode.Parent;
		BaseTest baseTest = TestTreeBrowser.GetPreviousSibling(tNode);
		if (tNode is FolderTest)
		{
			deleteLinkedFolder(((FolderTest)tNode).TestList.ToList());
		}
		if (baseTest == null)
		{
			baseTest = parent;
			baseTest.Properties.Expanded = true;
		}
		else
		{
			baseTest.Properties.Expanded = false;
		}
		if (baseTest != null && baseTest != parent && baseTest.Parent != null)
		{
			try
			{
				while (baseTest.Parent != parent)
				{
					baseTest = baseTest.Parent;
					baseTest.Properties.Expanded = false;
				}
			}
			catch
			{
			}
		}
		ImportTestTree(asLink: true, baseTest, fTest.FolderProperties.LinkLocation, folderTest, new ImportTestsInfo());
		if (tNode.Parent != null && tNode.Parent.TestList.Contains(tNode))
		{
			tNode.Parent.TestList.Remove(tNode);
		}
		RefreshTree(testTreeView);
	}

	private void deleteLinkedFolder(List<BaseTest> NodeList)
	{
		GlobalStatus.RegistrationStatus.LinkedTreeChanged = true;
		TreeChanged = true;
		FolderTest folderTest = new FolderTest();
		ArrayList arrayList = new ArrayList();
		int index = 0;
		foreach (BaseTest Node in NodeList)
		{
			arrayList.Add(Node);
			folderTest = Node.Parent;
			index = folderTest.TestList.IndexOf(Node);
		}
		foreach (BaseTest item in arrayList)
		{
			FolderTest parent = item.Parent;
			parent.Remove(item);
		}
		SelectedNextNode(folderTest, index);
	}

	private bool UnlinkTree()
	{
		TraceMessage.Write(ToString(), "Unlink Tree", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
				if (baseTest is FolderTest)
				{
					FolderTest folderTest = (FolderTest)baseTest;
					if (folderTest.FolderProperties.LinkRoot)
					{
						bool? isLinkActive = folderTest.FolderProperties.IsLinkActive;
						if (isLinkActive.GetValueOrDefault() && isLinkActive.HasValue && !folderTest.Properties.LinkNode)
						{
							DialogResult dialogResult = AppMessageDialog.Show("Do you want QSPR to remember the link information for a possible re-linking in future?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Question, DialogResult.No, MessageDialogType.Warning);
							if (dialogResult == DialogResult.No)
							{
								removeLink(folderTest);
								MarkCurrLinkStatus(folderTest.TestList, isLink: false, null);
							}
							else
							{
								folderTest.FolderProperties.IsLinkActive = false;
								folderTest.FolderProperties.LinkChecksum = new byte[0];
								MarkCurrLinkStatus(folderTest.TestList, isLink: true, false);
							}
							RefreshTree(testTreeView);
							ResetTestTree(Root);
							RefreshTreeViewList(Root.TestList.ToList());
							return true;
						}
					}
					if (folderTest.Properties.LinkNode && folderTest.Properties.IsLinkActive == true)
					{
						AppMessageDialog.Show("Please unlink at the root level of the linked tree.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
					}
					else
					{
						AppMessageDialog.Show("The selected folder is not linked.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
					}
				}
				else if (baseTest.Properties.LinkNode && baseTest.Properties.IsLinkActive == true)
				{
					AppMessageDialog.Show("Please unlink at the root level of the linked tree.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
				}
				else
				{
					AppMessageDialog.Show("Only linked folders can be unlinked.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Unlink Node " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void MarkCurrLinkStatus(IEnumerable<BaseTest> list, bool isLink, bool? isLinkActive)
	{
		foreach (BaseTest item in list)
		{
			BaseTest baseTest = item;
			baseTest.Properties.LinkNode = isLink;
			baseTest.Properties.IsLinkActive = isLinkActive;
			if (item is FolderTest)
			{
				FolderTest folderTest = (FolderTest)item;
				folderTest.FolderProperties.LinkNode = isLink;
				folderTest.FolderProperties.IsLinkActive = isLinkActive;
				MarkCurrLinkStatus(folderTest.TestList, isLink, isLinkActive);
			}
		}
	}

	private void MarkCurrLinkStatus(BaseTest test, bool isLink, bool? isLinkActive)
	{
		test.Properties.LinkNode = isLink;
		test.Properties.IsLinkActive = isLinkActive;
		if (!(test is FolderTest))
		{
			return;
		}
		foreach (BaseTest test2 in ((FolderTest)test).TestList)
		{
			MarkCurrLinkStatus(test2, isLink, isLinkActive);
		}
	}

	private bool ShowNodeDetails(BaseTest selectedNode)
	{
		bool result = false;
		try
		{
			new NodeDetailsForm(selectedNode, _scheduler.QTMData.WConfig).ShowDialog();
			result = true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ShowNodeDetails " + ex.Message, TraceMessageType.Exception);
		}
		return result;
	}

	private bool ShowParameters()
	{
		TraceMessage.Write(ToString(), "ShowParameters", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				tabItemParameters.IsSelected = true;
				return true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ShowParameters " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	internal bool PasteNodes()
	{
		if (QSecurity.LockedQGroup)
		{
			return false;
		}
		TraceMessage.Write(ToString(), "Paste Nodes", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0 && TestTreeSelectionManager.SelectedTests[0].TestUserInterfaceProperties.IsInEditMode)
			{
				TestTreeSelectionManager.SelectedTests[0].Properties.TestName = System.Windows.Clipboard.GetText();
				TestTreeEditor.EndTestNameEdit(TestTreeSelectionManager.SelectedTests[0], commit: true);
			}
			else
			{
				GetFromClipboard();
				if (CopiedNodes != null && TestTreeSelectionManager.SelectedTests.Count == 1)
				{
					TreeChanged = true;
					BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
					bool flag = false;
					BaseTest baseTest2 = baseTest;
					if (baseTest2.Properties.LinkNode && baseTest2.Properties.IsLinkActive == true)
					{
						flag = true;
					}
					if (baseTest2 is FolderTest && ((FolderTest)baseTest2).FolderProperties.LinkRoot)
					{
						bool? isLinkActive = ((FolderTest)baseTest2).FolderProperties.IsLinkActive;
						if (isLinkActive.GetValueOrDefault() && isLinkActive.HasValue && baseTest.Properties.Expanded)
						{
							flag = true;
						}
					}
					if (flag)
					{
						AppMessageDialog.Show("Linked nodes cannot be modified.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
						return false;
					}
					foreach (BaseTest copiedNode in CopiedNodes)
					{
						if (copiedNode is FolderTest && ((FolderTest)copiedNode).FolderProperties.LinkLocation != "")
						{
							removeLink((FolderTest)copiedNode);
						}
						if (baseTest == Root)
						{
							if (!(copiedNode is FolderTest))
							{
								AppMessageDialog.Show(copiedNode.Properties.TestName + " cannot be pasted at the ROOT Level", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.UIWarning);
								return false;
							}
							if (((FolderTest)copiedNode).FolderProperties.Scenarios != null)
							{
								AppMessageDialog.Show("Folder " + copiedNode.Properties.TestName + " with loop cannot be added to ROOT Level", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.UIWarning);
								return false;
							}
						}
						else if (baseTest.Parent == Root && !baseTest.Properties.Expanded && !(copiedNode is FolderTest))
						{
							if (baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count > 0)
							{
								AppMessageDialog.Show("Only Folders can be added to the Root level", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.UIWarning);
								return false;
							}
						}
						else if (baseTest.Parent == Root && !baseTest.Properties.Expanded && copiedNode is FolderTest && baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count > 0 && ((FolderTest)copiedNode).FolderProperties.Scenarios != null)
						{
							AppMessageDialog.Show("Folder with Loop cannot be added to ROOT level", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.UIWarning);
							return false;
						}
					}
					if (!CheckDroppedNodeForLoopDescription(baseTest))
					{
						return false;
					}
					bLoadingTree = true;
					for (int i = 1; i <= CopiedNodes.Count; i++)
					{
						BaseTest copiedTest = (BaseTest)CopiedNodes[CopiedNodes.Count - i];
						FolderTest folderTest = new FolderTest("Temp");
						ConstructPasteTree(folderTest, copiedTest, Root, aslink: false);
						if (!AddNewNode(baseTest, folderTest.TestList[0], Position.First))
						{
							AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.UIWarning);
						}
					}
					bLoadingTree = false;
					if (CopiedNodes != null && CopiedNodes.Count > 0 && baseTest != null)
					{
						for (int j = 1; j <= CopiedNodes.Count; j++)
						{
							BaseTest test = (BaseTest)CopiedNodes[CopiedNodes.Count - j];
							CheckBranchOnTestIndex(test, baseTest);
						}
					}
					if (baseTest.Parent != null)
					{
						RefreshTreeViewList(baseTest.Parent.TestList.ToList());
					}
					else
					{
						RefreshTreeViewList(Root.TestList.ToList());
					}
					ResetTestTree(Root);
					ArrayList arrayList = new ArrayList();
					foreach (BaseTest copiedNode2 in CopiedNodes)
					{
						arrayList.Add(copiedNode2.Clone());
					}
					CopiedNodes = arrayList;
					if (baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count > 0)
					{
						UpdateCheckState(((FolderTest)baseTest).TestList[0]);
					}
					else
					{
						UpdateCheckState(baseTest);
					}
					return true;
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Paste Nodes " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public bool GetFromClipboard()
	{
		try
		{
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(HandleClipboard));
			if (mutexWasCreated && handleClipBoardMutex != null)
			{
				handleClipBoardMutex.WaitOne(10000);
				using (FileStream fileStream = new FileStream(CLIPBOARD_FILE, FileMode.Open, FileAccess.Read, FileShare.Read))
				{
					if (fileStream != null)
					{
						HandleClipboard handleClipboard = (HandleClipboard)xmlSerializer.Deserialize(fileStream);
						CopiedNodes = handleClipboard.CopiedNodes;
					}
				}
				handleClipBoardMutex.ReleaseMutex();
			}
			else
			{
				using FileStream fileStream2 = new FileStream(CLIPBOARD_FILE, FileMode.Open, FileAccess.Read, FileShare.Read);
				if (fileStream2 != null)
				{
					HandleClipboard handleClipboard2 = (HandleClipboard)xmlSerializer.Deserialize(fileStream2);
					CopiedNodes = handleClipboard2.CopiedNodes;
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("Failed to retrive data from clipboard " + ex.Message, DialogResult.OK, MessageDialogType.Exception);
			return false;
		}
	}

	private void removeLink(FolderTest fTest)
	{
		resetLinkProperties(fTest);
		foreach (BaseTest test in fTest.TestList)
		{
			if (test is FolderTest)
			{
				removeLink((FolderTest)test);
			}
		}
	}

	private void resetLinkProperties(FolderTest fTest)
	{
		fTest.FolderProperties.LinkRoot = false;
		fTest.FolderProperties.LinkChecksum = new byte[0];
		fTest.FolderProperties.ConfigLocation = "";
		fTest.FolderProperties.ConfigChecksum = new byte[0];
		fTest.FolderProperties.SaveAsNewSession = true;
		fTest.FolderProperties.LinkRegisteredMachine = "";
		fTest.FolderProperties.LinkSiteKey = "";
		fTest.FolderProperties.LinkSiteTreeID = "";
		fTest.FolderProperties.LinkTreeStringID = "";
		fTest.FolderProperties.LinkTreeID = -1L;
		fTest.FolderProperties.LinkLocation = "";
	}

	private bool CheckDroppedNodeForLoopDescription(BaseTest droppedNode)
	{
		try
		{
			if (droppedNode is FolderTest)
			{
				if (droppedNode.Properties.Expanded)
				{
					if (((FolderTest)droppedNode).FolderProperties.Scenarios != null && ((FolderTest)droppedNode).FolderProperties.HasValidLoopDescription())
					{
						DialogResult dialogResult = AppMessageDialog.Show("Loop Descriptions should be modified for " + droppedNode.Properties.TestName + ".\n               Do you want to continue?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning);
						if (dialogResult == DialogResult.No)
						{
							return false;
						}
					}
				}
				else if (droppedNode.Parent != null)
				{
					FolderTest parent = droppedNode.Parent;
					FolderTest folderTest = parent;
					if (folderTest.FolderProperties.Scenarios != null && folderTest.FolderProperties.HasValidLoopDescription())
					{
						DialogResult dialogResult2 = AppMessageDialog.Show("Loop Descriptions should be modified for " + folderTest.Properties.TestName + ".\n               Do you want to continue?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning);
						if (dialogResult2 == DialogResult.No)
						{
							return false;
						}
					}
				}
			}
			else if (droppedNode.Parent != null)
			{
				FolderTest parent2 = droppedNode.Parent;
				FolderTest folderTest2 = parent2;
				if (folderTest2.FolderProperties.Scenarios != null && folderTest2.FolderProperties.HasValidLoopDescription())
				{
					DialogResult dialogResult3 = AppMessageDialog.Show("Loop Descriptions should be modified for " + folderTest2.Properties.TestName + ".\n               Do you want to continue?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning);
					if (dialogResult3 == DialogResult.No)
					{
						return false;
					}
				}
			}
		}
		catch
		{
			return false;
		}
		return true;
	}

	public bool Cut()
	{
		TraceMessage.Write(ToString(), "Cut", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0 && TestTreeSelectionManager.SelectedTests[0] != Root)
			{
				if (TestTreeSelectionManager.SelectedTests[0].Properties.LinkNode && TestTreeSelectionManager.SelectedTests[0].Properties.IsLinkActive == true)
				{
					AppMessageDialog.Show("Linked nodes cannot be modified.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
					return false;
				}
				if (TestTreeSelectionManager.SelectedTests[0].Parent != null)
				{
					FolderTest parent = TestTreeSelectionManager.SelectedTests[0].Parent;
					if (parent.FolderProperties.Scenarios != null && parent.FolderProperties.HasValidLoopDescription())
					{
						DialogResult dialogResult = AppMessageDialog.Show("Loop Descriptions should be modified for " + parent.Properties.TestName + ".\n               Do you want to continue?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning);
						if (dialogResult == DialogResult.No)
						{
							return false;
						}
					}
				}
				FolderTest parent2 = TestTreeSelectionManager.SelectedTests[0].Parent;
				int index = parent2.TestList.IndexOf(TestTreeSelectionManager.SelectedTests[0]);
				TestTreeEditor.Cut(TestTreeSelectionManager.SelectedTests.ToList());
				StoreToClipboard();
				menuToolBarManager.SetEnabled("Paste", enabledValue: true);
				QSPRMainWindow.PasteEnabled = true;
				TreeChangedDataCollection = true;
				GlobalStatus.RegistrationStatus.TreeNodeDeleted = true;
				SelectedNextNode(parent2, index);
				TestNodesColl.Clear();
				RefreshTreeViewList(Tests.ToList());
				return true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Cut " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public bool Copy()
	{
		TraceMessage.Write(ToString(), "Copy", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				if (TestTreeSelectionManager.SelectedTests[0].TestUserInterfaceProperties.IsInEditMode)
				{
					TestTreeEditor.EndTestNameEdit(TestTreeSelectionManager.SelectedTests[0], commit: true);
					System.Windows.Clipboard.SetText(TestTreeSelectionManager.SelectedTests[0].Properties.TestName);
				}
				else if (TestTreeSelectionManager.SelectedTests[0] != Root)
				{
					List<BaseTest> tests = TestTreeSelectionManager.SelectedTests.OrderBy((BaseTest t) => t.UniqueTestPath).ToList();
					TestTreeEditor.Copy(tests);
					StoreToClipboard();
					menuToolBarManager.SetEnabled("Paste", !QSecurity.LockedQGroup);
					QSPRMainWindow.PasteEnabled = true;
					System.Windows.Clipboard.SetText(TestTreeSelectionManager.SelectedTests[0].Properties.TestName);
					return true;
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Copy " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	internal string CopyTest(string destinationFolder, string newName, string testIndex, string position)
	{
		if (destinationFolder != null && newName != null && !string.IsNullOrEmpty(testIndex) && !string.IsNullOrEmpty(position))
		{
			Position position2 = Position.NextSibling;
			if (position == "1")
			{
				position2 = Position.NextSibling;
			}
			else
			{
				if (!(position == "2"))
				{
					throw new Exception("Invalid position specified");
				}
				position2 = Position.First;
			}
			BaseTest baseTest = TestNodesColl[testIndex];
			if (baseTest != null && !(baseTest is RootTest))
			{
				TestTreeSelectionManager.ClearSelections();
				TestTreeSelectionManager.SelectTest(baseTest);
				Copy();
				BaseTest baseTest2 = null;
				if (Root.TestList.Count > 0)
				{
					TestTreeSelectionManager.ClearSelections();
					TestTreeSelectionManager.SelectTest(Root);
					if (destinationFolder == "")
					{
						if (baseTest is FolderTest)
						{
							baseTest2 = TestTreeSelectionManager.SelectedTests[0];
							return PasteTest(baseTest2, newName, position2);
						}
						throw new Exception("Tests cannot be copied under the Root folder.");
					}
					string regexMatchString = GetRegexMatchString(destinationFolder);
					baseTest2 = TestTreeSelectionManager.SelectedTests[0];
					if (SearchNodes(baseTest2, regexMatchString, WorkspaceConfig.SearchOptions.TestName, childrenOnly: false))
					{
						baseTest2 = TestTreeSelectionManager.SelectedTests[0];
						if (baseTest2 != null)
						{
							return PasteTest(baseTest2, newName, position2);
						}
					}
				}
				return null;
			}
			throw new Exception("A valid test node was not selected. Valid nodes are tests or folders, excluding the root node.");
		}
		throw new Exception("DestinationFolder, NewName, TestIndex, and/or position object(s) are not valid.");
	}

	private string PasteTest(BaseTest destinationNode, string newName, Position pos)
	{
		if (QSecurity.LockedQGroup)
		{
			return string.Empty;
		}
		if (destinationNode is RootTest)
		{
			pos = Position.First;
			destinationNode.Properties.Expanded = true;
		}
		else if (destinationNode is FolderTest)
		{
			if (pos == Position.NextSibling || pos == Position.PreviousSibling)
			{
				destinationNode.Properties.Expanded = false;
			}
			else
			{
				destinationNode.Properties.Expanded = true;
			}
		}
		else if (pos != Position.PreviousSibling)
		{
			pos = Position.NextSibling;
		}
		if (PasteNodes())
		{
			BaseTest baseTest = null;
			if (pos == Position.NextSibling)
			{
				baseTest = destinationNode.Parent.TestList[destinationNode.Parent.TestList.IndexOf(destinationNode) + 1];
			}
			else if (destinationNode is FolderTest && pos == Position.First)
			{
				baseTest = ((FolderTest)destinationNode).TestList[0];
			}
			if (baseTest != null)
			{
				if (newName != "")
				{
					baseTest.Properties.TestName = newName;
				}
				return baseTest.Index;
			}
		}
		return null;
	}

	private void RemoveLoopLinkTest(ArrayList cNodes)
	{
		TraceMessage.Write(ToString(), "RemoveLoopLinkTest", TraceMessageType.Trace);
		try
		{
			if (cNodes == null)
			{
				return;
			}
			foreach (BaseTest cNode in cNodes)
			{
				foreach (DeletedLink item in dListGlobal)
				{
					cNode.RemoveLoopLinkTest(item.ParentIndex);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "RemoveLoopLinkTest " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void StoreToClipboard()
	{
		try
		{
			if (mutexWasCreated && handleClipBoardMutex != null)
			{
				handleClipBoardMutex.WaitOne(10000);
				XmlSerializer xmlSerializer = new XmlSerializer(typeof(HandleClipboard));
				using (StreamWriter streamWriter = new StreamWriter(CLIPBOARD_FILE))
				{
					HandleClipboard o = new HandleClipboard(CopiedNodes);
					xmlSerializer.Serialize(streamWriter, o);
					streamWriter.Close();
				}
				handleClipBoardMutex.ReleaseMutex();
				return;
			}
			XmlSerializer xmlSerializer2 = new XmlSerializer(typeof(HandleClipboard));
			using StreamWriter streamWriter2 = new StreamWriter(CLIPBOARD_FILE);
			HandleClipboard o2 = new HandleClipboard(CopiedNodes);
			xmlSerializer2.Serialize(streamWriter2, o2);
			streamWriter2.Close();
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("Failed to save data to clipboard " + ex.Message, DialogResult.OK, MessageDialogType.Exception);
		}
	}

	internal bool ImportTestTree(bool asLink, BaseTest DroppedNode, string fName, FolderTest oldRootFolder, ImportTestsInfo importInfo)
	{
		TraceMessage.Write(ToString(), "ImportTestTree", TraceMessageType.Trace);
		bool flag = true;
		try
		{
			if (DroppedNode == null)
			{
				flag = false;
				if (TestTreeSelectionManager.SelectedTests.Count > 0)
				{
					DroppedNode = TestTreeSelectionManager.SelectedTests[0];
					bool flag2 = false;
					BaseTest baseTest = DroppedNode;
					if (baseTest.Properties.LinkNode && baseTest.Properties.IsLinkActive == true)
					{
						flag2 = true;
					}
					if (baseTest is FolderTest && ((FolderTest)baseTest).FolderProperties.LinkRoot)
					{
						bool? isLinkActive = ((FolderTest)baseTest).FolderProperties.IsLinkActive;
						if (isLinkActive.GetValueOrDefault() && isLinkActive.HasValue && DroppedNode.Properties.Expanded)
						{
							flag2 = true;
						}
					}
					if (flag2)
					{
						AppMessageDialog.Show("Linked nodes cannot be modified.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
						return false;
					}
				}
			}
			if (DroppedNode == null)
			{
				return false;
			}
			DialogResult dialogResult = DialogResult.OK;
			if (fName.Trim() == "")
			{
				OpenFileDialog openFileDialog = new OpenFileDialog();
				openFileDialog.Filter = "QSPR test tree files (*.cxtt, *.xtt)|*.cxtt;*.xtt|All files (*.*)|*.*";
				openFileDialog.FilterIndex = 1;
				openFileDialog.RestoreDirectory = true;
				dialogResult = openFileDialog.ShowDialog();
				fName = openFileDialog.FileName;
			}
			if (dialogResult == DialogResult.OK)
			{
				if (fName != "" && fName == XMLTreeFileName && asLink)
				{
					AppMessageDialog.Show("You can not link a tree to itself.", DialogResult.OK, MessageDialogType.CritialError);
					return false;
				}
				if (asLink && !LinkedTree.CanLinkTree(fName, Root.RootProperties.RegisteredLinkedTreeOnly))
				{
					AppMessageDialog.Show("'" + fName + "' is not a registered tree." + Environment.NewLine + "Please do the tree registration before linking. " + Environment.NewLine + "Or Change the Root property RegisteredLinkedTreeOnly to false ", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.CritialError);
					return false;
				}
				if (!ConvertTree(fName, out var oldTreeVersion, out var newTreeName, out var flag3))
				{
					AppMessageDialog.Show("Cannot update tree to current version.", DialogResult.OK, MessageDialogType.CritialError);
					return false;
				}
				string text = fName;
				fName = newTreeName;
				if (fName.ToLower().EndsWith(".cxtt"))
				{
					fName = GetDecompressedFileName(fName);
				}
				FileStream fileStream = null;
				XmlSerializer xmlSerializer = new XmlSerializer(typeof(SerializeComponents));
				fileStream = new FileStream(fName, FileMode.Open, FileAccess.Read, FileShare.Read);
				if (fileStream != null)
				{
					SerializeComponents serializeComponents = (SerializeComponents)xmlSerializer.Deserialize(fileStream);
					RootTest theRootTest = serializeComponents.theRootTest;
					theRootTest.Scheduler = Root.Scheduler;
					InitializeParent(theRootTest);
					QTMRegistry theRegistry = serializeComponents.theRegistry;
					theRegistry.scheduler = _scheduler;
					theRegistry.CreateHastable();
					fileStream.Close();
					foreach (QTMTarget value in theRegistry.Targets.Values)
					{
						if (RegistryRoot.AppendTarget(value))
						{
							GlobalStatus.RegistrationStatus.RegistryChanged = true;
						}
					}
					ConstructRegistryTree(RegistryRoot);
					RegistryTreeBrowser.Expand(RegistryRoot);
					if (theRootTest != null && theRootTest.TestList.Count > 0 && theRootTest.TestList[0] != null && theRootTest.TestList[0] is FolderTest)
					{
						bool expanded = DroppedNode.Properties.Expanded;
						HandleSynchronization(oldTreeVersion, isTreeChanged: true, (FolderTest)theRootTest.TestList[0]);
						if (oldTreeVersion == TreeConverter.QSPR_TREE_VERSION)
						{
							((FolderTest)theRootTest.TestList[0]).UpdateLoopValues();
						}
						DroppedNode.Properties.Expanded = expanded;
					}
					if (importInfo.TestList != null && importInfo.TestList.Count > 0 && !asLink)
					{
						List<BaseTest> list = new List<BaseTest>();
						foreach (string test in importInfo.TestList)
						{
							List<BaseTest> matchingTests = null;
							if (!FindMatchingTests(theRootTest, test, out matchingTests))
							{
								continue;
							}
							foreach (BaseTest item in matchingTests)
							{
								list.Add(item);
							}
						}
						if (!(DroppedNode is FolderTest) || importInfo.InsertPosition == Position.First)
						{
							list.Reverse();
						}
						foreach (BaseTest item2 in list)
						{
							item2.CreateParent(null);
							IncludeNodes(DroppedNode, item2, importInfo.InsertPosition, importInfo.DestinationName);
						}
					}
					else
					{
						theRootTest.CreateParent(null);
						if (asLink)
						{
							theRootTest.FolderProperties.LinkRoot = true;
							theRootTest.FolderProperties.IsLinkActive = true;
							theRootTest.Properties.CheckStateTest = CheckState.Checked;
							theRootTest.FolderProperties.LinkLocation = text.Trim();
							theRootTest.FolderProperties.LinkChecksum = LinkedTree.GetFileHash(text.Trim());
							theRootTest.FolderProperties.SaveAsNewSession = true;
							Hashtable registrationInfo = LinkedTree.getRegistrationInfo(fName);
							theRootTest.FolderProperties.LinkTreeStringID = GetHashValue(registrationInfo, "TreeStringID");
							theRootTest.FolderProperties.LinkRegisteredMachine = GetHashValue(registrationInfo, "RegisteredMachine");
							theRootTest.FolderProperties.LinkSiteKey = GetHashValue(registrationInfo, "SiteKey");
							theRootTest.FolderProperties.LinkSiteTreeID = GetHashValue(registrationInfo, "SiteTreeID");
							theRootTest.FolderProperties.LinkTreeID = Convert.ToInt64(GetHashValue(registrationInfo, "TreeID"));
							LinkedTree.updateConfig(fName);
							theRootTest.FolderProperties.ConfigLocation = LinkedTree.configFileName(fName);
							theRootTest.FolderProperties.ConfigChecksum = LinkedTree.configFileChecksum(fName);
							MakeLinkNodes(theRootTest);
						}
						IncludeNodes(DroppedNode, theRootTest, oldRootFolder, asLink, importInfo.InsertPosition, importInfo.RemoveRootFolder, flag3, importInfo.DestinationName);
						if (asLink && flag)
						{
							GlobalStatus.RegistrationStatus.TreeChanged = false;
						}
						if (asLink && this.LinkFileFound != null)
						{
							this.LinkFileFound(this, fName, theRootTest.FolderProperties.ConfigLocation);
						}
					}
					if (DroppedNode.Parent != null)
					{
						RefreshTreeViewList(DroppedNode.Parent.TestList.ToList());
					}
					else
					{
						RefreshTreeViewList(Root.TestList.ToList());
					}
					ResetTestTree(Root);
				}
			}
			return true;
		}
		catch (UnauthorizedAccessException ex)
		{
			AppMessageDialog.Show("ERROR: " + ex.Message + "\n****Hint: \n        Test Tree is readonly.\n        User not permitted.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Exception);
			return false;
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "ImportTestTree " + ex2.Message, TraceMessageType.Exception);
			return false;
		}
	}

	private void HandleSynchronization(double oldTreeVersion, bool isTreeChanged, FolderTest multiSelectTests)
	{
		TraceMessage.Write(ToString(), "HandleSynchronization, oldTreeVersion=" + oldTreeVersion, TraceMessageType.Trace);
		if (oldTreeVersion == 1.0)
		{
			AddNonQTMLoopLinks();
			TreeChanged = true;
		}
		else
		{
			if (!(oldTreeVersion < 13.0) && !_scheduler.QTMData.WConfig.AutoSyncTree)
			{
				return;
			}
			try
			{
				if (TreeConverter.QSPR_TREE_VERSION != oldTreeVersion && !_scheduler.QTMData.WConfig.AutoSyncTree)
				{
					return;
				}
				QTMTarget target = RegistryRoot.GetTarget("This PC");
				foreach (QTMTestContainer testContainer in target.TestContainers)
				{
					RegistryRoot.LoadContainer(testContainer, newContainer: false);
				}
				isTreeChanged = TreeChanged;
				Synchronize(multiSelectTests);
				SetRetryCount();
				UpdateBranchOnTestIndexForQSPR2Tree(Root, Root);
				ResetTestTree(Root);
				TreeChanged = isTreeChanged;
			}
			catch (Exception ex)
			{
				AppMessageDialog.Show("Synchronize the new tree failed. \n " + ex.Message + " \n Make sure to   Synchronize on the tree once before running the tree", "Warning", MessageBoxButtons.OK, DialogResult.OK, MessageDialogType.Exception);
			}
		}
	}

	private bool Synchronize(FolderTest multiSelectTests)
	{
		TraceMessage.Write(ToString(), "Synchronize", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				if (multiSelectTests == null)
				{
					multiSelectTests = new FolderTest("MultipleSelect");
					foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
					{
						ResetTestTree(selectedTest);
						multiSelectTests.AddDummyTest(selectedTest);
					}
				}
				_scheduler.SyncTests(multiSelectTests);
				TreeChanged = true;
				TreeChangedDataCollection = true;
				GlobalStatus.RegistrationStatus.Synchronized = true;
				BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
				ttdPropView.CurrentNode = baseTest;
				if (!(baseTest is FolderTest))
				{
					ttdParameterView.Parameters = baseTest.Properties.Parameters;
				}
				return true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Synchronize " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private bool SetRetryCount()
	{
		try
		{
			Root.ResetRetryCount();
			return true;
		}
		catch
		{
			return false;
		}
	}

	private void UpdateBranchOnTestIndexForQSPR2Tree(FolderTest rootFolder, RootTest treeRootFolder)
	{
		try
		{
			foreach (BaseTest test in rootFolder.TestList)
			{
				if (test.Properties.PostCondition != null && test.Properties.PostCondition.Action == PostConditionActions.Branch && test.Properties.PostCondition.BranchOnTestName != null)
				{
					if (test.Properties.PostCondition.BranchOnTestName.Length > 0)
					{
						if (test.Properties.PostCondition.BranchTestIndex == null || (test.Properties.PostCondition.BranchTestIndex != null && test.Properties.PostCondition.BranchTestIndex.Length == 0))
						{
							try
							{
								string branchOnTestName = test.Properties.PostCondition.BranchOnTestName;
								BaseTest baseTest = TestNodesColl[test.Index];
								TestTreeSelectionManager.ClearSelections();
								TestTreeSelectionManager.SelectTest(baseTest);
								if (SearchNodes(baseTest, branchOnTestName, WorkspaceConfig.SearchOptions.TestName, childrenOnly: false) && TestTreeSelectionManager.SelectedTests[0] != null && TestTreeSelectionManager.SelectedTests[0] != null)
								{
									BaseTest baseTest2 = TestTreeSelectionManager.SelectedTests[0];
									test.Properties.PostCondition.BranchTestIndex = baseTest2.Index;
								}
							}
							catch
							{
							}
						}
					}
					else if (test.Properties.StopOnError != 0)
					{
						test.Properties.PostCondition = null;
					}
				}
				if (test is FolderTest)
				{
					FolderTest rootFolder2 = (FolderTest)test;
					UpdateBranchOnTestIndexForQSPR2Tree(rootFolder2, treeRootFolder);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateBranchOnTestIndexForQSPR2Tree " + ex.Message, TraceMessageType.Exception);
		}
	}

	internal bool SearchNodes(BaseTest currentNode, string searchString, WorkspaceConfig.SearchOptions searchtype, bool childrenOnly)
	{
		bool result = false;
		try
		{
			while (currentNode != null)
			{
				if (currentNode is FolderTest && ((FolderTest)currentNode).TestList.Count > 0)
				{
					if (SearchANode(((FolderTest)currentNode).TestList[0], searchString, searchtype))
					{
						result = true;
						break;
					}
					if (SearchNodes(((FolderTest)currentNode).TestList[0], searchString, searchtype, childrenOnly: true))
					{
						result = true;
						break;
					}
				}
				BaseTest baseTest = TestTreeBrowser.GetNextSibling(currentNode);
				while (baseTest == null && !childrenOnly)
				{
					BaseTest parent;
					for (parent = currentNode.Parent; parent != null; parent = parent.Parent)
					{
						baseTest = TestTreeBrowser.GetNextSibling(parent);
						if (baseTest != null)
						{
							break;
						}
					}
					if (parent == null)
					{
						baseTest = parent;
						currentNode = parent;
						break;
					}
				}
				currentNode = baseTest;
				if (currentNode != null && SearchANode(currentNode, searchString, searchtype))
				{
					result = true;
					break;
				}
			}
		}
		catch (FormatException ex)
		{
			Console.WriteLine(ex.Message);
		}
		return result;
	}

	private bool SearchANode(BaseTest currentNode, string searchString, WorkspaceConfig.SearchOptions searchtype)
	{
		bool flag = false;
		string matchedParamName = "";
		string text = "";
		string searchString2 = searchString;
		switch (searchtype)
		{
		case WorkspaceConfig.SearchOptions.TestName:
			text = currentNode.Properties.TestName;
			MatchCase(ref text, ref searchString2);
			if (text.Contains(searchString2))
			{
				flag = true;
			}
			else if (GlobalStatus.AutomationMode && GlobalStatus.RegexSupportEnabled)
			{
				Regex regex = new Regex(searchString);
				text = TranslateTestPath(currentNode);
				if (regex.IsMatch(text))
				{
					flag = true;
				}
			}
			break;
		case WorkspaceConfig.SearchOptions.RealName:
			text = currentNode.Properties.RealName;
			MatchCase(ref text, ref searchString);
			if (text.Contains(searchString))
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.ParameterName:
			if (currentNode.Properties.Parameters.HasParameter(searchString, exactMatch: false, out matchedParamName))
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.RetryCount:
			if (currentNode.Properties.RetryCount > 0)
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.StopOnError:
			if (currentNode.Properties.StopOnError != 0)
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.Loop:
			if (currentNode.Properties.LoopSetup != string.Empty && currentNode.Properties.LoopSetup != "False")
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.BreakPoint:
			if (currentNode.Properties.BreakPoint == BreakPointTypes.Enable)
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.BranchOnError:
			if (currentNode.Properties.BranchOnError != string.Empty)
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.PreCondition:
			if (currentNode.Properties.PreCondition != null)
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.PostCondition:
			if (currentNode.Properties.PostCondition != null)
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.BookKeepingTest:
			if (currentNode.Properties.BookKeeping)
			{
				flag = true;
			}
			break;
		case WorkspaceConfig.SearchOptions.TestErrorCode:
			text = currentNode.Properties.TestErrorCode;
			if (text != null)
			{
				MatchCase(ref text, ref searchString);
				if (text.Contains(searchString))
				{
					flag = true;
				}
			}
			break;
		case WorkspaceConfig.SearchOptions.Comments:
			text = currentNode.Properties.Comment;
			if (text == null)
			{
				break;
			}
			if (string.IsNullOrEmpty(searchString))
			{
				flag = true;
				break;
			}
			MatchCase(ref text, ref searchString);
			if (text.Contains(searchString))
			{
				flag = true;
			}
			break;
		}
		if (flag)
		{
			TestTreeSelectionManager.SelectedTests.RemoveAt(0);
			TestTreeSelectionManager.SelectTest(currentNode);
			for (FolderTest parent = currentNode.Parent; parent != null; parent = parent.Parent)
			{
				parent.Properties.Expanded = true;
			}
			TestTreeBrowser.GetTreeItemFromTest(testTreeView, currentNode)?.BringIntoView();
			_ = 5;
			return true;
		}
		return false;
	}

	private void MatchCase(ref string propertyString, ref string searchString)
	{
		if (!_scheduler.QTMData.WConfig.SearchCaseMatch)
		{
			propertyString = propertyString.ToUpper();
			searchString = searchString.ToUpper();
		}
	}

	private string TranslateTestPath(BaseTest testNode, bool excludeRootFromPath = true)
	{
		string text = testNode.Properties.TestName;
		for (FolderTest folderTest = testNode.Parent; folderTest != null; folderTest = ((folderTest == Root) ? null : folderTest.Parent))
		{
			text = folderTest.Properties.TestName + "\\" + text;
		}
		if (excludeRootFromPath && !text.StartsWith("\\"))
		{
			text = "\\" + text;
		}
		return text;
	}

	private bool FindMatchingTests(RootTest rootTest, string testName, out List<BaseTest> matchingTests)
	{
		matchingTests = new List<BaseTest>();
		Stack<string> currentTreeStack = new Stack<string>();
		string regexMatchString = GetRegexMatchString(testName);
		FindMatches(rootTest, regexMatchString, ref matchingTests, currentTreeStack);
		return matchingTests.Count > 0;
	}

	internal string GetRegexMatchString(string name)
	{
		string text = name;
		if (GlobalStatus.RegexSupportEnabled)
		{
			if (text.StartsWith("^") && text.EndsWith("$"))
			{
				text = text.Remove(0, 1);
				return "\\\\" + text;
			}
			if (text.StartsWith("^"))
			{
				text = text.Remove(0, 1) + "(.*)";
			}
			text = ((!text.EndsWith("$")) ? (text + "$") : ("(.*)" + text));
			if (!text.StartsWith("\\\\"))
			{
				text = "\\\\" + text;
			}
		}
		return text;
	}

	private bool FindMatches(BaseTest testToSearchFrom, string testNameToMatch, ref List<BaseTest> matchingTests, Stack<string> currentTreeStack)
	{
		currentTreeStack.Push(testToSearchFrom.Properties.TestName);
		if (IsMatch(testToSearchFrom, testNameToMatch, currentTreeStack))
		{
			matchingTests.Add(testToSearchFrom);
			currentTreeStack.Pop();
			return true;
		}
		if (testToSearchFrom is FolderTest folderTest)
		{
			foreach (BaseTest test in folderTest.TestList)
			{
				FindMatches(test, testNameToMatch, ref matchingTests, currentTreeStack);
			}
		}
		currentTreeStack.Pop();
		return matchingTests.Count > 0;
	}

	private bool IsMatch(BaseTest testToCheck, string testNameToMatch, Stack<string> currentTreeStack)
	{
		if (GlobalStatus.AutomationMode && GlobalStatus.RegexSupportEnabled)
		{
			Regex regex = new Regex(testNameToMatch);
			string testPath = GetTestPath(testToCheck, currentTreeStack);
			return regex.IsMatch(testPath);
		}
		return testToCheck.Properties.TestName == testNameToMatch;
	}

	private string GetTestPath(BaseTest testToCheck, Stack<string> treeNames)
	{
		Stack<string> stack = new Stack<string>(treeNames.Reverse());
		string text = "";
		while (stack.Count > 0)
		{
			text = ((text.Length <= 0) ? stack.Pop() : (stack.Pop() + "\\" + text));
		}
		return text;
	}

	private void IncludeNodes(BaseTest DroppedNode, BaseTest test, Position insertPosition, string destinationName)
	{
		TraceMessage.Write(ToString(), "IncludeNodes", TraceMessageType.Trace);
		try
		{
			BaseTest copiedTest = test;
			bLoadingTree = true;
			if (test is FolderTest)
			{
				FolderTest folderTest = new FolderTest(test.Properties.TestName);
				foreach (BaseTest test2 in ((FolderTest)test).TestList)
				{
					folderTest.Add(test2);
				}
				folderTest.FolderProperties.ConfigLocation = ((FolderTest)test).FolderProperties.ConfigLocation;
				folderTest.FolderProperties.ConfigChecksum = ((FolderTest)test).FolderProperties.ConfigChecksum;
				folderTest.Properties.CheckStateTest = ((FolderTest)test).Properties.CheckStateTest;
				folderTest.FolderProperties.LinkRoot = ((FolderTest)test).FolderProperties.LinkRoot;
				folderTest.FolderProperties.LinkLocation = ((FolderTest)test).FolderProperties.LinkLocation;
				folderTest.FolderProperties.LinkChecksum = ((FolderTest)test).FolderProperties.LinkChecksum;
				folderTest.FolderProperties.LinkTreeID = ((FolderTest)test).FolderProperties.LinkTreeID;
				folderTest.FolderProperties.LinkSiteKey = ((FolderTest)test).FolderProperties.LinkSiteKey;
				folderTest.FolderProperties.LinkSiteTreeID = ((FolderTest)test).FolderProperties.LinkSiteTreeID;
				folderTest.FolderProperties.LinkRegisteredMachine = ((FolderTest)test).FolderProperties.LinkRegisteredMachine;
				folderTest.FolderProperties.LinkTreeStringID = ((FolderTest)test).FolderProperties.LinkTreeStringID;
				folderTest.FolderProperties.IsLinkActive = ((FolderTest)test).FolderProperties.IsLinkActive;
				folderTest.Properties.TestErrorCode = ((FolderTest)test).Properties.TestErrorCode;
				copiedTest = folderTest;
			}
			FolderTest folderTest2 = new FolderTest();
			folderTest2.Properties.TestName = "Temp";
			importingTrees = true;
			ConstructPasteTree(folderTest2, copiedTest, Root, aslink: false);
			importingTrees = false;
			if (!AddNewNode(DroppedNode, folderTest2.TestList[0], insertPosition))
			{
				AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			bLoadingTree = false;
			if (DroppedNode is FolderTest && ((FolderTest)DroppedNode).TestList.Count > 0)
			{
				UpdateCheckState(((FolderTest)DroppedNode).TestList[0]);
			}
			else
			{
				UpdateCheckState(DroppedNode);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "IncludeNodes " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void ConstructPasteTree(FolderTest Parent, BaseTest copiedTest, RootTest originalRoot, bool aslink)
	{
		TraceMessage.Write(ToString(), "ConstructPasteTree", TraceMessageType.Trace);
		try
		{
			CreatePasteTree(Parent, copiedTest, originalRoot, aslink);
			UpdatePostConditionIndices(copiedTest, originalRoot);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ConstructPasteTree " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void CreatePasteTree(FolderTest Parent, BaseTest copiedTest, RootTest originalRoot, bool aslink)
	{
		if (!Parent.TestList.Contains(copiedTest))
		{
			Parent.TestList.Add(copiedTest);
		}
		if (aslink && copiedTest.Properties.SkipWhenLinked)
		{
			copiedTest.Properties.CheckStateTest = CheckState.Unchecked;
		}
		copiedTest.OriginalIndex = copiedTest.Index;
		copiedTest.Index = Guid.NewGuid().ToString();
		UpdatePreConditionIndices(copiedTest, originalRoot);
		UpdateLoopIndices(copiedTest, originalRoot);
		try
		{
			if (copiedTest.Properties.RetryCount > 0)
			{
				int retryCount = copiedTest.Properties.RetryCount;
				copiedTest.Properties.RetryCount = 0;
				copiedTest.Properties.RetryCount = retryCount;
			}
		}
		catch
		{
		}
		TestNodesColl[copiedTest.Index] = copiedTest;
		ApplyLeftIcons(copiedTest);
		if (copiedTest is FolderTest)
		{
			foreach (BaseTest test in ((FolderTest)copiedTest).TestList)
			{
				test.Parent = (FolderTest)copiedTest;
				CreatePasteTree((FolderTest)copiedTest, test, originalRoot, aslink);
			}
			return;
		}
		copiedTest.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTest.png", "/QSPR;component/Icons/TestTreeTest.png");
		if (importingTrees)
		{
			ApplyParameterLogging(copiedTest);
		}
	}

	private void UpdateLoopIndices(BaseTest copiedTest, RootTest originalRoot)
	{
		if (copiedTest.Properties.Scenarios == null)
		{
			return;
		}
		foreach (LoopCondition loopCondition in copiedTest.Properties.Scenarios.LoopConditions)
		{
			if (!string.IsNullOrWhiteSpace(loopCondition.TestIndex))
			{
				BaseTest baseTest = originalRoot.FindTestWithOrigIndex(loopCondition.TestIndex);
				if (baseTest != null)
				{
					loopCondition.TestIndex = baseTest.Index;
				}
			}
		}
		if (copiedTest.Properties.Scenarios.Condition == null || copiedTest.Properties.Scenarios.Condition.Conditions.Count <= 0)
		{
			return;
		}
		foreach (ScenarioCondition condition in copiedTest.Properties.Scenarios.Condition.Conditions)
		{
			if (!string.IsNullOrWhiteSpace(condition.TestIndex))
			{
				BaseTest baseTest2 = originalRoot.FindTestWithOrigIndex(condition.TestIndex);
				if (baseTest2 != null)
				{
					condition.TestIndex = baseTest2.Index;
				}
			}
		}
	}

	private void UpdatePreConditionIndices(BaseTest copiedTest, RootTest originalRoot)
	{
		if (copiedTest.Properties.PreCondition == null)
		{
			return;
		}
		foreach (TestPreCondition condition in copiedTest.Properties.PreCondition.Conditions)
		{
			if (!string.IsNullOrWhiteSpace(condition.TestIndex))
			{
				BaseTest baseTest = originalRoot.FindTestWithOrigIndex(condition.TestIndex);
				if (baseTest != null)
				{
					condition.TestIndex = baseTest.Index;
				}
			}
		}
	}

	private void UpdatePostConditionIndices(BaseTest copiedTest, RootTest originalRoot)
	{
		if (copiedTest.Properties.PostCondition != null)
		{
			foreach (TestPreCondition condition in copiedTest.Properties.PostCondition.Conditions)
			{
				if (!string.IsNullOrWhiteSpace(condition.TestIndex))
				{
					BaseTest baseTest = originalRoot.FindTestWithOrigIndex(condition.TestIndex);
					if (baseTest != null)
					{
						condition.TestIndex = baseTest.Index;
					}
				}
			}
		}
		if (!(copiedTest is FolderTest))
		{
			return;
		}
		foreach (BaseTest test in (copiedTest as FolderTest).TestList)
		{
			UpdatePostConditionIndices(test, originalRoot);
		}
	}

	private void UpdateCheckState(BaseTest checkNode)
	{
		try
		{
			if (checkNode.Parent != null)
			{
				CheckState checkState = UpdateParentCheckedState(checkNode.Parent);
				if (checkState != checkNode.Parent.Properties.CheckStateTest)
				{
					checkNode.Parent.Properties.CheckStateTest = checkState;
				}
				UpdateCheckState(checkNode.Parent);
			}
			if (checkNode is FolderTest)
			{
				bool? isLinkActive = (checkNode as FolderTest).FolderProperties.IsLinkActive;
				if ((!isLinkActive.HasValue || isLinkActive == false) && (checkNode.Properties.CheckStateTest == CheckState.Checked || checkNode.Properties.CheckStateTest == CheckState.Unchecked))
				{
					CheckFolderNodes((FolderTest)checkNode, checkNode.Properties.CheckStateTest);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateCheckState " + ex.Message, TraceMessageType.Exception);
		}
	}

	private CheckState UpdateParentCheckedState(FolderTest node)
	{
		int count = node.TestList.Count;
		int num = 0;
		foreach (BaseTest test in node.TestList)
		{
			if (test.Properties.CheckStateTest == CheckState.Indeterminate)
			{
				return CheckState.Indeterminate;
			}
			if (test.Properties.CheckStateTest == CheckState.Checked)
			{
				num++;
			}
		}
		if (count == num)
		{
			return CheckState.Checked;
		}
		if (num == 0)
		{
			return CheckState.Unchecked;
		}
		return CheckState.Indeterminate;
	}

	private void CheckFolderNodes(FolderTest checkNode, CheckState checkState)
	{
		TraceMessage.Write(ToString(), "CheckFolderNodes", TraceMessageType.Trace);
		try
		{
			if (checkNode.TestList.Count <= 0)
			{
				return;
			}
			foreach (BaseTest test in checkNode.TestList)
			{
				if (!test.IsTestStep)
				{
					test.Properties.CheckStateTest = checkState;
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "CheckFolderNodes " + ex.Message, TraceMessageType.Exception);
		}
	}

	private static string GetHashValue(Hashtable hash, string key)
	{
		if (hash.Contains(key))
		{
			return hash[key].ToString();
		}
		return "";
	}

	private void MakeLinkNodes(BaseTest qTests)
	{
		qTests.Properties.LinkNode = true;
		qTests.Properties.IsLinkActive = true;
		if (!(qTests is FolderTest))
		{
			return;
		}
		foreach (BaseTest test in ((FolderTest)qTests).TestList)
		{
			MakeLinkNodes(test);
		}
	}

	private void IncludeNodes(BaseTest DroppedNode, RootTest rTest, FolderTest oldRootFolder, bool aslink, Position insertPosition, bool removeRootFolder, bool isQSPR2Tree, string destinationName)
	{
		TraceMessage.Write(ToString(), "IncludeNodes", TraceMessageType.Trace);
		try
		{
			FolderTest folderTest = new FolderTest(rTest.Properties.TestName);
			if (isQSPR2Tree)
			{
				folderTest = (FolderTest)rTest.TestList[0];
				if (string.IsNullOrEmpty(destinationName) && GlobalStatus.AutomationMode)
				{
					folderTest.FolderProperties.TestName = DroppedNode.Properties.TestName;
					if (DroppedNode is FolderTest)
					{
						foreach (BaseTest test in ((FolderTest)DroppedNode).TestList)
						{
							if (test.Properties.TestName == "StartUp" && test is FolderTest && ((FolderTest)test).TestList.Count == 0)
							{
								TestTreeSelectionManager.ClearSelections();
								TestTreeSelectionManager.SelectTest(test);
								DeleteNode();
							}
						}
					}
				}
				if (aslink)
				{
					folderTest.Properties.LinkNode = false;
				}
			}
			else
			{
				foreach (BaseTest test2 in rTest.TestList)
				{
					folderTest.Add(test2);
				}
			}
			if (removeRootFolder && !string.IsNullOrEmpty(destinationName))
			{
				HandleRemovingRootFolder(folderTest, insertPosition, DroppedNode);
				return;
			}
			bLoadingTree = true;
			FolderTest folderTest2 = new FolderTest();
			folderTest2.Properties.TestName = "Temp";
			if (oldRootFolder != null)
			{
				oldRootFolder.FolderProperties.Copy(folderTest.FolderProperties);
				if (!folderTest.FolderProperties.LinkConfigLocationEdited)
				{
					folderTest.FolderProperties.ConfigLocation = rTest.FolderProperties.ConfigLocation;
					folderTest.FolderProperties.ConfigChecksum = rTest.FolderProperties.ConfigChecksum;
				}
			}
			else
			{
				folderTest.FolderProperties.ConfigLocation = rTest.FolderProperties.ConfigLocation;
				folderTest.FolderProperties.ConfigChecksum = rTest.FolderProperties.ConfigChecksum;
			}
			folderTest.Properties.CheckStateTest = rTest.Properties.CheckStateTest;
			folderTest.FolderProperties.LinkRoot = rTest.FolderProperties.LinkRoot;
			folderTest.FolderProperties.LinkLocation = rTest.FolderProperties.LinkLocation;
			folderTest.FolderProperties.LinkChecksum = rTest.FolderProperties.LinkChecksum;
			folderTest.FolderProperties.LinkTreeID = rTest.FolderProperties.LinkTreeID;
			folderTest.FolderProperties.LinkSiteKey = rTest.FolderProperties.LinkSiteKey;
			folderTest.FolderProperties.LinkSiteTreeID = rTest.FolderProperties.LinkSiteTreeID;
			folderTest.FolderProperties.LinkRegisteredMachine = rTest.FolderProperties.LinkRegisteredMachine;
			folderTest.FolderProperties.LinkTreeStringID = rTest.FolderProperties.LinkTreeStringID;
			folderTest.FolderProperties.IsLinkActive = rTest.FolderProperties.IsLinkActive;
			folderTest.Properties.TestErrorCode = rTest.Properties.TestErrorCode;
			importingTrees = true;
			ConstructPasteTree(folderTest2, folderTest, rTest, aslink);
			importingTrees = false;
			if (!AddNewNode(DroppedNode, folderTest2.TestList[0], insertPosition))
			{
				AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			bLoadingTree = false;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "IncludeNodes " + ex.Message, TraceMessageType.Exception);
		}
	}

	public bool DeleteNode(BaseTest nodeToDelete = null)
	{
		TraceMessage.Write(ToString(), "Delete Node", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0 || nodeToDelete != null)
			{
				foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
				{
					if (selectedTest.IsTestStep && selectedTest.TestCase != null && selectedTest.TestCase.TestCaseProperties != null && selectedTest.TestCase.TestCaseProperties.Status == ApprovalStates.Approved)
					{
						AppMessageDialog.Show("Unable to delete test steps inside an approved test case.  Please switch the test case to draft mode (right click and hit switch to draft).", DialogResult.OK, MessageDialogType.Error);
						return false;
					}
				}
				if (nodeToDelete == null && AppMessageDialog.Show("Do you want to delete the Selected Nodes ? ", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning) == DialogResult.No)
				{
					return false;
				}
				BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
				if (nodeToDelete != null)
				{
					baseTest = nodeToDelete;
					TestTreeSelectionManager.ClearSelections();
					TestTreeSelectionManager.SelectTest(nodeToDelete);
				}
				if (baseTest == Root)
				{
					AppMessageDialog.Show("Root node can not be deleted", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Warning);
					return false;
				}
				if (baseTest.Properties.LinkNode && baseTest.Properties.IsLinkActive == true)
				{
					AppMessageDialog.Show("Linked nodes cannot be modified.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
					return false;
				}
				ArrayList arrayList = new ArrayList();
				foreach (BaseTest selectedTest2 in TestTreeSelectionManager.SelectedTests)
				{
					BaseTest baseTest2 = selectedTest2;
					BaseTest baseTest3 = baseTest2.Clone();
					baseTest3.Parent = null;
					baseTest3.CreateLoopParentList(arrayList);
				}
				if (arrayList.Count > 0)
				{
					string text = "";
					foreach (DeletedLink item in arrayList)
					{
						text = text + "\n" + TestNodesColl[item.ChildIndex].UltraTreeNodePath;
					}
					DialogResult dialogResult = AppMessageDialog.Show("Following Tests will be deleted from the Loop Conditions: " + text + "\nDo you want to continue..", "Loop Tests Deletion", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, DialogResult.OK, MessageDialogType.Warning);
					if (dialogResult == DialogResult.Cancel)
					{
						return false;
					}
				}
				if (baseTest.Parent != null)
				{
					FolderTest parent = baseTest.Parent;
					if (parent.FolderProperties.Scenarios != null && parent.FolderProperties.HasValidLoopDescription())
					{
						DialogResult dialogResult2 = AppMessageDialog.Show("Loop Descriptions should be modified for " + parent.Properties.TestName + ".\n               Do you want to continue?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning);
						if (dialogResult2 == DialogResult.No)
						{
							return false;
						}
					}
				}
				FolderTest folderTest = new FolderTest();
				ArrayList arrayList2 = new ArrayList();
				int index = 0;
				foreach (BaseTest selectedTest3 in TestTreeSelectionManager.SelectedTests)
				{
					arrayList2.Add(selectedTest3);
					folderTest = selectedTest3.Parent;
					index = selectedTest3.Parent.TestList.IndexOf(selectedTest3);
				}
				foreach (BaseTest item2 in arrayList2)
				{
					FolderTest parent2 = item2.Parent;
					parent2.TestList.Remove(item2);
				}
				SelectedNextNode(folderTest, index);
				RefreshTree(testTreeView);
				TreeChanged = true;
				TreeChangedDataCollection = true;
				GlobalStatus.RegistrationStatus.TreeNodeDeleted = true;
				if (folderTest.TestList.Count > 0)
				{
					UpdateCheckState(folderTest.TestList[0]);
				}
				else
				{
					folderTest.Properties.CheckStateTest = CheckState.Unchecked;
				}
				ResetTestTree(folderTest);
				RefreshTreeViewList(Root.TestList.ToList());
				return true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Delete Node " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void SelectedNextNode(BaseTest pNode, int index)
	{
		int num = 0;
		if (pNode is FolderTest)
		{
			num = ((FolderTest)pNode).TestList.Count;
		}
		if (num == 0)
		{
			TestTreeSelectionManager.SelectTest(pNode);
		}
		else if (index < num)
		{
			TestTreeSelectionManager.SelectTest(((FolderTest)pNode).TestList[index]);
		}
		else
		{
			TestTreeSelectionManager.SelectTest(((FolderTest)pNode).TestList[num - 1]);
		}
	}

	private void HandleRemovingRootFolder(FolderTest tFolder, Position insertPosition, BaseTest DroppedNode)
	{
		bLoadingTree = true;
		importingTrees = true;
		foreach (BaseTest test in tFolder.TestList)
		{
			FolderTest folderTest = new FolderTest();
			folderTest.Properties.TestName = "Temp";
			ConstructPasteTree(folderTest, test, Root, aslink: false);
			if (!AddNewNode(DroppedNode, folderTest.TestList[0], insertPosition))
			{
				AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
		}
		bLoadingTree = false;
		importingTrees = false;
	}

	public bool CollapseExpandAllTests(bool collapse)
	{
		TraceMessage.Write(ToString(), "CollapseExpandAllTests", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
				{
					if (collapse)
					{
						TestTreeBrowser.CollapseAll(selectedTest);
					}
					else
					{
						TestTreeBrowser.ExpandAll(selectedTest);
					}
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "CollapseExpandAllTests " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void ClearAllComments()
	{
		TraceMessage.Write(ToString(), "ClearAllComments", TraceMessageType.Trace);
		try
		{
			if (AppMessageDialog.Show("Do you want to reset the comments ? ", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning) != DialogResult.No && TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
				baseTest.ResetComment();
				TreeChanged = true;
				ResetTestFolder();
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ClearAllComments " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void ResetTestFolder()
	{
		if (TestTreeSelectionManager.SelectedTests.Count <= 0)
		{
			return;
		}
		TraceMessage.Write(ToString(), "ResetTestFolderIcons", TraceMessageType.Trace);
		try
		{
			foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
			{
				ResetTestTree(selectedTest);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ResetTestFolderIcons " + ex.Message, TraceMessageType.Exception);
		}
	}

	private bool AddFolder(Position insertPosition)
	{
		FolderTest FolderNode;
		return AddFolder(insertPosition, out FolderNode);
	}

	public bool AddFolder(Position insertPosition, out FolderTest FolderNode, BaseTest dropNode = null, bool isTestCaseFolder = false)
	{
		FolderNode = null;
		TraceMessage.Write(ToString(), "Add Folder", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
				if (dropNode != null)
				{
					baseTest = dropNode;
				}
				bool flag = false;
				BaseTest baseTest2 = baseTest;
				if (baseTest2.Properties.LinkNode && baseTest2.Properties.IsLinkActive == true)
				{
					flag = true;
				}
				if (baseTest2 is FolderTest && !(baseTest2 is TestCaseTest) && ((FolderTest)baseTest2).FolderProperties.LinkRoot)
				{
					bool? isLinkActive = ((FolderTest)baseTest2).FolderProperties.IsLinkActive;
					if (isLinkActive.GetValueOrDefault() && isLinkActive.HasValue && baseTest.Properties.Expanded)
					{
						flag = true;
					}
				}
				if (flag)
				{
					AppMessageDialog.Show("Linked nodes cannot be modified.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
					return false;
				}
				if (isTestCaseFolder)
				{
					FolderNode = new TestCaseTest();
				}
				else
				{
					FolderNode = new FolderTest();
				}
				FolderNode.Properties.TestName = "Folder";
				FolderNode.ConfigureNodeImage("/QSPR;component/Icons/folder-closed.png", "/QSPR;component/Icons/folder-open.png");
				FolderNode.Properties.CheckStateTest = CheckState.Checked;
				FolderNode.Properties.Expanded = true;
				bDragFromRegistry = true;
				TestTreeSelectionManager.ClearSelections();
				if (!AddNewNode(baseTest, FolderNode, insertPosition))
				{
					AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
				}
				if (baseTest is FolderTest)
				{
					((FolderTest)baseTest).Properties.Expanded = true;
				}
				TestNodesColl.Clear();
				RefreshTreeViewList(Root.TestList.ToList());
				TestTreeSelectionManager.SelectTest(FolderNode);
				TestTreeEditor.BeginTestNameEdit(FolderNode);
				return true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Add Folder " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void AddNonQTMLoopLinks()
	{
		RootTest root = Root;
		root.AddNonQTMLoopLinks();
	}

	public void AddTestCasesPlugin(TestCasesPlugin dWin)
	{
		TabItem tabItem = new TabItem();
		tabItem.Header = dWin.Caption;
		QTMUtility.LoadPluginContainer(tabItem, dWin);
		treeViewSubTabControl.Items.Add(tabItem);
		TestCasesPluginsColl.Add(dWin.Caption, dWin);
		GlobalStatus.PluginList.Add(dWin.Caption);
		dWin.OnGetTestCases += tcPlugin_OnGetTestCases;
		dWin.OnLoadTestPlan += dWin_OnLoadTestPlan;
		dWin.OnTestCasesCreated += dWin_OnTestCaseCreated;
		dWin.OnTestPlanCreated += dWin_OnTestPlanCreated;
		dWin.OnRequestSerializedTestCase += dWin_OnRequestSerializedTestCase;
		dWin.OnConfigInfo(wsc);
		treeViewSubTabControl.SelectedItem = tabItem;
	}

	private bool ValidateVersion(BaseTest startingNode = null)
	{
		DLLVersionValidator dLLVersionValidator = new DLLVersionValidator(RegistryRoot);
		if (!Root.RootProperties.EnforceTestDllVersions)
		{
			return true;
		}
		if (!dLLVersionValidator.ValidateRegistryVersions(out var errorMessage))
		{
			AppMessageDialog.Show(errorMessage, DialogResult.OK, MessageDialogType.Error);
			return false;
		}
		if (startingNode == null)
		{
			startingNode = Root;
		}
		NodeAppearanceUtility.SetNodeColorRecursive(Root, Colors.White);
		List<string> invalidTestIndexList = new List<string>();
		if (!dLLVersionValidator.Validate(startingNode, out invalidTestIndexList))
		{
			foreach (string item in invalidTestIndexList)
			{
				BaseTest baseTest = FindNodeByGUID(item);
				if (baseTest != null)
				{
					NodeAppearanceUtility.SetNodeColorRecursiveUp(baseTest, Colors.Red);
				}
			}
			bool flag = invalidTestIndexList.Count > 1;
			errorMessage = string.Format("{0} test{1} require{2} a higher DLL version than you have loaded.\nThe invalid tests are marked in red.", invalidTestIndexList.Count, flag ? "s" : "", flag ? "" : "s");
			AppMessageDialog.Show(errorMessage, DialogResult.OK, MessageDialogType.Error);
			return false;
		}
		NodeAppearanceUtility.SetNodeColorRecursive(Root, Colors.White);
		return true;
	}

	private void RevertSelectedTestCases()
	{
		List<TestCaseTest> list = new List<TestCaseTest>();
		foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
		{
			list.AddRange(GetTestCasesFromNodeAndChildren(selectedTest));
		}
		foreach (TestCaseTest item in list.Where((TestCaseTest tc) => tc.TestCaseProperties.Dirty).Distinct())
		{
			RevertTestCase(item);
		}
	}

	private void RevertTestCase(TestCaseTest testCase)
	{
		WaitForTestCasePluginsToFinishWork();
		_testCasePluginsWaiting = 0;
		foreach (TestCasesPlugin plugin in TestCasesPluginsColl.Values)
		{
			TestCaseMaster tcData = CreateFakeTestCaseMasterFromTestCaseTest(testCase);
			tcData.LatestVersion.VersionNumber = 0;
			ThreadPool.QueueUserWorkItem(delegate
			{
				plugin.RequestTestCases(new List<TestCaseMaster> { tcData }, wasManualUpdateRequest: true, forceUpdateOrRevert: true);
			});
			_testCasePluginsWaiting++;
		}
		WaitForTestCasePluginsToFinishWork();
	}

	private bool UpdateTestCases(bool wasManualUpdateRequest, bool forceUpdate)
	{
		if (TestTreeSelectionManager.SelectedTests.Count == 0)
		{
			return false;
		}
		List<TestCaseMaster> testCaseList = GetTestCaseProxiesFromSelectedNodes();
		_testCasePluginsWaiting = 0;
		if (testCaseList.Count > 0)
		{
			foreach (TestCasesPlugin plugin in TestCasesPluginsColl.Values)
			{
				WaitCallback callBack = delegate
				{
					plugin.RequestTestCases(testCaseList, wasManualUpdateRequest, forceUpdate);
				};
				ThreadPool.QueueUserWorkItem(callBack);
				_testCasePluginsWaiting++;
			}
		}
		WaitForTestCasePluginsToFinishWork();
		return _testCasesUpdatedCount != 0;
	}

	private List<TestCaseMaster> GetTestCaseProxiesFromSelectedNodes()
	{
		List<TestCaseMaster> list = new List<TestCaseMaster>();
		foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
		{
			List<TestCaseTest> testCasesFromNodeAndChildren = GetTestCasesFromNodeAndChildren(selectedTest);
			foreach (TestCaseTest item2 in testCasesFromNodeAndChildren)
			{
				TestCaseMaster item = CreateFakeTestCaseMasterFromTestCaseTest(item2);
				list.Add(item);
			}
		}
		return list;
	}

	private static TestCaseMaster CreateFakeTestCaseMasterFromTestCaseTest(TestCaseTest tc)
	{
		TestCaseMaster testCaseMaster = new TestCaseMaster();
		testCaseMaster.Id = tc.TestCaseProperties.TestCaseMasterID;
		testCaseMaster.Versions = new List<TestCaseVersion>();
		testCaseMaster.DisplayId = tc.TestCaseProperties.DisplayID;
		testCaseMaster.Name = tc.TestCaseProperties.TestName;
		TestCaseMaster testCaseMaster2 = testCaseMaster;
		testCaseMaster2.Versions.Add(new TestCaseVersion
		{
			Id = tc.TestCaseProperties.TestCaseID,
			ApprovalState = tc.TestCaseProperties.Status,
			ModifiedDate = tc.TestCaseProperties.ModifiedDate,
			VersionNumber = (int)tc.TestCaseProperties.Version
		});
		return testCaseMaster2;
	}

	private void WaitForTestCasePluginsToFinishWork()
	{
		while (_testCasePluginsWaiting > 0)
		{
			QTMData.DoEvents();
			Thread.Sleep(10);
		}
	}

	private List<TestCaseTest> GetTestCasesFromNodeAndChildren(BaseTest node)
	{
		List<TestCaseTest> list = new List<TestCaseTest>();
		if (node is FolderTest)
		{
			foreach (BaseTest item2 in from p in (node as FolderTest).Descendants()
				where p is TestCaseTest
				select p)
			{
				TestCaseTest item = (TestCaseTest)item2;
				list.Add(item);
			}
			if (node is TestCaseTest)
			{
				list.Add((TestCaseTest)node);
			}
		}
		return list;
	}

	private void tcPlugin_OnGetTestCases(object sender, GetTestCasesEventArgs e)
	{
		try
		{
			if (this.InvokeRequired())
			{
				this.BeginInvoke(delegate
				{
					tcPlugin_OnGetTestCases(sender, e);
				});
				return;
			}
			_testCasesUpdatedCount = e.TestCases.Count;
			string text = "ID\tVersion\tName\n";
			foreach (TestCaseMaster item in e.TestCases.Take(25))
			{
				text += $"{item.DisplayId}\t{(e.ForceUpdateOrRevert ? item.LatestVersion.VersionNumber : item.LatestApprovedVersion.VersionNumber)}\t{item.Name}\n";
			}
			if (e.TestCases.Count > 25)
			{
				text += "Additional test cases need to be updated but are not shown....";
			}
			if (_testCasesUpdatedCount == 0)
			{
				_testCasePluginsWaiting--;
				if (e.WasManualUpdateRequest)
				{
					AppMessageDialog.Show("All testcases are up to date.", "Test Cases Updated", MessageBoxButtons.OK, DialogResult.OK, MessageDialogType.Information);
				}
				return;
			}
			if (e.ForceUpdateOrRevert)
			{
				if (AppMessageDialog.Show($"{_testCasesUpdatedCount} test cases in this plan will be updated.", "Refresh Test Cases", MessageBoxButtons.OKCancel, DialogResult.OK, MessageDialogType.Warning) != DialogResult.OK)
				{
					_testCasePluginsWaiting--;
					return;
				}
			}
			else if (AppMessageDialog.Show($"{_testCasesUpdatedCount} test cases in this plan have been updated.\nYou can not run this tree without updating the testcases.\n\n{text}\n\nDo you want to update your tree or cancel?", "Test Cases Updated", MessageBoxButtons.OKCancel, DialogResult.OK, MessageDialogType.Warning) != DialogResult.OK)
			{
				_testCasePluginsWaiting--;
				return;
			}
			int num = 0;
			List<BaseTest> list = new List<BaseTest>();
			BaseTest root = Root;
			UpdatingTestCasesDialog updatingTestCasesDialog = new UpdatingTestCasesDialog(_testCasesUpdatedCount * 2);
			updatingTestCasesDialog.Show();
			int num2 = 0;
			foreach (BaseTest d in from p in (root as FolderTest).Descendants()
				where p is TestCaseTest
				select p)
			{
				List<TestCaseMaster> testCases = e.TestCases;
				Func<TestCaseMaster, bool> predicate = (TestCaseMaster p) => ((TestCaseTest)d).TestCaseProperties.TestCaseMasterID == p.Id;
				TestCaseMaster testCaseMaster = testCases.FirstOrDefault(predicate);
				if (testCaseMaster != null)
				{
					updatingTestCasesDialog.SetCurrent(num2++, testCaseMaster.Name);
					_testCaseDragDrop.AddTestCase(testCaseMaster, d);
					list.Add(d);
					if (testCaseMaster == null)
					{
						AppMessageDialog.Show("Unable to update testcases.  Aborting", DialogResult.OK, MessageDialogType.Error);
						throw new Exception("Unable to update testcases.  Aborting");
					}
					QTMData.DoEvents();
					Thread.Sleep(10);
				}
			}
			while (list.Count > 0)
			{
				updatingTestCasesDialog.SetCurrent(num2++, "Cleaning");
				DeleteNode(list[0]);
				list.RemoveAt(0);
				QTMData.DoEvents();
				Thread.Sleep(10);
			}
			updatingTestCasesDialog.Close();
			while (num > 0)
			{
				QTMData.DoEvents();
				Thread.Sleep(10);
			}
		}
		catch (Exception)
		{
		}
		_testCasePluginsWaiting--;
	}

	private void dWin_OnRequestSerializedTestCase(object sender, SerializeTestCaseEventArgs e)
	{
		string xmlData = e.TCMaster.LatestVersion.XmlData;
		ManualTest manualTest;
		if (xmlData == null)
		{
			manualTest = new ManualTest();
			manualTest.Properties = new TestProperties();
			manualTest.Properties.TestErrorCode = e.TCMaster.Name;
			manualTest.IsTestStep = true;
			manualTest.Properties.Parameters = new ParameterCollection(e.TCMaster.LatestVersion.Steps.Last().Parameters);
		}
		else
		{
			manualTest = (ManualTest)TestCaseDragDrop.DeserializeTestCaseMaster(e.TCMaster);
			manualTest.Properties.Parameters = new ParameterCollection(e.TCMaster.LatestVersion.Steps.Last().Parameters);
		}
		manualTest.Properties.TestName = e.TCMaster.Name;
		manualTest.Properties.RealName = e.TCMaster.Name;
		manualTest.Properties.Description = e.TCMaster.LatestVersion.Description;
		manualTest.Root = Root;
		string serializedXml = TestCaseDragDrop.GenerateXmlData(manualTest);
		((TestCasesPlugin)sender).TestCaseSerialized(e.TCMaster, serializedXml);
	}

	private void dWin_OnTestPlanCreated(object sender, TestPlanCreatedEventArgs e)
	{
		AppMessageDialog.Show("Test PLAN Created", DialogResult.OK, MessageDialogType.Information);
	}

	private void dWin_OnTestCaseCreated(object sender, TestCaseCreatedEventArgs e)
	{
		for (int i = 0; i < e.TestIndexList.Count; i++)
		{
			string guid = e.TestIndexList[i];
			BaseTest baseTest = FindNodeByGUID(guid);
			if (baseTest != null)
			{
				BaseTest baseTest2 = TestTreeBrowser.GetPreviousSibling(baseTest);
				if (baseTest2 == null)
				{
					baseTest2 = baseTest.Parent;
				}
				else if (baseTest2.Properties.Expanded)
				{
					TestTreeBrowser.CollapseAll(baseTest2);
				}
				_testCaseDragDrop.AddTestCase(e.TestCases[i], baseTest2);
				DeleteNode(baseTest);
			}
		}
	}

	public ArrayList GetTesterConfiguration()
	{
		return (base.Parent as TabItem).Parent.FindParent<WPFTestTreeWindowColl>().GetTesterConfiguration();
	}

	private void dWin_OnLoadTestPlan(object sender, LoadTestPlanEventArgs e)
	{
		(base.Parent as TabItem).Parent.FindParent<WPFTestTreeWindowColl>().OpenFile(e.TestPlanFileName);
		XmlTreeName = e.TestPlanFileName;
		if (!(Root.RootProperties is TestPlanProperties))
		{
			Root.RootProperties = new TestPlanProperties(Root.RootProperties);
		}
		(Root.RootProperties as TestPlanProperties).TestPlanVersionID = e.TestPlanId;
		(Root.RootProperties as TestPlanProperties).TestPlanName = e.TestPlanName;
		(Root.RootProperties as TestPlanProperties).Status = e.TestPlanStatus;
		(Root.RootProperties as TestPlanProperties).TestPlanMasterID = e.MasterId;
		(Root.RootProperties as TestPlanProperties).ID = e.DisplayId;
		(Root.RootProperties as TestPlanProperties).Version = e.Version;
		if (!string.IsNullOrWhiteSpace(e.DynamicLimitsFileNameBase))
		{
			(Root.RootProperties as TestPlanProperties).DynamicLimitsFileExcel = e.DynamicLimitsFileNameBase + ".xls";
			(Root.RootProperties as TestPlanProperties).DynamicLimitsFileXML = e.DynamicLimitsFileNameBase + ".xml";
		}
		ResetTestPlanDirtyFlag(e.TestPlanName);
		SaveFile(SaveAsFormat.QSPR, suppressTreeUpgradeWarning: true);
		ResetTestPlanDirtyFlag(e.TestPlanName);
	}

	private void ResetTestPlanDirtyFlag(string testPlanName)
	{
		(Root.RootProperties as TestPlanProperties).SetDirty(isDirty: false);
		Root.RootProperties.TestName = testPlanName;
	}

	private void dWin_OnCreateTestCase(object sender, CreateTestCaseEventArgs e)
	{
		throw new NotImplementedException();
	}

	private void SendSelectedNodesToTestCasePlugins(ObservableCollection<BaseTest> nodes)
	{
		foreach (BaseTest node in nodes)
		{
			_ = node;
		}
	}

	private void GenerateTestCaseData()
	{
		foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
		{
			BaseTest baseTest = selectedTest;
			if (baseTest.Properties.Parameters.Count == 0)
			{
				AppMessageDialog.Show("No parameters on this test.  Please use a test with parameters.", DialogResult.OK, MessageDialogType.Error);
				break;
			}
			ParameterCls parameterCls = baseTest.Properties.Parameters[0];
			List<TestCaseMaster> list = new List<TestCaseMaster>();
			for (int i = 0; i < 1000; i++)
			{
				parameterCls.Value = i.ToString();
				TestCaseMaster testCaseMaster = TestCaseDragDrop.CreateTestCaseData(baseTest);
				testCaseMaster.Name = baseTest.Properties.TestName + " Debug TestCase " + i;
				list.Add(testCaseMaster);
			}
			SendTestCaseToPlugins(list);
		}
	}

	private void SendTestCaseToPlugins(List<TestCaseMaster> testCases)
	{
		foreach (TestCasesPlugin value in TestCasesPluginsColl.Values)
		{
			value.CreateTestCase(testCases);
		}
	}

	public void AddParamPlugIn(ParamViewPlugIn dWin)
	{
		_ = paramPluginsTabControl.SelectedItem;
		TabItem tabItem = new TabItem();
		tabItem.Header = dWin.Caption;
		tabItem.Visibility = Visibility.Collapsed;
		QTMUtility.LoadPluginContainer(tabItem, dWin);
		paramPluginsTabControl.Items.Add(tabItem);
		paramPluginComboBox.Items.Add(new ComboBoxItem
		{
			Content = dWin.Caption
		});
		ParamPlugInsColl.Add(dWin.Caption, dWin);
		GlobalStatus.PluginList.Add(dWin.Caption);
		dWin.OnConfigInfo(wsc);
		dWin.OnParameterChanged += OnParamPluginChanged;
		ParamPluginsLoaded = true;
	}

	protected void OnParamPluginChanged(object sender, ParamChangedEventArgs e)
	{
		List<ParamValue> parameters = e.Parameters;
		string text = "All";
		switch (e.ChangedField)
		{
		case ParamFieldChanged.Value:
			text = "Value";
			break;
		case ParamFieldChanged.ChartingEnabled:
			text = ((!(bool)e.Parameters[0].EnabledCharting[0]) ? "Charting_Disabled" : "Reporting_Enabled");
			break;
		case ParamFieldChanged.DataLogging:
			treeChangedDataCollection = true;
			GlobalStatus.RegistrationStatus.ParameterAttributeChanged = true;
			text = ((!(bool)e.Parameters[0].EnabledDataLogging[0]) ? "Data_Logging_Disabled" : "Data_Logging_Enabled");
			break;
		case ParamFieldChanged.Description:
			text = "Description";
			break;
		case ParamFieldChanged.GvGet:
			text = "GV_Get";
			break;
		case ParamFieldChanged.GvGetLL:
			text = "GV_LL_Get";
			break;
		case ParamFieldChanged.GvGetUL:
			text = "GV_UL_Get";
			break;
		case ParamFieldChanged.GvSet:
			text = "GV_Set";
			break;
		case ParamFieldChanged.LoggingCondition:
			treeChangedDataCollection = true;
			GlobalStatus.RegistrationStatus.ParameterAttributeChanged = true;
			text = "Logging_Condition";
			break;
		case ParamFieldChanged.LowerLimit:
			text = "LL";
			break;
		case ParamFieldChanged.Units:
			text = "Unit";
			break;
		case ParamFieldChanged.UpperLimit:
			text = "UL";
			break;
		case ParamFieldChanged.None:
			return;
		default:
			text = "All";
			break;
		}
		TreeChanged = true;
		foreach (ParamValue item in parameters)
		{
			ParameterCls parameterCls = null;
			foreach (ParameterCls parameter in TestTreeSelectionManager.SelectedTests[0].Properties.Parameters)
			{
				if (parameter.Name == item.ParamName)
				{
					parameterCls = parameter;
					break;
				}
			}
			if (parameterCls != null)
			{
				switch (text)
				{
				case "Value":
					if (parameterCls.NoOfElements == 1)
					{
						parameterCls.Value = item.Value[0].ToString();
					}
					else
					{
						string[] array2 = new string[item.Value.Count];
						for (int j = 0; j < item.Value.Count; j++)
						{
							array2[j] = item.Value[j].ToString();
						}
						if (parameterCls.DataType == DataType.String)
						{
							parameterCls.Value = ParameterCls.ConvertStrArrayToParamString(array2);
						}
						else
						{
							parameterCls.Value = string.Join(','.ToString(), array2);
						}
					}
					if (parameterCls.IsParamDataTable() && item.DataTableValue != null)
					{
						parameterCls.DataTableValue = item.DataTableValue.Copy();
					}
					else
					{
						parameterCls.DataTableValue = null;
					}
					break;
				case "Reporting_Enabled":
				case "Charting_Disabled":
					parameterCls.EnableCharting = item.EnabledCharting;
					break;
				case "Data_Logging_Enabled":
				case "Data_Logging_Disabled":
					parameterCls.EnableDataLogging = item.EnabledDataLogging;
					break;
				case "Description":
					parameterCls.Description = item.Desc;
					break;
				case "GV_Get":
					parameterCls.GlobalVariableName = item.GvGetName;
					break;
				case "GV_LL_Get":
					parameterCls.GlobalVariableForLL = item.GvGetLowerLimit;
					break;
				case "GV_UL_Get":
					parameterCls.GlobalVariableForUL = item.GvGetUpperLimit;
					break;
				case "GV_Set":
					parameterCls.GlobalVariableNameOther = item.GvSetName;
					break;
				case "LL":
					parameterCls.LowerLimit = item.LL[0].ToString();
					break;
				case "Unit":
					parameterCls.Unit = item.Unit;
					break;
				case "UL":
					parameterCls.UpperLimit = item.UL[0].ToString();
					break;
				case "All":
					if (parameterCls.NoOfElements == 1)
					{
						parameterCls.Value = item.Value[0].ToString();
					}
					else
					{
						string[] array = new string[item.Value.Count];
						for (int i = 0; i < item.Value.Count; i++)
						{
							array[i] = item.Value[i].ToString();
						}
						if (parameterCls.DataType == DataType.String)
						{
							parameterCls.Value = ParameterCls.ConvertStrArrayToParamString(array);
						}
						else
						{
							parameterCls.Value = string.Join(','.ToString(), array);
						}
					}
					if (parameterCls.IsParamDataTable() && item.DataTableValue != null)
					{
						parameterCls.DataTableValue = item.DataTableValue.Copy();
					}
					else
					{
						parameterCls.DataTableValue = null;
					}
					parameterCls.EnableCharting = item.EnabledCharting;
					parameterCls.EnableDataLogging = item.EnabledDataLogging;
					parameterCls.Description = item.Desc;
					parameterCls.GlobalVariableName = item.GvGetName;
					parameterCls.GlobalVariableForLL = item.GvGetLowerLimit;
					parameterCls.GlobalVariableForUL = item.GvGetUpperLimit;
					parameterCls.GlobalVariableNameOther = item.GvSetName;
					parameterCls.LowerLimit = item.LL[0].ToString();
					parameterCls.Unit = item.Unit;
					parameterCls.UpperLimit = item.UL[0].ToString();
					break;
				}
				ParameterChangeEventArgs e2 = new ParameterChangeEventArgs(parameterCls, ParameterState.DontCare, text, e.UpdateChangesToAll);
				if (TestTreeSelectionManager.SelectedTests.Count > 0)
				{
					UpdateParameter(TestTreeSelectionManager.SelectedTests[0], e2);
				}
				foreach (ParamViewPlugIn value in ParamPlugInsColl.Values)
				{
					if (value != sender)
					{
						object[] state = new object[2] { value, e.Parameters };
						ThreadPool.QueueUserWorkItem(SendParamUpdateToPlugins, state);
					}
				}
			}
			ttdParameterView.Parameters = TestTreeSelectionManager.SelectedTests[0].Properties.Parameters;
		}
	}

	private void CreateCopyMutex()
	{
		try
		{
			bool flag = false;
			try
			{
				handleClipBoardMutex = Mutex.OpenExisting("TestTreeClipboardMutexName");
				mutexWasCreated = true;
			}
			catch (WaitHandleCannotBeOpenedException)
			{
				flag = true;
			}
			if (flag)
			{
				handleClipBoardMutex = new Mutex(initiallyOwned: false, "TestTreeClipboardMutexName", out mutexWasCreated);
			}
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "CreateCopyMutex failed: " + ex2.Message, TraceMessageType.Exception);
		}
	}

	public void InitTree()
	{
		TraceMessage.Write(ToString(), "InitTree", TraceMessageType.Trace);
		try
		{
			InitTestTree();
			InitRegistryTree();
			CopiedNodes = null;
			TreeChanged = false;
			ttdPropView.PropertyChangedDel = OnPropChanged;
			ttdParameterView.OnParameterChanged += ParameterChangedHandler;
			ttdParameterView.OnDataLoggingChanged += ttdParameterView_OnDataLoggingChanged;
			ttdParameterView.OnRegistrationChanged += ttdParameterView_OnRegistrationChanged;
			ttdLoopView.OnLoopSelectionChanged += ttdLoopView_OnLoopSelectionChanged;
			ttdLoopView.ShowLoopSetupEvent += ttdLoopView_ShowLoopSetupEvent;
			ttdNotes.OnNotesChanged += ttdNotes_OnNotesChanged;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "InitTree " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void OnMouseDown(object sender, EventArgs e)
	{
		tabItemParameters.IsSelected = true;
	}

	private void paramPluginComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		string paramViewName = ((sender as System.Windows.Controls.ComboBox).SelectedItem as ComboBoxItem).Content.ToString();
		ShowParamView(paramViewName, userSelectedDropdown: true);
	}

	private void ShowParamView(string paramViewName, bool userSelectedDropdown)
	{
		if (!(paramViewName != currentTabInView))
		{
			return;
		}
		List<TabItem> list = paramPluginsTabControl.Items.Cast<TabItem>().ToList();
		foreach (TabItem item in list)
		{
			string text = "Parameters";
			if (item.Header != null)
			{
				text = item.Header.ToString();
			}
			if (text == paramViewName)
			{
				if (tabItemParameters.IsSelected)
				{
					tabItemProperties.IsSelected = true;
					tabItemParameters.IsSelected = true;
					paramPluginComboBox.Focus();
				}
				paramPluginsTabControl.SelectedItem = item;
				currentTabInView = paramViewName;
				paramPluginComboBox.SelectedItem = paramPluginComboBox.Items.OfType<ComboBoxItem>().FirstOrDefault((ComboBoxItem item) => item.Content as string == paramViewName);
				break;
			}
		}
	}

	private void paramPluginsTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
	}

	public void ParameterChangedHandler(object sender, ParameterChangeEventArgs e)
	{
		TraceMessage.Write(ToString(), "ParameterChangedHandler", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count <= 0)
			{
				return;
			}
			BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
			if (ParamPlugInsColl.Values.Count > 0)
			{
				List<ParamValue> list = new List<ParamValue>();
				ParamValue p = default(ParamValue);
				if (e.Parameter.GetParamValue(baseTest.Properties.Parameters, out p))
				{
					list.Add(p);
					foreach (ParamViewPlugIn value in ParamPlugInsColl.Values)
					{
						if (value != sender)
						{
							object[] state = new object[2] { value, list };
							ThreadPool.QueueUserWorkItem(SendParamUpdateToPlugins, state);
						}
					}
				}
			}
			if (baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count > 0 && e.UpdateChangesToAll)
			{
				foreach (BaseTest test in ((FolderTest)baseTest).TestList)
				{
					if (!baseTest.Properties.LinkNode || baseTest.Properties.IsLinkActive != true)
					{
						UpdateParameter(test, e);
					}
				}
			}
			switch (e.State.ToString())
			{
			case "IncludeGlobally":
			case "ExcludeGlobally":
				foreach (BaseTest test2 in Root.TestList)
				{
					UpdateParameter(test2, e);
				}
				break;
			}
			ttdPropView.CurrentNode = baseTest;
			if (GlobalStatus.RegistrationStatus.ParameterAttributeChanged)
			{
				_paramIsEditable = e.Parameter.IsEditableInTestPlan;
				TreeChanged = true;
				_paramIsEditable = false;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ParameterChangedHandler " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void TrySetTestCaseDirty(BaseTest test)
	{
		TestCaseTest testCase = test.TestCase;
		if (testCase != null)
		{
			testCase.TestCaseProperties.SetDirty();
			RefreshTestCaseNode(testCase);
		}
	}

	private void RefreshTestCaseNode(TestCaseTest testCase)
	{
		FindNodeByGUID(testCase.Index);
	}

	public void UpdateParameter(BaseTest node, ParameterChangeEventArgs e)
	{
		TraceMessage.Write(ToString(), "UpdateParameter", TraceMessageType.Trace);
		try
		{
			if (node is FolderTest && ((FolderTest)node).TestList.Count > 0)
			{
				foreach (BaseTest test in ((FolderTest)node).TestList)
				{
					UpdateParameter(test, e);
				}
				return;
			}
			bool flag = false;
			foreach (ParameterCls parameter in node.Properties.Parameters)
			{
				if (parameter.Name == e.Parameter.Name)
				{
					flag = true;
					UpdateParamValue(parameter, e);
					break;
				}
			}
			if (!flag)
			{
				return;
			}
			if (node.TestCase != null)
			{
				node.TestCase.TestCaseProperties.SetDirty();
			}
			if (e.State == ParameterState.IncludeGlobally)
			{
				TTInfo.IncludeLoggingGlobally(e.Parameter.Name);
				if (node.Properties.Parameters.DataLogging(e.Parameter.Name, bEnableLogging: true))
				{
					ttdParameterView_OnDataLoggingChanged(this, CheckState.Checked);
				}
			}
			else if (e.State == ParameterState.ExcludeGlobally)
			{
				TTInfo.ExcludeLoggingGlobally(e.Parameter.Name);
				if (node.Properties.Parameters.DataLogging(e.Parameter.Name, bEnableLogging: false))
				{
					ttdParameterView_OnDataLoggingChanged(this, CheckState.Unchecked);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateParameter " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void UpdateParamValue(ParameterCls param, ParameterChangeEventArgs e)
	{
		if (e != null && !string.IsNullOrEmpty(e.Cause))
		{
			switch (e.Cause)
			{
			case "All":
				param.Copy(e.Parameter);
				break;
			case "Reporting_Enabled":
				param.bEnableCharting = true;
				break;
			case "Charting_Disabled":
				param.bEnableCharting = false;
				break;
			case "Value":
				param.Value = e.Parameter.Value;
				break;
			case "Data_Logging_Enabled":
				param.bEnableDataLogging = true;
				break;
			case "Data_Logging_Disabled":
				param.bEnableDataLogging = false;
				break;
			case "Description":
				param.Description = e.Parameter.Description;
				break;
			case "Unit":
				param.Unit = e.Parameter.Unit;
				break;
			case "GV_Get":
				param.GlobalVariableName = e.Parameter.GlobalVariableName;
				break;
			case "GV_Set":
				param.GlobalVariableNameOther = e.Parameter.GlobalVariableNameOther;
				break;
			case "LL":
				param.LowerLimit = e.Parameter.LowerLimit;
				break;
			case "UL":
				param.UpperLimit = e.Parameter.UpperLimit;
				break;
			case "GV_LL_Get":
				param.GlobalVariableForLL = e.Parameter.GlobalVariableForLL;
				break;
			case "GV_UL_Get":
				param.GlobalVariableForUL = e.Parameter.GlobalVariableForUL;
				break;
			case "Logging_Condition":
				param.DataLoggingCondition = e.Parameter.DataLoggingCondition.Clone();
				break;
			}
		}
	}

	private void ttdParameterView_OnDataLoggingChanged(object sender, CheckState newState)
	{
		treeChangedDataCollection = true;
		GlobalStatus.RegistrationStatus.ParameterAttributeChanged = true;
	}

	private void ttdParameterView_OnRegistrationChanged(object sender, string cause)
	{
		treeChangedDataCollection = true;
		GlobalStatus.RegistrationStatus.ParameterAttributeChanged = true;
	}

	private void SendNodeSelectedMessage(object testObj)
	{
		try
		{
			if (testObj != null)
			{
				TestMessage tMessage = default(TestMessage);
				BaseTest baseTest = (BaseTest)testObj;
				tMessage.Message = baseTest.Properties.TestName;
				object parameterExportList = baseTest.Properties.Parameters.GetParameterExportList(onlyLoggedParameters: false, outputOnly: false, ignoreEmptyStringValues: false);
				ArrayList propertyList = GetPropertyList(baseTest.Properties);
				tMessage.Object = new object[2] { parameterExportList, propertyList };
				tMessage.TestIndex = baseTest.Index;
				_scheduler.SendNodeSelectMessage(tMessage);
			}
		}
		catch
		{
		}
	}

	private ArrayList GetPropertyList(TestProperties properties)
	{
		ArrayList arrayList = new ArrayList();
		PropertyGrid propertyGrid = new PropertyGrid();
		propertyGrid.SelectedObject = properties;
		Attribute[] array = new Attribute[propertyGrid.BrowsableAttributes.Count];
		propertyGrid.BrowsableAttributes.CopyTo(array, 0);
		PropertyDescriptorCollection properties2 = propertyGrid.SelectedTab.GetProperties(propertyGrid.SelectedObject, array);
		foreach (PropertyDescriptor item in properties2)
		{
			PropertyValue propertyValue = default(PropertyValue);
			propertyValue.PropertyName = item.Name;
			propertyValue.Value = item.GetValue(propertyGrid.SelectedObject);
			arrayList.Add(propertyValue);
		}
		return arrayList;
	}

	private void SendParamUpdateToPlugins(object paramsChangedArgs)
	{
		try
		{
			object[] array = (object[])paramsChangedArgs;
			ParamViewPlugIn paramViewPlugIn = (ParamViewPlugIn)array[0];
			List<ParamValue> changedParams = (List<ParamValue>)array[1];
			paramViewPlugIn.ParametersUpdated(changedParams);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SendParamUpdateToPlugins failed, " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void InitRegistryTree()
	{
		RegistryRoot.scheduler = _scheduler;
		_ = (QTMThisPCTarget)RegistryRoot.Add("This PC", QTMTargetType.ThisPC);
		Registries.Add(RegistryRoot);
		RegistryRoot.Expanded = true;
		RegistryTreeEditor = new RegistryTreeEditor(treeRegistry);
		RegistryTreeEditor.AfterContainerNameEdit += RegistryTreeEditor_AfterContainerNameEdit;
	}

	public void OnPropChanged(PropertyValueChangedEventArgs e)
	{
		TraceMessage.Write(ToString(), "OnPropChanged", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count <= 0)
			{
				return;
			}
			BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
			ttdPropView.CurrentNode = baseTest;
			if (baseTest is FolderTest)
			{
				UpdateLoopFolderIcons((FolderTest)baseTest);
			}
			ValidateCleanupFolderProperty(baseTest);
			if (baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count > 0)
			{
				baseTest.OnPropChanged(e);
				ApplyLeftIcons(baseTest);
				switch (e.ChangedItem.Label)
				{
				case "ToolTest":
				case "TreeMustRun":
				case "FolderMustRun":
				case "TestResultBasedOnLimits":
				case "DataLoggingOnlyOnFailure":
				case "TestTimeOut":
				case "IsSetupFolder":
				case "LoggingEnabled":
				case "SkipWhenLinked":
				case "IsCleanupFolder":
					ApplyFolderProperties(((FolderTest)baseTest).TestList.ToList(), e);
					break;
				}
				FolderTest folderTest = baseTest as FolderTest;
				if (e.ChangedItem.Label == "LinkLocation" && folderTest.FolderProperties.LinkLocation != e.OldValue.ToString())
				{
					bool flag = false;
					bool flag2 = false;
					string pathToConvert = e.OldValue.ToString();
					string linkLocation = folderTest.FolderProperties.LinkLocation;
					pathToConvert = PathUtils.ConvertToAbsolute(TreeName, pathToConvert);
					linkLocation = PathUtils.ConvertToAbsolute(TreeName, linkLocation);
					if (!File.Exists(linkLocation))
					{
						DialogResult dialogResult = AppMessageDialog.Show("The linked tree location does not exist, would you like to browse for it?\nSelecting No will revert back to the previous location.", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, DialogResult.No, MessageDialogType.Warning);
						if (dialogResult == DialogResult.Yes)
						{
							OpenFileDialog openFileDialog = new OpenFileDialog();
							openFileDialog.CheckFileExists = true;
							openFileDialog.FilterIndex = 1;
							openFileDialog.RestoreDirectory = true;
							openFileDialog.Filter = "QSPR test tree files (*.cxtt, *.xtt)|*.cxtt;*.xtt|All files (*.*)|*.*";
							if (linkLocation != null)
							{
								if (Path.IsPathRooted(linkLocation))
								{
									openFileDialog.InitialDirectory = Path.GetDirectoryName(linkLocation);
								}
								else
								{
									openFileDialog.InitialDirectory = Environment.CurrentDirectory;
								}
							}
							if (openFileDialog.ShowDialog() == DialogResult.OK)
							{
								linkLocation = openFileDialog.FileName;
								folderTest.FolderProperties.LinkLocation = linkLocation;
								flag2 = true;
							}
							else
							{
								flag = true;
							}
						}
						else
						{
							flag = true;
						}
					}
					if (flag)
					{
						folderTest.FolderProperties.LinkLocation = e.OldValue.ToString();
						flag2 = true;
					}
					else if (!LinkedTree.AreChecksumsEqual(LinkedTree.GetFileHash(pathToConvert), LinkedTree.GetFileHash(linkLocation)))
					{
						AppMessageDialog.Show("The linked tree location has changed and will be updated.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Information);
						UpdateLinkedTrees(TestTreeSelectionManager.SelectedTests[0], reLink: true, openTree: false, userChangedLink: true);
					}
					if (flag2)
					{
						TestTreeSelectionManager.ClearSelections();
						TestTreeSelectionManager.SelectTest(baseTest);
					}
				}
			}
			else
			{
				try
				{
					baseTest.OnPropChanged(e);
					ApplyLeftIcons(baseTest);
				}
				catch (Exception ex)
				{
					AppMessageDialog.Show(ex.Message, "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Exception);
				}
			}
			if (e.ChangedItem.Label == "TestName")
			{
				GlobalStatus.RegistrationStatus.TreeChanged = true;
				RefreshTreeViewList(Tests.ToList());
				UpdateLoopsTestName(baseTest);
			}
			bool flag3 = (e.ChangedItem.Label == "BreakPoint") | (e.ChangedItem.Label == "LoggingEnabled") | (e.ChangedItem.Label == "Comment");
			if (baseTest is FolderTest && e.ChangedItem.Label == "ConfigLocation")
			{
				((FolderTest)baseTest).FolderProperties.LinkConfigLocationEdited = true;
			}
			TreeChanged = true;
			if (!flag3)
			{
				GlobalStatus.RegistrationStatus.TreeChanged = true;
			}
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "OnPropChanged " + ex2.Message, TraceMessageType.Exception);
		}
	}

	public void ApplyFolderProperties(List<BaseTest> tc, PropertyValueChangedEventArgs e)
	{
		TraceMessage.Write(ToString(), "ApplyFolderProperties", TraceMessageType.Trace);
		try
		{
			foreach (BaseTest item in tc)
			{
				if (item is FolderTest && ((FolderTest)item).TestList.Count > 0)
				{
					item.OnPropChanged(e);
					ApplyLeftIcons(item);
					switch (e.ChangedItem.Label)
					{
					case "ToolTest":
					case "TreeMustRun":
					case "FolderMustRun":
					case "TestResultBasedOnLimits":
					case "DataLoggingOnlyOnFailure":
					case "TestTimeOut":
					case "IsSetupFolder":
					case "LoggingEnabled":
					case "SkipWhenLinked":
						ApplyFolderProperties(((FolderTest)item).TestList.ToList(), e);
						break;
					}
				}
				else
				{
					item.OnPropChanged(e);
					ApplyLeftIcons(item);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ApplyFolderProperties " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void UpdateLoopsTestName(BaseTest test)
	{
		try
		{
			foreach (string loopLink in test.Properties.LoopLinks)
			{
				if (!TestNodesColl.ContainsKey(loopLink))
				{
					continue;
				}
				BaseTest baseTest = TestNodesColl[loopLink];
				FolderTest folderTest = (FolderTest)baseTest;
				foreach (LoopCondition loopCondition in folderTest.FolderProperties.Scenarios.LoopConditions)
				{
					if (loopCondition.TestIndex == test.Index)
					{
						loopCondition.TestName = test.Properties.TestName;
					}
				}
			}
		}
		catch
		{
		}
	}

	private void ValidateCleanupFolderProperty(BaseTest treeNode)
	{
		if (!(treeNode is FolderTest))
		{
			return;
		}
		if (DoesOtherCleanupFolderExist(treeNode) && ((FolderTest)treeNode).FolderProperties.IsCleanupFolder)
		{
			((FolderTest)treeNode).FolderProperties.IsCleanupFolder = false;
			AppMessageDialog.Show("Only 1 cleanup folder can be added to a tree.", "Cleanup folder already exists", MessageBoxButtons.OK, DialogResult.OK, MessageDialogType.Information);
		}
		else if (((FolderTest)treeNode).FolderProperties.IsCleanupFolder)
		{
			if (treeNode.Parent.Parent != null || IsBeforeNonCleanupFolder(treeNode))
			{
				DialogResult dialogResult = AppMessageDialog.Show("Cleanup folder must be located at the end of the root.\nDo you want to move this folder to the end of the root.\n\n(Hitting No will reset the cleanup folder property to false)", "Invalid cleanup folder location.", MessageBoxButtons.YesNo, DialogResult.Yes, MessageDialogType.Information);
				if (dialogResult == DialogResult.No)
				{
					((FolderTest)treeNode).FolderProperties.IsCleanupFolder = false;
				}
				else
				{
					MoveCleanupFolderNode(treeNode);
				}
			}
		}
		else if (IsAfterCleanupFolder(treeNode))
		{
			DialogResult dialogResult2 = AppMessageDialog.Show("Removing the cleanup folder property will move this folder ahead of the remaining cleanup folder(s).\n\nDo you want to remove the cleanup property and move this folder?\n(Hitting no will keep the cleanup property set to true and not move the folder)", "Invalid cleanup folder location.", MessageBoxButtons.YesNo, DialogResult.Yes, MessageDialogType.Information);
			if (dialogResult2 == DialogResult.No)
			{
				((FolderTest)treeNode).FolderProperties.IsCleanupFolder = true;
			}
			else
			{
				MoveCleanupFolderNode(treeNode);
			}
		}
	}

	private void MoveCleanupFolderNode(BaseTest treeNode)
	{
		RootTest root = Root;
		treeNode.CreateLoopParentList(dListGlobal);
		ArrayList arrayList = new ArrayList();
		arrayList.Add(treeNode);
		RemoveLoopTests(dListGlobal);
		RemoveLoopLinkTest(arrayList);
		BaseTest baseTest = treeNode.Clone();
		((FolderTest)baseTest).FolderProperties.IsCleanupFolder = true;
		treeNode.Parent.TestList.Remove(treeNode);
		AddNewNode(root, baseTest, Position.Last);
		RefreshTreeViewList(Root.TestList.ToList());
		TestTreeSelectionManager.SelectTest(baseTest);
		CheckBranchOnTestIndex(treeNode, root);
		ResetTestTree(baseTest);
	}

	private void CheckBranchOnTestIndex(BaseTest test, BaseTest DroppedNode)
	{
		try
		{
			if (test.Properties.PostCondition != null && test.Properties.PostCondition.Action == PostConditionActions.Branch && test.Properties.PostCondition.BranchOnTestName != null)
			{
				if (test.Properties.PostCondition.BranchOnTestName.Length > 0)
				{
					if (test.Properties.PostCondition.BranchTestIndex == null || (test.Properties.PostCondition.BranchTestIndex != null && test.Properties.PostCondition.Enabled && test.Properties.PostCondition.BranchTestIndex.Length == 0) || test.Index != null)
					{
						try
						{
							string branchOnTestName = test.Properties.PostCondition.BranchOnTestName;
							SearchForValidPostBranchIndex(test, test.Properties.PostCondition.BranchTestIndex, branchOnTestName);
						}
						catch
						{
						}
					}
				}
				else if (test.Properties.StopOnError != 0)
				{
					test.Properties.PostCondition = null;
				}
				else
				{
					string text = "UpdateBranchOnTestIndex - BranchName not set for test " + test.Properties.TestName;
					AppMessageDialog.Show(text, DialogResult.OK, MessageDialogType.Exception);
				}
			}
			if (test.Properties.PreCondition != null && test.Properties.PreCondition.Conditions != null && test.Properties.PreCondition.Conditions.Count > 0)
			{
				foreach (BaseCondition condition in test.Properties.PreCondition.Conditions)
				{
					try
					{
						if (condition is TestPreCondition && condition.TestConditionType != ConditionType.None && test.Properties.PreCondition.Enabled && condition.TestConditionType != ConditionType.GlobalVariables && ((TestPreCondition)condition).TestIndex != "")
						{
							if (DroppedNode is RootTest)
							{
								SearchForValidPreBranchIndex(test, ((TestPreCondition)condition).TestIndex, DroppedNode.Index, isRoot: true);
							}
							else
							{
								SearchForValidPreBranchIndex(test, ((TestPreCondition)condition).TestIndex, DroppedNode.Index, isRoot: false);
							}
						}
					}
					catch
					{
					}
				}
			}
			if (!(test is FolderTest) || ((FolderTest)test).TestList.Count <= 0)
			{
				return;
			}
			foreach (BaseTest test2 in ((FolderTest)test).TestList)
			{
				CheckBranchOnTestIndex(test2, DroppedNode);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateBranchOnTestIndexForQSPR2Tree " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void SearchForValidPostBranchIndex(BaseTest test, string branchTestIndex, string branchTestName)
	{
		BaseTest baseTest = TestNodesColl[test.Index];
		TestTreeSelectionManager.ClearSelections();
		TestTreeSelectionManager.SelectTest(baseTest);
		BaseTest baseTest2 = FindNodeByGUID(branchTestIndex);
		if (!NodeRelativePosition(test.Index, baseTest2.Index))
		{
			string text = "The test " + test.Properties.TestName + " has a branch to test " + branchTestName + " that is not found or is invalid.";
			AppMessageDialog.Show(text, DialogResult.OK, MessageDialogType.Exception);
			test.Properties.Comment += text;
		}
	}

	private bool NodeRelativePosition(string firstGuid, string secondGuid)
	{
		var source = Tests[0].Descendants().Select((BaseTest n, int index) => new
		{
			Index = index,
			GUID = n.Index
		});
		var source2 = source.ToList();
		return source2.First(p => p.GUID == firstGuid).Index > source2.First(p => p.GUID == secondGuid).Index;
	}

	private BaseTest FindNodeByGUID(string guid, BaseTest node = null)
	{
		if (node == null)
		{
			node = Root;
		}
		return node.Descendants().FirstOrDefault((BaseTest p) => p.Index == guid);
	}

	private void SearchForValidPreBranchIndex(BaseTest test, string branchTestIndex, string droppedNodeIndex, bool isRoot)
	{
		List<string> list = new List<string>();
		bool currentNodeFound = false;
		if (isRoot)
		{
			list.Add(droppedNodeIndex);
		}
		else
		{
			GetListOfNodesForPreCond((FolderTest)Tests[0], droppedNodeIndex, list, ref currentNodeFound);
		}
		if (!list.Contains(branchTestIndex))
		{
			string text = "The test " + test.Properties.TestName + " has an invalid PreCondtion.";
			AppMessageDialog.Show(text, DialogResult.OK, MessageDialogType.Exception);
			test.Properties.Comment += text;
		}
	}

	private bool IsBeforeNonCleanupFolder(BaseTest treeNode)
	{
		for (int num = treeNode.Parent.TestList.Count - 1; num >= 0; num--)
		{
			BaseTest baseTest = treeNode.Parent.TestList[num];
			if (baseTest == treeNode)
			{
				return false;
			}
			if (baseTest is FolderTest && !((FolderTest)baseTest).FolderProperties.IsCleanupFolder)
			{
				return true;
			}
		}
		return false;
	}

	private bool IsAfterCleanupFolder(BaseTest treeNode)
	{
		foreach (BaseTest test in treeNode.Parent.TestList)
		{
			if (test == treeNode)
			{
				return false;
			}
			if (test is FolderTest && ((FolderTest)test).FolderProperties.IsCleanupFolder)
			{
				return true;
			}
		}
		return false;
	}

	private bool DoesOtherCleanupFolderExist(BaseTest treeNode)
	{
		foreach (BaseTest test in Root.TestList)
		{
			if (test != treeNode && test is FolderTest && ((FolderTest)test).FolderProperties.IsCleanupFolder)
			{
				return true;
			}
		}
		return false;
	}

	private void GetListOfNodesForPreCond(FolderTest folder, string testIndex, List<string> nodeCollection, ref bool currentNodeFound)
	{
		try
		{
			foreach (BaseTest test in folder.TestList)
			{
				if (!currentNodeFound)
				{
					if (testIndex == test.Index)
					{
						currentNodeFound = true;
						break;
					}
					nodeCollection.Add(test.Index);
					if (test is FolderTest)
					{
						GetListOfNodesForPreCond((FolderTest)test, testIndex, nodeCollection, ref currentNodeFound);
					}
					continue;
				}
				break;
			}
		}
		catch
		{
		}
	}

	public void RefreshTreeViewList(List<BaseTest> tc)
	{
		TraceMessage.Write(ToString(), "RefreshTreeViewList", TraceMessageType.Trace);
		bool flag = false;
		for (int i = 0; i < tc.Count; i++)
		{
			try
			{
				BaseTest baseTest = tc[i];
				if (baseTest != null)
				{
					TestNodesColl[baseTest.Index] = baseTest;
				}
				if (baseTest.Parent != null)
				{
					if (!flag)
					{
						baseTest.Parent.Clear();
						flag = true;
					}
					baseTest.Parent.Add(baseTest);
					if (baseTest.Parent is RootTest)
					{
						RootTest rootTest = baseTest.Parent as RootTest;
						TestNodesColl[rootTest.Index] = baseTest.Parent;
					}
				}
				if (baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count == 0)
				{
					baseTest.Clear();
					((FolderTestProperties)((FolderTest)baseTest).Properties).Scenarios = null;
				}
				if (baseTest is FolderTest)
				{
					RefreshTreeViewList(((FolderTest)baseTest).TestList.ToList());
				}
			}
			catch (Exception ex)
			{
				TraceMessage.Write(ToString(), "RefreshTreeViewList " + ex.Message, TraceMessageType.Exception);
			}
		}
		TreeChanged = true;
	}

	private void RemoveLoopTests(ArrayList dList)
	{
		TraceMessage.Write(ToString(), "RemoveLoopTests", TraceMessageType.Trace);
		try
		{
			foreach (DeletedLink d in dList)
			{
				BaseTest baseTest = TestNodesColl[d.ParentIndex];
				if (baseTest != null)
				{
					FolderTest folderTest = (FolderTest)baseTest;
					folderTest.RemoveLoopTests(d.ChildIndex);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "RemoveLoopTests " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void ttdLoopView_ShowLoopSetupEvent(object sender, EventArgs e)
	{
		LoopSetup();
	}

	private void ttdLoopView_OnLoopSelectionChanged(object sender, EventArgs e)
	{
		GlobalStatus.RegistrationStatus.LoopSelectionChanged = true;
		TreeChanged = true;
	}

	private void ttdNotes_OnNotesChanged(string newNotes)
	{
		TreeChanged = true;
	}

	private bool LoopSetup()
	{
		if (QSecurity.LockedQGroup)
		{
			return false;
		}
		TraceMessage.Write(ToString(), "LoopSetup", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0 && TestTreeSelectionManager.SelectedTests[0].Parent != null)
			{
				LoopSetup loopSetup = new LoopSetup();
				using (loopSetup)
				{
					ttdLoopView.CurrTestPath = "";
					if (TestTreeSelectionManager.SelectedTests[0] is FolderTest)
					{
						FolderTest loopFolder = (loopSetup.LoopFolder = (FolderTest)TestTreeSelectionManager.SelectedTests[0]);
						if (loopSetup.ShowDialog() == DialogResult.OK)
						{
							UpdateLoopFolderIcons(loopFolder);
							return true;
						}
					}
					else
					{
						FolderTest folderTest2 = new FolderTest("TempFolder");
						BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
						FolderTest parent = baseTest.Parent;
						if (baseTest.Properties.LinkNode)
						{
							folderTest2.Properties.LinkNode = true;
						}
						folderTest2.AddDummyTest(baseTest);
						folderTest2.Properties.Scenarios = baseTest.Properties.Scenarios;
						loopSetup.LoopFolder = folderTest2;
						loopSetup.singleTestSelected = true;
						if (loopSetup.ShowDialog() == DialogResult.OK)
						{
							baseTest.Properties.Scenarios = folderTest2.Properties.Scenarios;
							UpdateLoopFolderIcons(folderTest2);
						}
						baseTest.Parent = parent;
					}
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "LoopSetup " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void UpdateLoopFolderIcons(FolderTest loopFolder)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				UpdateLoopFolderIcons(loopFolder);
			});
			return;
		}
		TreeChanged = true;
		ttdPropView.CurrentNode = TestTreeSelectionManager.SelectedTests[0];
		ttdLoopView.CurrentTest = TestTreeSelectionManager.SelectedTests[0];
		loopFolder.UpdateLoopLinks();
		ResetTestTree(TestTreeSelectionManager.SelectedTests[0]);
		ApplyLeftIcons(TestTreeSelectionManager.SelectedTests[0]);
	}

	public void InitTestTree()
	{
		TraceMessage.Write(ToString(), "InitTestTree", TraceMessageType.Trace);
		try
		{
			bLoadingTree = true;
			if (Root != null)
			{
				Root.RootProperties.OnTreeTypeChanged -= RootProperties_OnTreeTypeChanged;
			}
			TreeDisplayName = "";
			Tests.Clear();
			Root = new RootTest("ROOT");
			Root.Properties.CheckStateTest = CheckState.Checked;
			Root.Properties.Expanded = true;
			Root.ConfigureNodeImage("/QSPR;component/Icons/Root.png", "/QSPR;component/Icons/Root.png");
			Root.Scheduler = _scheduler;
			TestNodesColl.Add(Root.Index, Root);
			Tests.Add(Root);
			TestTreeSelectionManager = new TestTreeSelectionManager(Root, testTreeView);
			TestTreeSelectionManager.FirstSelectedTestChanged += TestTreeSelectionManager_FirstSelectedTestChanged;
			TestTreeEditor = new TestTreeEditor(testTreeView);
			TestTreeEditor.BeforeTestNameEdit += TestTreeEditor_BeforeTestNameEdit;
			TestTreeEditor.AfterTestNameEdit += TestTreeEditor_AfterTestNameEdit;
			TestTreeEditor.BeforeTestCut += TestTreeEditor_BeforeTestCut;
			TestTreeEditor.AfterTestCut += TestTreeEditor_AfterTestCut;
			TestTreeEditor.BeforeTestCopy += TestTreeEditor_BeforeTestCopy;
			TestTreeEditor.AfterTestCopy += TestTreeEditor_AfterTestCopy;
			FolderTest folderTest = new FolderTest("StartUp");
			folderTest.Properties.CheckStateTest = CheckState.Checked;
			folderTest.Properties.Expanded = true;
			folderTest.ConfigureNodeImage("/QSPR;component/Icons/folder-closed.png", "/QSPR;component/Icons/folder-open.png");
			if (!AddNewNode(Root, folderTest, Position.First))
			{
				AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			TestNodesColl.Clear();
			XmlTreeName = "";
			TreeChanged = false;
			CopiedNodes = null;
			TestTreeSelectionManager.SelectTest(Root);
			ttdPropView.CurrentNode = Root;
			ttdParameterView.Parameters = null;
			TTInfo = new TestTreeInfo();
			GlobalStatus.StopOnFirstTestFailure = false;
			GlobalStatus.PauseOnTestFailure = false;
			if (_scheduler.QTMData.WConfig.ResetGlobalVariables)
			{
				QTMGlobalVariable.GVariables = new Hashtable();
				_scheduler.QTMData.WConfig.SearchString = _scheduler.QTMData.WConfig.SearchString;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "InitTestTree " + ex.Message, TraceMessageType.Exception);
		}
		finally
		{
			bLoadingTree = false;
		}
	}

	private void TestTreeEditor_AfterTestCopy(object sender, TestTreeNodeEventArgs e)
	{
		TraceMessage.Write(ToString(), "ultraTreeTTDView_AfterCopy", TraceMessageType.Trace);
		try
		{
			ArrayList arrayList = new ArrayList();
			foreach (BaseTest test in e.Tests)
			{
				arrayList.Add(test.Clone());
			}
			CopiedNodes = arrayList;
			ArrayList arrayList2 = new ArrayList();
			foreach (BaseTest copiedNode in CopiedNodes)
			{
				BaseTest baseTest2 = copiedNode.Clone();
				baseTest2.Parent = null;
				baseTest2.CreateLoopParentList(arrayList2);
			}
			if (arrayList2.Count <= 0)
			{
				return;
			}
			foreach (DeletedLink item in arrayList2)
			{
				foreach (BaseTest copiedNode2 in CopiedNodes)
				{
					copiedNode2.RemoveLoopLinkTest(item.ParentIndex);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ultraTreeTTDView_AfterCopy " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void TestTreeEditor_BeforeTestCopy(object sender, TestTreeNodeEventArgs e)
	{
	}

	private void TestTreeEditor_AfterTestCut(object sender, TestTreeNodeEventArgs e)
	{
		TraceMessage.Write(ToString(), "ultraTreeTTDView_AfterCut", TraceMessageType.Trace);
		try
		{
			FolderTest folderTest = new FolderTest();
			ArrayList arrayList = new ArrayList();
			foreach (BaseTest test in e.Tests)
			{
				if (TestTreeSelectionManager.SelectedTests.Contains(test))
				{
					TestTreeSelectionManager.SelectedTests.Remove(test);
				}
				arrayList.Add(test.Clone());
				folderTest = test.Parent;
			}
			CopiedNodes = arrayList;
			if (folderTest.TestList.Count > 0)
			{
				UpdateCheckState(folderTest.TestList[0]);
			}
			else
			{
				folderTest.Properties.CheckStateTest = CheckState.Unchecked;
			}
			RefreshTreeViewList(folderTest.TestList.ToList());
			RemoveLoopTests(dListGlobal);
			RemoveLoopLinkTest(CopiedNodes);
			dListGlobal = new ArrayList();
			RefreshTreeViewList(Root.TestList.ToList());
			ResetTestTree(Root);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ultraTreeTTDView_AfterCut " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void TestTreeEditor_BeforeTestCut(object sender, TestTreeNodeEventArgs e)
	{
		TraceMessage.Write(ToString(), "Test Tree Before Node Cut", TraceMessageType.Trace);
		try
		{
			ArrayList arrayList = new ArrayList();
			foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
			{
				BaseTest baseTest = selectedTest;
				BaseTest baseTest2 = baseTest.Clone();
				baseTest2.Parent = null;
				baseTest2.CreateLoopParentList(arrayList);
			}
			if (arrayList.Count > 0)
			{
				string text = "";
				foreach (DeletedLink item in arrayList)
				{
					text = text + "\n" + TestNodesColl[item.ChildIndex].UltraTreeNodePath;
				}
				DialogResult dialogResult = AppMessageDialog.Show("Following Tests will be deleted from the Loop Conditions: " + text + "\nDo you want to continue..", "Loop Tests Deletion", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, DialogResult.OK, MessageDialogType.Warning);
				if (dialogResult == DialogResult.Cancel)
				{
					RefreshTreeViewList(Root.TestList.ToList());
					e.Cancel = true;
				}
			}
			dListGlobal = arrayList;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Test Tree Before Node Cut " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void TestTreeEditor_AfterTestNameEdit(object sender, TestTreeNodeEventArgs e)
	{
		if (e.Tests.Count > 0)
		{
			BaseTest baseTest = e.Tests[0];
			TreeChangedDataCollection = true;
			GlobalStatus.RegistrationStatus.TreeChanged = true;
			TreeChanged = true;
			UpdateLoopsTestName(baseTest);
			ttdPropView.CurrentNode = baseTest;
		}
	}

	private void TestTreeEditor_BeforeTestNameEdit(object sender, TestTreeNodeEventArgs e)
	{
		if (e.Tests.Count > 0)
		{
			BaseTest baseTest = e.Tests[0];
			if (GlobalStatus.TestRunning || (baseTest.Properties.LinkNode && baseTest.Properties.IsLinkActive == true) || !QSecurity.IsTechnician || baseTest is TestCaseTest)
			{
				e.Cancel = true;
			}
		}
	}

	private void TestTreeSelectionManager_FirstSelectedTestChanged(object sender, RoutedPropertyChangedEventArgs<BaseTest> e)
	{
		BaseTest newValue = e.NewValue;
		UpdateTestTreeSelections(newValue);
		if (TestTreeSelectionManager.SelectedTests.Count != 1 || _bLoadingTree)
		{
			return;
		}
		ThreadPool.QueueUserWorkItem(SendNodeSelectedMessage, newValue);
		if (ParamPlugInsColl.Count <= 0)
		{
			return;
		}
		ParamViewPlugIn paramViewPlugIn = null;
		if (!(newValue is FolderTest))
		{
			int num = 0;
			foreach (ParamViewPlugIn value in ParamPlugInsColl.Values)
			{
				if (value.TestList.Count <= 0)
				{
					continue;
				}
				switch (MatchString(value.TestList, newValue.Properties.RealName))
				{
				case 1:
					paramViewPlugIn = value;
					goto end_IL_00cc;
				case 2:
					if (num == 0 || num == 3)
					{
						num = 2;
						paramViewPlugIn = value;
					}
					break;
				case 3:
					if (num == 0)
					{
						num = 3;
						paramViewPlugIn = value;
					}
					break;
				}
				continue;
				end_IL_00cc:
				break;
			}
		}
		if (paramViewPlugIn != null)
		{
			ShowParamView(paramViewPlugIn.Caption, userSelectedDropdown: false);
		}
		else
		{
			ShowParamView("Parameters", userSelectedDropdown: false);
		}
	}

	public bool AddNewNode(BaseTest ParentNode, BaseTest NewNode, Position insertPosition, bool isTestStep = false)
	{
		bool flag = false;
		bool flag2 = false;
		int num = 0;
		if (NewNode is FolderTest)
		{
			if (NewNode is TestCaseTest)
			{
				NewNode.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTestCase.png", "/QSPR;component/Icons/TestTreeTestCase.png");
			}
			else
			{
				NewNode.ConfigureNodeImage("/QSPR;component/Icons/folder-closed.png", "/QSPR;component/Icons/folder-open.png");
				if ((NewNode as FolderTest).FolderProperties.LinkRoot)
				{
					NewNode.TestUserInterfaceProperties.IsLocked = true;
				}
			}
		}
		else
		{
			NewNode.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTest.png", "/QSPR;component/Icons/TestTreeTest.png");
			if (NewNode.Properties.LinkNode && NewNode.Properties.IsLinkActive == true)
			{
				NewNode.TestUserInterfaceProperties.IsLocked = true;
			}
		}
		if (ParentNode is RootTest)
		{
			if (ParentNode.Properties.Expanded)
			{
				if (insertPosition == Position.Last)
				{
					num = ((RootTest)ParentNode).TestList.Count;
					flag = true;
				}
				else
				{
					num = 0;
					flag = true;
				}
			}
			else
			{
				num = ((RootTest)ParentNode).TestList.Count;
				flag = true;
			}
		}
		else if (ParentNode is FolderTest)
		{
			if (((FolderTest)ParentNode).Properties.Expanded || ((FolderTest)ParentNode).TestList.Count == 0)
			{
				switch (insertPosition)
				{
				case Position.Last:
					num = ((FolderTest)ParentNode).TestList.Count;
					flag = true;
					break;
				case Position.First:
					num = 0;
					flag = true;
					break;
				default:
					if (ParentNode.Parent == Root && !(NewNode is FolderTest))
					{
						return false;
					}
					switch (insertPosition)
					{
					case Position.NextSibling:
						num = ParentNode.Parent.TestList.IndexOf(ParentNode) + 1;
						flag2 = true;
						break;
					case Position.PreviousSibling:
						num = ParentNode.Parent.TestList.IndexOf(ParentNode);
						flag2 = true;
						break;
					}
					break;
				}
			}
			else if (ParentNode.Parent is RootTest && !(NewNode is FolderTest))
			{
				if (insertPosition == Position.NextSibling || insertPosition == Position.PreviousSibling)
				{
					return false;
				}
				num = 0;
				flag = true;
			}
			else
			{
				switch (insertPosition)
				{
				case Position.NextSibling:
					num = ParentNode.Parent.TestList.IndexOf(ParentNode) + 1;
					flag2 = true;
					break;
				case Position.PreviousSibling:
					num = ParentNode.Parent.TestList.IndexOf(ParentNode);
					flag2 = true;
					break;
				default:
					num = ParentNode.Parent.TestList.IndexOf(ParentNode) + 1;
					ParentNode = ParentNode.Parent;
					flag = true;
					break;
				}
			}
		}
		else
		{
			switch (insertPosition)
			{
			case Position.NextSibling:
				num = ParentNode.Parent.TestList.IndexOf(ParentNode) + 1;
				flag2 = true;
				break;
			case Position.PreviousSibling:
				num = ParentNode.Parent.TestList.IndexOf(ParentNode);
				flag2 = true;
				break;
			default:
				num = ParentNode.Parent.TestList.IndexOf(ParentNode) + 1;
				ParentNode = ParentNode.Parent;
				flag = true;
				break;
			}
		}
		if (flag)
		{
			if (num > 0)
			{
				BaseTest baseTest = ((FolderTest)ParentNode).TestList[num - 1];
				if (num > 0 && baseTest is FolderTest && ((FolderTest)baseTest).FolderProperties.IsCleanupFolder)
				{
					num--;
				}
			}
			((FolderTest)ParentNode).TestList.Insert(num, NewNode);
			NewNode.Parent = (FolderTest)ParentNode;
		}
		else if (flag2)
		{
			ParentNode.Parent.TestList.Insert(num, NewNode);
			if (ParentNode is FolderTest)
			{
				NewNode.Parent = (FolderTest)ParentNode;
			}
			else
			{
				NewNode.Parent = ParentNode.Parent;
			}
		}
		else
		{
			((FolderTest)ParentNode).TestList.Add(NewNode);
			NewNode.Parent = (FolderTest)ParentNode;
		}
		NewNode.Parent.Properties.Expanded = true;
		GlobalStatus.RegistrationStatus.TreeChanged = true;
		return true;
	}

	public bool ExportNodeToTextFile(ExportNodeInfo exportInfo)
	{
		bool result = false;
		try
		{
			if (Root.TestList.Count > 0 && !string.IsNullOrEmpty(exportInfo.testIndex))
			{
				BaseTest baseTest = TestNodesColl[exportInfo.testIndex];
				if (baseTest != null)
				{
					NodeDetailsForm nodeDetailsForm = new NodeDetailsForm(baseTest, exportInfo.includeProperties, exportInfo.includeParameters, exportInfo.includeGlobalVals, exportInfo.includeNotes, exportInfo.includeLoop);
					return nodeDetailsForm.ExportDataToFile(exportInfo.filePath);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ExportNodeToTextFile failed, " + ex.Message, TraceMessageType.Exception);
			throw ex;
		}
		return result;
	}

	private void CheckBox_Checked(object sender, RoutedEventArgs e)
	{
		System.Windows.Controls.CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
		BaseTest checkNode = checkBox.DataContext as BaseTest;
		try
		{
			if (!bLoadingTree && checkBox.IsLoaded)
			{
				UpdateCheckState(checkNode);
				if (Root.RootProperties.TreeType != QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan)
				{
					TreeChanged = true;
				}
				GlobalStatus.RegistrationStatus.TreeSelectionChanged = true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ultraTreeTTDView_AfterCheck " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
	{
		System.Windows.Controls.CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
		BaseTest checkNode = checkBox.DataContext as BaseTest;
		try
		{
			if (!bLoadingTree && checkBox.IsLoaded)
			{
				UpdateCheckState(checkNode);
				TreeChanged = true;
				GlobalStatus.RegistrationStatus.TreeSelectionChanged = true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ultraTreeTTDView_AfterCheck " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void QSecurity_UserAccessLevelChanged(object sender, UserAccessLevelChangedEventArgs e)
	{
		try
		{
			switch (e.UserAccessLevel)
			{
			case AccessLevel.Operator:
				treeRegistry.IsEnabled = false;
				ttdPropView.EnableControls(enable: false);
				ttdParameterView.ReadOnly = true;
				ttdParameterView.RefreshParamView();
				ttdLoopView.EnableControls(enable: false);
				ttdNotes.EnableControls(enable: false);
				Root.SetReadOnly(isReadOnly: true);
				{
					foreach (ParamViewPlugIn value in ParamPlugInsColl.Values)
					{
						value.Enabled = false;
					}
					break;
				}
			case AccessLevel.Technician:
			case AccessLevel.Engineer:
				treeRegistry.IsEnabled = true;
				ttdPropView.EnableControls(enable: true);
				ttdParameterView.ReadOnly = false;
				ttdParameterView.RefreshParamView();
				ttdLoopView.EnableControls(enable: true);
				ttdNotes.EnableControls(enable: true);
				Root.SetReadOnly(isReadOnly: false);
				{
					foreach (ParamViewPlugIn value2 in ParamPlugInsColl.Values)
					{
						value2.Enabled = true;
					}
					break;
				}
			}
		}
		catch
		{
		}
	}

	public void testTreeView_ContextMenuOpening(object sender, ContextMenuEventArgs e)
	{
		if (QSecurity.LockedQGroup || !QSecurity.IsTechnician)
		{
			e.Handled = true;
		}
	}

	public bool TargetHelper_TargetMessageReceived(object sender, TargetMessageEventsArg e)
	{
		return false;
	}

	public void OnConfigInfo(WSpaceConfig wsc)
	{
		this.wsc = wsc;
		UpdateWorkSpace();
	}

	public void UpdateWorkSpace()
	{
		if (wsc.iconSize != null)
		{
			if (wsc.iconSize == "Large Icons")
			{
				ImageHeight = 30.0;
				ImageWidth = 30.0;
			}
			else
			{
				ImageHeight = 16.0;
				ImageWidth = 16.0;
			}
			ApplyFont(testTreeView, wsc.Font);
			ApplyFont(treeRegistry, wsc.Font);
			TreeItemMargin = new Thickness
			{
				Bottom = wsc.TreeItemMargin
			};
			if (wsc.ShowToolTips)
			{
				Root.UpdateToolTipVisibility(Visibility.Visible);
				RegistryRoot.UpdateToolTipVisibility(Visibility.Visible);
			}
			else
			{
				Root.UpdateToolTipVisibility(Visibility.Hidden);
				RegistryRoot.UpdateToolTipVisibility(Visibility.Hidden);
			}
			ttdParameterView.OnConfigInfo(wsc);
			ttdLoopView.OnConfigInfo(wsc);
		}
	}

	private void ApplyFont(System.Windows.Controls.Control control, Font font)
	{
		control.FontFamily = new System.Windows.Media.FontFamily(font.FontFamily.Name);
		if (font.Italic)
		{
			control.FontStyle = FontStyles.Italic;
		}
		else
		{
			control.FontStyle = FontStyles.Normal;
		}
		if (font.Bold)
		{
			control.FontWeight = FontWeights.Bold;
		}
		else
		{
			control.FontWeight = FontWeights.Normal;
		}
		control.FontSize = (double)font.Size * 96.0 / 72.0;
	}

	public void OnMsg(ArrayList message)
	{
		TraceMessage.Write(ToString(), "OnMsg", TraceMessageType.Trace);
		try
		{
			foreach (MsgData item in message)
			{
				ProcessMessage(item.msgType, item.TestFullPath, item.TestIndex, item.Result, item.ParamResult);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void ProcessMessage(TestMsgType msgType, string strTestFullPath, string testIndex, TestResult Result, object msgDetails)
	{
		TraceMessage.Write(ToString(), "ProcessMessage " + msgType, TraceMessageType.Trace);
		try
		{
			if (currBreakPointNode != null && !GlobalStatus.SecondaryQueueRunning && msgType != TestMsgType.OnTestNodeSelected)
			{
				currBreakPointNode.TestUserInterfaceProperties.BackColor = Colors.Transparent.ToString();
			}
			switch (msgType)
			{
			case TestMsgType.OnTestResult:
			{
				BaseTest baseTest = TestNodesColl[testIndex];
				if (baseTest == null)
				{
					break;
				}
				switch (Result)
				{
				case TestResult.Passed:
					UpdateTestIcon(baseTest, NodeState.Passed);
					UpdateParentIcons(baseTest, NodeState.Passed);
					break;
				case TestResult.Failed:
					UpdateTestIcon(baseTest, NodeState.Failed);
					if (!GlobalStatus.TestMsgHold)
					{
						UpdateParentIcons(baseTest, NodeState.Failed);
					}
					break;
				case TestResult.Exception:
					UpdateTestIcon(baseTest, NodeState.Exception);
					if (!GlobalStatus.TestMsgHold)
					{
						UpdateParentIcons(baseTest, NodeState.Exception);
					}
					break;
				}
				if (testIndex == GlobalStatus.CurrentNodeIndex && GlobalStatus.IsDebugMode)
				{
					UpdateTestTreeSelections(baseTest);
				}
				break;
			}
			case TestMsgType.OnTestStart:
			{
				BaseTest baseTest = TestNodesColl[testIndex];
				if (baseTest != null)
				{
					UpdateTestIcon(baseTest, NodeState.Running);
					UpdateParentIcons(baseTest, NodeState.Running);
				}
				break;
			}
			case TestMsgType.OnDLLLoaded:
			{
				string[] array = strTestFullPath.Split(',');
				string targetName = array[0];
				string text = array[1];
				strTestFullPath = strTestFullPath.Remove(0, targetName.Length + 1);
				strTestFullPath = strTestFullPath.Remove(0, text.Length + 1);
				QTMTestContainer qTMTestContainer = null;
				RegistryRoot.Target.FirstOrDefault((QTMTarget t) => t.Name == targetName);
				if (msgDetails != null && ((DllLoadedDetails)msgDetails).DllPathUpdated)
				{
					text = ((DllLoadedDetails)msgDetails).oldPath;
					qTMTestContainer = (QTMTestContainer)RegistryNodesColl[targetName + text];
				}
				else
				{
					qTMTestContainer = (QTMTestContainer)RegistryNodesColl[targetName + text];
				}
				try
				{
					if (qTMTestContainer != null)
					{
						qTMTestContainer.HideTests = testIndex == "true";
					}
				}
				catch
				{
				}
				UpdateLoadedDLL(qTMTestContainer, strTestFullPath);
				break;
			}
			case TestMsgType.OnLoopStart:
			{
				BaseTest baseTest = TestNodesColl[testIndex];
				if (baseTest != null)
				{
					FolderTest folderTest = new FolderTest();
					folderTest.Root = Root;
					folderTest.TestList.Add((FolderTest)baseTest);
					folderTest.QueueTestCount(0, new ArrayList());
				}
				break;
			}
			case TestMsgType.OnEnqueueTest:
			{
				BaseTest baseTest = TestNodesColl[testIndex];
				if (baseTest != null)
				{
					SetQueuedState(baseTest, 1);
					SetQueuedParentState(baseTest, 1);
					this.Refresh();
				}
				break;
			}
			case TestMsgType.OnDequeueTest:
			{
				BaseTest baseTest = TestNodesColl[testIndex];
				if (baseTest != null)
				{
					SetQueuedState(baseTest, 0);
					SetQueuedParentState(baseTest, 0);
					ResetQueueStateChild(baseTest);
					RefreshTree(testTreeView);
				}
				break;
			}
			case TestMsgType.OnTestSkipped:
			{
				BaseTest baseTest = TestNodesColl[testIndex];
				if (baseTest != null)
				{
					SetQueuedState(baseTest, 0);
					SetQueuedParentState(baseTest, 0);
					ResetQueueStateChild(baseTest);
					baseTest.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/skip.png";
					RefreshTree(testTreeView);
				}
				break;
			}
			case TestMsgType.OnAbort:
			{
				BaseTest baseTest = TestNodesColl[testIndex];
				if (baseTest != null)
				{
					SetAbortState(baseTest);
				}
				break;
			}
			case TestMsgType.OnBreak:
			{
				BaseTest baseTest = TestNodesColl[testIndex];
				if (baseTest != null)
				{
					SetBreakState(baseTest);
				}
				break;
			}
			case TestMsgType.OnUnitEnd:
			case TestMsgType.OnEndOfDebugTesting:
				RefreshTree(testTreeView);
				break;
			case TestMsgType.OnTestNodeSelected:
				try
				{
					MsgData msgData = default(MsgData);
					msgData.msgType = msgType;
					msgData.TestFullPath = strTestFullPath;
					msgData.TestIndex = testIndex;
					msgData.Result = Result;
					msgData.ParamResult = msgDetails;
					ArrayList arrayList = new ArrayList();
					arrayList.Add(msgData);
					foreach (ParamViewPlugIn value in ParamPlugInsColl.Values)
					{
						try
						{
							value.OnMsg(arrayList);
						}
						catch
						{
						}
					}
				}
				catch (Exception ex)
				{
					TraceMessage.Write(ToString(), "ProcessMessage " + ex.Message, TraceMessageType.Exception);
				}
				RefreshTree(testTreeView);
				break;
			case TestMsgType.OnFolderEnd:
				if (Result == TestResult.Skipped)
				{
					BaseTest baseTest = TestNodesColl[testIndex];
					baseTest.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/skip.png";
					RefreshTree(testTreeView);
				}
				break;
			}
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "ProcessMessage " + ex2.Message, TraceMessageType.Exception);
		}
	}

	private void UpdateLoadedDLL(QTMTestContainer containerNode, string listOfTests)
	{
		if (this.InvokeRequired())
		{
			this.Invoke(delegate
			{
				UpdateLoadedDLL(containerNode, listOfTests);
			});
			return;
		}
		TraceMessage.Write(ToString(), "UpdateLoadedDLL", TraceMessageType.Trace);
		try
		{
			if (containerNode == null)
			{
				return;
			}
			QTMTestContainer qTMTestContainer = containerNode;
			qTMTestContainer.Loaded = true;
			qTMTestContainer.CreateTestList(listOfTests);
			if (qTMTestContainer.IsDllPathUpdated && string.Compare(qTMTestContainer.OriginalName, qTMTestContainer.UpdatedDllPathName, ignoreCase: true) != 0)
			{
				containerNode.UserInterfaceProperties.FontColor = Colors.DarkOrange.ToString();
				containerNode.UserInterfaceProperties.FontStyle = FontStyles.Italic;
			}
			else
			{
				containerNode.UserInterfaceProperties.FontColor = Colors.Black.ToString();
			}
			containerNode.UserInterfaceProperties.NodeImageUri = "/QSPR;component/Icons/RegistryTreeLoadedDll.png";
			QTMTestContainer qTMTestContainer2 = containerNode;
			if (qTMTestContainer2.ContainerType == QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTestEx)
			{
				containerNode.UserInterfaceProperties.FontColor = Colors.Chocolate.ToString();
			}
			AddTestNodesToRegistryTree(containerNode);
			containerNode.Expanded = true;
			foreach (QTMTestContainerItem item in containerNode.UserInterfaceProperties.Items)
			{
				SetExpandedAllQTMTestContainerItems(item, expanded: true);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateLoadedDLL " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void SetExpandedAllQTMTestContainerItems(QTMTestContainerItem item, bool expanded)
	{
		item.Expanded = expanded;
		foreach (QTMTestContainerItem item2 in item.Items)
		{
			SetExpandedAllQTMTestContainerItems(item2, expanded);
		}
	}

	private void SetQueuedParentState(BaseTest node, int state)
	{
		if (node.Parent != null)
		{
			SetQueuedState(node.Parent, state);
			SetQueuedParentState(node.Parent, state);
		}
	}

	private bool ResetQueueStateChild(BaseTest node)
	{
		try
		{
			SetQueuedState(node, 0);
			if (node is FolderTest)
			{
				FolderTest folderTest = node as FolderTest;
				foreach (BaseTest test in folderTest.TestList)
				{
					ResetQueueStateChild(test);
				}
			}
		}
		catch
		{
		}
		return true;
	}

	private void RefreshTree(System.Windows.Controls.TreeView tree)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				RefreshTree(tree);
			});
		}
		else
		{
			tree.Refresh();
		}
	}

	private void UpdateParentIcons(BaseTest node, NodeState state)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				UpdateParentIcons(node, state);
			});
			return;
		}
		node.TestUserInterfaceProperties.BackColor = Colors.Transparent.ToString();
		node.TestUserInterfaceProperties.FontWeight = FontWeights.Bold;
		TraceMessage.Write(ToString(), "UpdateParentIcons", TraceMessageType.Trace);
		try
		{
			if (node.Parent != null)
			{
				node.Parent.TestUserInterfaceProperties.FontWeight = FontWeights.Bold;
			}
			if (state == NodeState.Exception || node.Parent.RuntimeAttributes.Exception)
			{
				if (node.Parent != null)
				{
					node.Parent.FolderProperties.Exception = true;
					BaseTest parent = node.Parent;
					parent.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/abort.png";
					parent.TestUserInterfaceProperties.ForeColor = Colors.Red.ToString();
					if (!(parent is RootTest))
					{
						UpdateParentIcons(node.Parent, NodeState.Exception);
					}
				}
			}
			else if (state == NodeState.Failed)
			{
				if (node.Parent == null)
				{
					return;
				}
				node.Parent.FolderProperties.Failed = true;
				if (node.Parent.FolderProperties.Exception)
				{
					node.Parent.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/abort.png";
					node.Parent.TestUserInterfaceProperties.ForeColor = Colors.Red.ToString();
					UpdateParentIcons(node.Parent, NodeState.Exception);
					return;
				}
				BaseTest parent2 = node.Parent;
				parent2.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/failed.png";
				parent2.TestUserInterfaceProperties.ForeColor = Colors.Red.ToString();
				if (!(parent2 is RootTest))
				{
					UpdateParentIcons(node.Parent, NodeState.Failed);
				}
			}
			else if (state == NodeState.Passed)
			{
				if (node.Parent == null)
				{
					return;
				}
				if (node.Parent.FolderProperties.Exception)
				{
					node.Parent.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/abort.png";
					node.Parent.TestUserInterfaceProperties.ForeColor = Colors.Red.ToString();
					UpdateParentIcons(node.Parent, NodeState.Exception);
					return;
				}
				if (!node.Parent.FolderProperties.Failed)
				{
					BaseTest parent3 = node.Parent;
					parent3.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/passed.png";
					if (!(parent3 is RootTest))
					{
						UpdateParentIcons(node.Parent, NodeState.Passed);
					}
					return;
				}
				BaseTest parent4 = node.Parent;
				parent4.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/failed.png";
				parent4.TestUserInterfaceProperties.ForeColor = Colors.Red.ToString();
				if (!(parent4 is RootTest))
				{
					UpdateParentIcons(node.Parent, NodeState.Failed);
				}
			}
			else if (node.Parent != null)
			{
				BaseTest parent5 = node.Parent;
				parent5.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/running.png";
				if (!(parent5 is RootTest))
				{
					UpdateParentIcons(node.Parent, NodeState.Running);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateParentIcons " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void UpdateTestIcon(BaseTest node, NodeState state)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				UpdateTestIcon(node, state);
			});
			return;
		}
		node.TestUserInterfaceProperties.FontWeight = FontWeights.Bold;
		if (node.RuntimeAttributes.Exception || state == NodeState.Exception)
		{
			node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/abort.png";
			node.TestUserInterfaceProperties.ForeColor = Colors.Red.ToString();
		}
		if (state == NodeState.Failed)
		{
			node.TestUserInterfaceProperties.ForeColor = Colors.Red.ToString();
			if (node.RuntimeAttributes.HasPassedOnce)
			{
				node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/pass-fail.png";
			}
			else
			{
				node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/failed.png";
			}
		}
		else if (state == NodeState.Passed)
		{
			if (node.RuntimeAttributes.HasFailedOnce)
			{
				node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/pass-fail.png";
			}
			else if (node.Properties.BookKeeping && !node.Properties.TestResult)
			{
				node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/bookkeepfail.png";
			}
			else
			{
				node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/passed.png";
			}
		}
		else if (state == NodeState.Running)
		{
			node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/running.png";
		}
	}

	private void SetQueuedState(BaseTest node, int state)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				SetQueuedState(node, state);
			});
			return;
		}
		TraceMessage.Write(ToString(), "SetQueuedState" + state + " " + node.Properties.TestName, TraceMessageType.Trace);
		try
		{
			if (!(node is RootTest) || (!(node as RootTest).FolderProperties.Failed && !(node as RootTest).FolderProperties.Exception))
			{
				if (state == 1)
				{
					node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/queue.png";
				}
				else if (state == 0 && node.TestUserInterfaceProperties.StatusImageUri != "/QSPR;component/Icons/failed.png" && node.TestUserInterfaceProperties.StatusImageUri != "/QSPR;component/Icons/passed.png" && node.TestUserInterfaceProperties.StatusImageUri != "/QSPR;component/Icons/abort.png")
				{
					node.TestUserInterfaceProperties.StatusImageUri = "";
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SetQueuedState " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void SetAbortState(BaseTest node)
	{
		try
		{
			node.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/abort.png";
			UpdateParentIcons(node, NodeState.Exception);
			SetNormalState(Root);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SetAbortState : " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void SetBreakState(BaseTest node)
	{
		try
		{
			TraceMessage.Write(ToString(), "SetBreakState for node " + node.TestPath, TraceMessageType.Trace);
			if (currBreakPointNode != null)
			{
				currBreakPointNode.TestUserInterfaceProperties.BackColor = Colors.Transparent.ToString();
			}
			node.TestUserInterfaceProperties.BackColor = Colors.Yellow.ToString();
			currBreakPointNode = node;
			ExpandParent(node);
			if (GlobalStatus.Pause)
			{
				_ = GlobalStatus.SecondaryQueueRunning;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SetBreakState : " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void ExpandParent(BaseTest node)
	{
		if (node.Parent != null)
		{
			ExpandParent(node.Parent);
		}
		node.Properties.Expanded = true;
	}

	private void SetNormalState(BaseTest node)
	{
		if (node is FolderTest)
		{
			FolderTest folderTest = node as FolderTest;
			foreach (BaseTest test in folderTest.TestList)
			{
				SetNormalState(test);
			}
		}
		node.TestUserInterfaceProperties.StatusImageUri = "";
	}

	public bool MenuMessages(string MenuMessage)
	{
		TraceMessage.Write(ToString(), "MenuMessages " + MenuMessage, TraceMessageType.Trace);
		bool result = true;
		try
		{
			switch (MenuMessage)
			{
			case "Enable All Logging":
				EnableLoggingAction(action: true, Root);
				break;
			case "Disable All Logging":
				EnableLoggingAction(action: false, Root);
				break;
			case "Enable All Breakpoints":
				BreakPointAction(BreakPointTypes.Enable, Root);
				break;
			case "Disable All Breakpoints":
				BreakPointAction(BreakPointTypes.Disable, Root);
				break;
			case "DeleteAllBreakpoints":
				if (AppMessageDialog.Show("Do you want to delete all breakpoints?", "QSPR - Delete All Breakpoints", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning) == DialogResult.Yes)
				{
					BreakPointAction(BreakPointTypes.None, Root);
				}
				break;
			case "New":
				result = NewTree();
				break;
			case "Open":
				result = OpenTree();
				break;
			case "Save":
				result = SaveFile(SaveAsFormat.None);
				if (Root.RootProperties.TreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan)
				{
					SaveTestPlan();
				}
				break;
			case "SaveAs":
				result = SaveAsFile(null, saveAsLatestFormat: false);
				break;
			case "Save as Test Plan":
				result = SaveTestPlan();
				break;
			case "Cut":
				result = Cut();
				break;
			case "Copy":
				result = Copy();
				break;
			case "Paste":
				result = PasteNodes();
				break;
			case "Delete":
				result = DeleteNode();
				break;
			case "New Folder":
				result = AddFolder(Position.First);
				break;
			case "Toggle BreakPoint":
				result = ToggleBreakPoint();
				break;
			case "Toggle Logging":
				result = ToggleLogging();
				break;
			case "Text View...":
				result = ShowNodeDetails(TestTreeSelectionManager.SelectedTests[0]);
				break;
			case "Run Test":
				result = RunDebugTests();
				break;
			case "Run Setup Tests":
				result = RunSetupTests();
				break;
			case "Run Tree":
				result = RunTree();
				break;
			case "Rerun":
				result = RunTree(rerun: true);
				break;
			case "Loop Setup":
				result = LoopSetup();
				break;
			case "Stop Tree":
				result = StopTree();
				break;
			case "Stop Test":
				result = StopTest();
				break;
			case "Synchronize":
				result = Synchronize(null);
				break;
			case "Exit":
			case "Save Current Docking":
				ttdParameterView.SaveCurrentDataGridSettings();
				ttdParameterView.SaveLayout();
				foreach (TestCasesPlugin value in TestCasesPluginsColl.Values)
				{
					value.MenuMessages(MenuMessage);
				}
				break;
			case "Reset Tree Icons":
			case "Reset All":
				result = ResetTestTree(Root);
				break;
			case "Reset Test/Folder Icons":
				ResetTestFolder();
				break;
			case "Abort":
				result = AbortTree();
				break;
			case "Pause":
				result = PauseTree();
				break;
			case "Search":
				result = SearchTree();
				break;
			case "SearchSetting":
				result = SearchSetting();
				break;
			case "Refresh":
				result = RefreshTree();
				break;
			case "Add DLL":
			case "Load DLL":
			case "UnLoad DLL":
			case "Delete DLL":
			case "Show Parameters":
			case "Restore Window Layout":
			case "Restore Current Docking":
			case "Tree Edit Mode Layout":
			case "QSPR2.0 Window Layout":
			case "Restore Customized Layout":
			case "Save As Customized Layout":
			case "Simulation Mode":
				break;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "MenuMessages " + ex.Message, TraceMessageType.Exception);
		}
		return result;
	}

	private bool ToggleBreakPoint()
	{
		TraceMessage.Write(ToString(), "InsertBreakPoint", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
				{
					if (selectedTest.Properties.BreakPoint == BreakPointTypes.Enable)
					{
						selectedTest.Properties.BreakPoint = BreakPointTypes.None;
					}
					else
					{
						selectedTest.Properties.BreakPoint = BreakPointTypes.Enable;
					}
					ApplyLeftIcons(selectedTest);
					TreeChanged = true;
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "InsertBreakPoint " + ex.Message, TraceMessageType.Exception);
			return false;
		}
	}

	private bool ToggleLogging()
	{
		TraceMessage.Write(ToString(), "ToggleLogging", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
				{
					selectedTest.Properties.LoggingEnabled = !selectedTest.Properties.LoggingEnabled;
					ApplyLeftIcons(selectedTest);
					TreeChanged = true;
					if (selectedTest is FolderTest)
					{
						bool loggingEnabled = selectedTest.Properties.LoggingEnabled;
						ApplyLoggingProperties(selectedTest, loggingEnabled);
					}
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ToggleLogging " + ex.Message, TraceMessageType.Exception);
			return false;
		}
	}

	public void ApplyLoggingProperties(BaseTest treeNode, bool action)
	{
		TraceMessage.Write(ToString(), "ApplyLoggingProperties", TraceMessageType.Trace);
		try
		{
			if (!(treeNode is FolderTest))
			{
				return;
			}
			foreach (BaseTest test in ((FolderTest)treeNode).TestList)
			{
				BaseTest baseTest = test;
				baseTest.Properties.LoggingEnabled = action;
				ApplyLeftIcons(test);
				if (test is FolderTest && ((FolderTest)test).TestList.Count > 0)
				{
					ApplyLoggingProperties(test, action);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ApplyLoggingProperties " + ex.Message, TraceMessageType.Exception);
		}
	}

	private bool SearchSetting()
	{
		SearchSetting searchSetting = new SearchSetting(_scheduler.QTMData.WConfig);
		if (searchSetting.ShowDialog() == DialogResult.OK)
		{
			SearchTree();
		}
		return true;
	}

	private bool SearchTree()
	{
		try
		{
			string gvValue = "";
			WorkspaceConfig.SearchOptions currentSearchOptions = _scheduler.QTMData.WConfig.CurrentSearchOptions;
			if (currentSearchOptions == WorkspaceConfig.SearchOptions.ParameterName || currentSearchOptions == WorkspaceConfig.SearchOptions.TestName || currentSearchOptions == WorkspaceConfig.SearchOptions.RealName || currentSearchOptions == WorkspaceConfig.SearchOptions.TestErrorCode || currentSearchOptions == WorkspaceConfig.SearchOptions.Comments || currentSearchOptions == WorkspaceConfig.SearchOptions.Registry)
			{
				QTMGlobalVariable.GetGlobalVariable("QSPR_SEARCH", out gvValue);
				if (gvValue == string.Empty && currentSearchOptions != WorkspaceConfig.SearchOptions.Comments)
				{
					AppMessageDialog.Show("Enter Search String in the Global Variable 'QSPR_SEARCH' in the GlobalVariable Window or From the Menu\\edit\\Search Setting", DialogResult.OK, MessageDialogType.Warning);
					QTMGlobalVariable.SetGlobalVariable("QSPR_SEARCH", "");
					return false;
				}
			}
			if (currentSearchOptions == WorkspaceConfig.SearchOptions.Registry)
			{
				SearchRegistry(gvValue);
			}
			else
			{
				if (TestTreeSelectionManager.SelectedTests.Count == 0)
				{
					TestTreeSelectionManager.SelectTest(Root);
				}
				BaseTest currentNode = TestTreeSelectionManager.SelectedTests[0];
				bool flag = false;
				if (!SearchNodes(currentNode, gvValue, currentSearchOptions, childrenOnly: false) && AppMessageDialog.Show("Search completed, do you want to start from the beginning?", "Search Completed", MessageBoxButtons.YesNo, DialogResult.No, MessageDialogType.Warning) == DialogResult.Yes)
				{
					TestTreeSelectionManager.SelectTest(Root);
					SearchTree();
				}
			}
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("Enter Search String in the Global Variable 'QSPR_SEARCH' in the GlobalVariable Window or From the Menu\\edit\\Search Setting.\n Error: " + ex.Message, DialogResult.OK, MessageDialogType.Exception);
		}
		return true;
	}

	private void SearchRegistry(string searchString)
	{
		bool flag = false;
		QTMTestContainerItem qTMTestContainerItem = treeRegistry.SelectedItem as QTMTestContainerItem;
		QTMTest testNode = null;
		QTMTestContainer tContainer = null;
		if (qTMTestContainerItem != null)
		{
			testNode = qTMTestContainerItem.Object as QTMTest;
			if (testNode != null)
			{
				RegistryRoot.GetContainerForTest(testNode.Name, testNode.TargetName, out tContainer);
			}
			else
			{
				RegistryRoot.IsSelected = true;
			}
		}
		if (GetRegistryTestNode(searchString, _scheduler.QTMData.WConfig.SearchCaseMatch, partialMatch: true, ref testNode, ref tContainer))
		{
			foreach (object value in RegistryNodesColl.Values)
			{
				if (value is QTMTestContainerItem qTMTestContainerItem2 && qTMTestContainerItem2.Object == testNode)
				{
					RegistryTreeBrowser.Expand(RegistryRoot);
					RegistryTreeBrowser.ExpandAll(tContainer);
					qTMTestContainerItem2.IsSelected = true;
					break;
				}
			}
			return;
		}
		if (AppMessageDialog.Show("Search completed, do you want to start from the beginning?", "Search Completed", MessageBoxButtons.YesNo, DialogResult.No, MessageDialogType.Warning) == DialogResult.Yes)
		{
			RegistryRoot.IsSelected = true;
			SearchTree();
		}
	}

	private bool RefreshTree()
	{
		bool result = true;
		try
		{
			if (Root != null)
			{
				result = Root.UpdateLoopValues();
			}
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				UpdateTestTreeSelections(TestTreeSelectionManager.SelectedTests[0]);
			}
		}
		catch
		{
		}
		return result;
	}

	private bool AbortTree()
	{
		try
		{
			if (_scheduler.QTMData.WConfig.AskBeforeStoppingTree && DialogResult.No == AppMessageDialog.Show("Are you sure you want to abort the tree?", "QSPR - Abort Tree", MessageBoxButtons.YesNo, DialogResult.Yes, MessageDialogType.Information))
			{
				return false;
			}
			GlobalStatus.Abort = true;
			if (!GlobalStatus.SecondaryQueueRunning)
			{
				GlobalStatus.GlobalTestResult = TestResult.Exception;
				Root.FolderProperties.Failed = true;
				Root.FolderProperties.Exception = true;
				Root.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/abort.png";
				RegistryRoot.MenuMessages("Abort");
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "AbortTree " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private bool StopTree()
	{
		TraceMessage.Write(ToString(), "StopTree", TraceMessageType.Trace);
		try
		{
			if (_scheduler.QTMData.WConfig.AskBeforeStoppingTree && DialogResult.No == AppMessageDialog.Show("Are you sure you want to stop the tree?", "QSPR - Stop Tree", MessageBoxButtons.YesNo, DialogResult.Yes, MessageDialogType.Information))
			{
				return false;
			}
			if (!GlobalStatus.SecondaryQueueRunning)
			{
				GlobalStatus.Pause = false;
				if (currBreakPointNode != null)
				{
					currBreakPointNode.TestUserInterfaceProperties.BackColor = Colors.Transparent.ToString();
				}
				GlobalStatus.Stop = true;
				GlobalStatus.GlobalTestResult = TestResult.Failed;
				Root.FolderProperties.Failed = true;
				Root.TestUserInterfaceProperties.StatusImageUri = "/QSPR;component/Icons/failed.png";
			}
			else
			{
				GlobalStatus.Stop = true;
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "StopTree " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public bool StopTest()
	{
		TraceMessage.Write(ToString(), "StopTest", TraceMessageType.Trace);
		try
		{
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
				baseTest.StopTest();
				return true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "StopTest " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private bool PauseTree()
	{
		TraceMessage.Write(ToString(), "PauseTree", TraceMessageType.Trace);
		try
		{
			GlobalStatus.Pause = !GlobalStatus.Pause;
			if (GlobalStatus.Pause)
			{
				_ = GlobalStatus.SecondaryQueueRunning;
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "PauseTree " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void UpdateTestTreeSelections(BaseTest node)
	{
		try
		{
			if (this.InvokeRequired())
			{
				this.BeginInvoke(delegate
				{
					UpdateTestTreeSelections(node);
				});
				return;
			}
			GlobalStatus.CurrentNodeIndex = node.Index;
			GlobalStatus.CurrentNodePath = node.TestPath;
			node.Properties.TestIndexCopy = node.Index;
			ttdPropView.Enabled = IsEnabled(node);
			ttdPropView.CurrentNode = node;
			ttdNotes.Enabled = IsEnabled(node);
			ttdNotes.CurrentNode = node;
			ttdLoopView.Enabled = IsEnabled(node);
			if (node is FolderTest)
			{
				if (((FolderTest)node).FolderProperties.Scenarios != null)
				{
					ttdLoopView.CurrentTest = node;
				}
				else
				{
					ttdLoopView.CurrentTest = null;
				}
				if ((node.Properties.LinkNode && node.Properties.IsLinkActive == true) || (((FolderTest)node).FolderProperties.LinkRoot && ((FolderTest)node).FolderProperties.IsLinkActive == true))
				{
					ttdParameterView.ReadOnly = true;
					ttdParameterView.IsLinkNode = true;
				}
				else
				{
					ttdParameterView.ReadOnly = Root.TestUserInterfaceProperties.IsReadOnly;
					ttdParameterView.IsLinkNode = false;
				}
				ttdParameterView.IsFolder = true;
				ttdParameterView.TestType = "";
				ttdParameterView.Parameters = null;
				ttdParameterView.CurrTestPath = node.TestPath;
				ttdParameterView.FolderNode = (FolderTest)node;
			}
			else
			{
				ttdParameterView.TestType = node.ToString();
				try
				{
					QTMTestContainer tContainer = new QTMTestContainer();
					RegistryRoot.GetContainerForTest(node.Properties.RealName, node.Properties.TargetName, out tContainer);
					ttdParameterView.TestContainerName = tContainer.Name;
					ttdParameterView.RealName = node.Properties.RealName;
				}
				catch
				{
				}
				if (node.Properties.Scenarios != null && node.Properties.Scenarios.Count > 0)
				{
					ttdLoopView.CurrentTest = node;
				}
				else
				{
					ttdLoopView.CurrentTest = null;
				}
				if (node.Properties.LinkNode && node.Properties.IsLinkActive == true)
				{
					ttdParameterView.ReadOnly = true;
					ttdParameterView.IsLinkNode = true;
				}
				else
				{
					ttdParameterView.ReadOnly = Root.TestUserInterfaceProperties.IsReadOnly;
					ttdParameterView.IsLinkNode = false;
				}
				ttdParameterView.IsFolder = false;
				ttdParameterView.CurrTestPath = node.TestPath;
				ttdParameterView.Test = node;
				if (node is TestCaseTest)
				{
					ttdParameterView.Parameters = (node as TestCaseTest).TestCaseProperties.Parameters;
				}
				else
				{
					ttdParameterView.Parameters = node.Properties.Parameters;
				}
			}
			BaseTest tempNode = node;
			UpdateTestTreeNodeStatus(tempNode);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateTestTreeSelections, Error: " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void UpdateTestTreeNodeStatus(BaseTest tempNode)
	{
		TraceMessage.Write(ToString(), "UpdateTestTreeNodeStatus", TraceMessageType.Trace);
		try
		{
			if (tempNode == Root)
			{
				CurrentTestTreeNodeStatus = TestTreeSelectedNode.RootNode;
			}
			else if (tempNode.Parent == Root)
			{
				CurrentTestTreeNodeStatus = TestTreeSelectedNode.LoopEnabledFolderNode;
			}
			else if (!(tempNode is FolderTest))
			{
				CurrentTestTreeNodeStatus = TestTreeSelectedNode.LoopEnabledFolderNode;
			}
			else if (tempNode is FolderTest && ((FolderTest)tempNode).TestList.Count == 0)
			{
				CurrentTestTreeNodeStatus = TestTreeSelectedNode.LoopDisabledFolderNode;
			}
			else if (tempNode is FolderTest)
			{
				CurrentTestTreeNodeStatus = TestTreeSelectedNode.LoopEnabledFolderNode;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateTestTreeNodeStatus " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void UpdateToolBar(TestTreeSelectedNode nodeStatus)
	{
		TraceMessage.Write(ToString(), "UpdateToolBar", TraceMessageType.Trace);
		try
		{
			ResetToolbar();
			switch (nodeStatus)
			{
			case TestTreeSelectedNode.RootNode:
				SetRootNodeState();
				break;
			}
			if (GlobalStatus.TestRunning)
			{
				menuToolBarManager.SetEnabled("Stop Test", enabledValue: true);
			}
			else
			{
				menuToolBarManager.SetEnabled("Stop Test", enabledValue: false);
			}
			if (TestTreeSelectionManager.SelectedTests.Count != 1)
			{
				return;
			}
			if (TestTreeSelectionManager.SelectedTests[0].Properties.LinkNode && TestTreeSelectionManager.SelectedTests[0].Properties.IsLinkActive == true)
			{
				menuToolBarManager.SetEnabled("Link Tree", enabledValue: false);
			}
			if (!(TestTreeSelectionManager.SelectedTests[0] is FolderTest))
			{
				return;
			}
			FolderTest folderTest = (FolderTest)TestTreeSelectionManager.SelectedTests[0];
			menuToolBarManager.SetEnabled("Update Link(s)", enabledValue: true);
			if (folderTest.FolderProperties.LinkRoot && folderTest.FolderProperties.IsLinkActive == true)
			{
				if (!folderTest.Properties.LinkNode)
				{
					menuToolBarManager.SetEnabled("Unlink Tree", enabledValue: true);
				}
				return;
			}
			if (folderTest.FolderProperties.LinkRoot && folderTest.FolderProperties.IsLinkActive == false)
			{
				menuToolBarManager.SetEnabled("Re-link Tree", enabledValue: true);
			}
			if (folderTest.FolderProperties.LinkNode && folderTest.FolderProperties.IsLinkActive == true)
			{
				menuToolBarManager.SetEnabled("Update Link(s)", enabledValue: false);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "UpdateToolBar " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void SetRootNodeState()
	{
		TraceMessage.Write(ToString(), "SetRootNodeState", TraceMessageType.Trace);
		menuToolBarManager.SetEnabled("Copy", enabledValue: false);
		menuToolBarManager.SetEnabled("Cut", enabledValue: false);
		menuToolBarManager.SetEnabled("Delete Test", enabledValue: false);
		menuToolBarManager.SetEnabled("Loop Setup", enabledValue: false);
		menuToolBarManager.SetEnabled("Link Tree", enabledValue: true);
		menuToolBarManager.SetEnabled("Update Link(s)", enabledValue: true);
		menuToolBarManager.SetEnabled("Unlink Tree", enabledValue: false);
		menuToolBarManager.SetEnabled("Re-link Tree", enabledValue: false);
	}

	private void ResetToolbar()
	{
		TraceMessage.Write(ToString(), "ResetToolbar", TraceMessageType.Trace);
		menuToolBarManager.SetEnabled("Import Test Tree", !QSecurity.LockedQGroup);
		menuToolBarManager.SetEnabled("Rename Test", !QSecurity.LockedQGroup);
		menuToolBarManager.SetEnabled("Loop Setup", !QSecurity.LockedQGroup);
		menuToolBarManager.SetEnabled("Copy", enabledValue: true);
		menuToolBarManager.SetEnabled("Cut", !QSecurity.LockedQGroup);
		menuToolBarManager.SetEnabled("Delete Test", !QSecurity.LockedQGroup);
		menuToolBarManager.SetEnabled("New Folder", !QSecurity.LockedQGroup);
		menuToolBarManager.SetEnabled("Show Parameters", enabledValue: true);
		menuToolBarManager.SetEnabled("Synchronize", enabledValue: true);
		menuToolBarManager.SetEnabled("Paste", !QSecurity.LockedQGroup);
		menuToolBarManager.SetEnabled("Create Test Case", TestCasesPluginsColl.Count > 0);
		menuToolBarManager.SetEnabled("Switch To Draft", TestCasesPluginsColl.Count > 0);
		menuToolBarManager.SetEnabled("Find in Database", TestCasesPluginsColl.Count > 0);
		menuToolBarManager.SetEnabled("DEBUG - Generate TestCase Data", enabledValue: false);
		menuToolBarManager.SetVisible("DEBUG - Generate TestCase Data", visiblilty: false);
		menuToolBarManager.SetEnabled("Link Tree", enabledValue: true);
		menuToolBarManager.SetEnabled("Update Link(s)", enabledValue: false);
		menuToolBarManager.SetEnabled("Unlink Tree", enabledValue: false);
		menuToolBarManager.SetEnabled("Re-link Tree", enabledValue: false);
		object obj = null;
		if (TestTreeSelectionManager.SelectedTests.Count > 0)
		{
			obj = TestTreeSelectionManager.SelectedTests[0];
		}
		menuToolBarManager.SetEnabled("Create Test Case", enabledValue: false);
		menuToolBarManager.SetEnabled("Switch To Draft", obj is TestCaseTest && (obj as TestCaseTest).TestCaseProperties.Status == ApprovalStates.Approved);
		menuToolBarManager.SetEnabled("Refresh Test Case", obj is TestCaseTest && (obj as TestCaseTest).TestCaseProperties.Dirty);
	}

	private new bool IsEnabled(BaseTest node)
	{
		if (node is FolderTest && ((FolderTest)node).FolderProperties.LinkRoot)
		{
			return true;
		}
		if (node.Properties.LinkNode)
		{
			if (node.Properties.IsLinkActive != true)
			{
				return true;
			}
			return false;
		}
		return true;
	}

	public bool SaveFile(SaveAsFormat selectedFormat, bool suppressTreeUpgradeWarning = false)
	{
		TraceMessage.Write(ToString(), "Save File " + XmlTreeName, TraceMessageType.Trace);
		if (Environment.OSVersion.Version.Major >= 6 && !checkedSavePath)
		{
			checkedSavePath = false;
			string newSavePath = "";
			if (!CheckForSaveToProgramFiles(TreeDisplayName, out newSavePath))
			{
				return false;
			}
			TreeDisplayName = newSavePath;
		}
		checkedSavePath = false;
		if (!QSecurity.IsEngineer)
		{
			return false;
		}
		if (WPFTestTreeWindowColl.TTDView.RegistrationRequired)
		{
			DialogResult dialogResult = AppMessageDialog.Show("Saving Tree will lose the registration information. \nDo you want to continue?", "QSPR - Message Center", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, DialogResult.OK, MessageDialogType.Warning);
			if (dialogResult == DialogResult.Cancel)
			{
				return false;
			}
			Root.RemoveRegistrationInformation();
		}
		TextWriter textWriter = null;
		try
		{
			if (!suppressTreeUpgradeWarning)
			{
				string treeDisplayName = TreeDisplayName;
				if (XMLTreeFileName != treeDisplayName || XMLTreeFileName.ToLower().EndsWith(".xtt2"))
				{
					StringBuilder stringBuilder = new StringBuilder();
					stringBuilder.Append("The Tree " + TreeDisplayName + " is from older version \n\n");
					stringBuilder.Append("Click Yes to save the existing tree in the new version.   \n");
					stringBuilder.Append("(New tree will be saved with extn .xtt)\n");
					stringBuilder.Append("Click No to select a new filename\n");
					stringBuilder.Append("Click Cancel to cancel the saving of the tree\n");
					switch (AppMessageDialog.Show(stringBuilder.ToString(), "QSPR - Message Center", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk, DialogResult.Yes, MessageDialogType.Warning))
					{
					case DialogResult.Cancel:
						return false;
					case DialogResult.No:
					{
						string[] array = TreeDisplayName.Split('\\');
						string text = array[array.Length - 1];
						string[] array2 = text.Split('.');
						SaveFileDialog saveFileDialog = new SaveFileDialog();
						saveFileDialog.FileName = array2[0];
						saveFileDialog.Title = "Save Converted file " + array[array.Length - 1] + " as";
						saveFileDialog.Filter = "QSPR test tree files (*.cxtt, *.xtt)|*.cxtt;*.xtt|All files (*.*)|*.*";
						saveFileDialog.AddExtension = true;
						saveFileDialog.FilterIndex = 1;
						if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
						{
							return false;
						}
						XmlTreeName = saveFileDialog.FileName;
						break;
					}
					default:
						if (Path.GetExtension(TreeDisplayName).ToUpper() == ".XML" || Path.GetExtension(TreeDisplayName).ToUpper() == ".XTT" || Path.GetExtension(TreeDisplayName).ToUpper() == ".XTT2")
						{
							XmlTreeName = Path.ChangeExtension(TreeDisplayName, ".xtt");
						}
						break;
					}
				}
			}
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(SerializeComponents));
			if (XmlTreeName.Trim() == "")
			{
				SaveAsFormat selectedFormat2 = SaveAsFormat.QSPR_Compressed;
				if (!GetSaveFileName(out selectedFormat2))
				{
					return false;
				}
			}
			if (XmlTreeName.Trim() != "")
			{
				isQSPR2Tree = false;
				textWriter = new StreamWriter(TEMP_TREE_FILE);
				SerializeComponents serializeComponents = new SerializeComponents();
				serializeComponents.theRegistry = RegistryRoot;
				GlobalStatus.SavingTree = true;
				Root.GetSetNumberOfTests();
				Root.RootProperties.TreeFileName = TreeDisplayName.Trim();
				serializeComponents.theRootTest = Root;
				TTInfo.TestTreeVersion = 13.0;
				TTInfo.QGlobalVariables = new GlobalVariables(QTMGlobalVariable.SortedGVNames);
				serializeComponents.theTestTreeInfo = TTInfo;
				serializeComponents.thePlugInConfig = QSPRMainWindow.AllPlugInConfig;
				serializeComponents.WConfig.CopyDataLoggingConfig(_scheduler.QTMData.WConfig);
				serializeComponents.DebugConfig = null;
				xmlSerializer.Serialize(textWriter, serializeComponents);
				GlobalStatus.SavingTree = false;
				TreeChanged = false;
				AddRecentFile(TreeDisplayName);
				textWriter.Close();
				textWriter = null;
				XmlDocument xmlDocument = new XmlDocument();
				xmlDocument.Load(TEMP_TREE_FILE.Trim());
				string fullPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(QSPRMainWindow.FeatureConfigInfo.StyleSheetsDirectory, "qtmtesterrorcode.xsl")));
				string data = "type='text/xsl' href='" + fullPath + "'";
				XmlProcessingInstruction newChild = xmlDocument.CreateProcessingInstruction("xml-stylesheet", data);
				XmlNode firstChild = xmlDocument.FirstChild;
				xmlDocument.InsertAfter(newChild, firstChild);
				string fullPath2 = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(QSPRMainWindow.FeatureConfigInfo.StyleSheetsDirectory, "QTMTestTree ver4.xsl")));
				data = "type='text/xsl' href='" + fullPath2 + "'";
				newChild = xmlDocument.CreateProcessingInstruction("xml-stylesheet", data);
				xmlDocument.InsertAfter(newChild, firstChild);
				xmlDocument.Save(TEMP_TREE_FILE.Trim());
				ApplyLeftIcons(Root);
				if (textWriter != null)
				{
					textWriter.Close();
					textWriter = null;
				}
				GlobalStatus.RegistrationStatus.Reset();
				if (TreeDisplayName.ToLower().EndsWith(".cxtt"))
				{
					FileCompressionUtility.CompressFile(TEMP_TREE_FILE, TreeDisplayName);
				}
				else
				{
					File.Copy(TEMP_TREE_FILE, XmlTreeName, overwrite: true);
				}
				_scheduler.KernelMgr.SetTreeName(TreeDisplayName);
				QTMGlobalVariable.SetGlobalVariable("TreeFileName", TreeDisplayName);
				return true;
			}
			if (textWriter != null)
			{
				textWriter.Close();
				textWriter = null;
			}
			return false;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), string.Concat("Save File ", XmlTreeName, " ", ex.Message, ";\n ", ex.InnerException, ";\n", ex.StackTrace), TraceMessageType.Exception);
			AppMessageDialog.Show(ex.Message + ";\n " + ex.InnerException, "Save Test Tree", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Exception);
		}
		finally
		{
			if (textWriter != null)
			{
				textWriter.Close();
				textWriter = null;
			}
		}
		return false;
	}

	private bool SaveTestPlan()
	{
		using (Dictionary<string, TestCasesPlugin>.ValueCollection.Enumerator enumerator = TestCasesPluginsColl.Values.GetEnumerator())
		{
			if (enumerator.MoveNext())
			{
				TestCasesPlugin current = enumerator.Current;
				if (current.CanCreateTestPlan() && AppMessageDialog.Show("Do you want to update this testplan in the database?", "Update TestPlan in Database", MessageBoxButtons.YesNo, DialogResult.Yes, MessageDialogType.Information) == DialogResult.Yes)
				{
					RegistryRoot.UpdateDLLVersions();
					GenerateDynamicLimitsXmlFile();
					TestPlanMaster testPlanMaster = _testPlanDragDrop.CreateTestPlanData(Root, "C:\\qualcomm\\qspr\\TestPlans\\testplan.xtt");
					current.SaveTestPlan(testPlanMaster);
				}
			}
		}
		return true;
	}

	public bool SaveAsFile(string fileName, bool saveAsLatestFormat)
	{
		TraceMessage.Write(ToString(), "SaveAsFile", TraceMessageType.Trace);
		try
		{
			if (!QSecurity.IsEngineer)
			{
				return false;
			}
			if (fileName == null)
			{
				if (GetSaveFileName(out var selectedFormat))
				{
					checkedSavePath = true;
					return SaveFile(selectedFormat);
				}
				return false;
			}
			if (!fileName.ToLower().EndsWith(".xtt") && !fileName.ToLower().EndsWith(".cxtt"))
			{
				fileName = ((!(Path.GetExtension(fileName).ToUpper() == ".XML") && !(Path.GetExtension(fileName).ToUpper() == ".XTT")) ? (fileName + ".xtt") : Path.ChangeExtension(fileName, ".xtt"));
			}
			string xmlTreeName = (TreeDisplayName = fileName);
			XmlTreeName = xmlTreeName;
			if (saveAsLatestFormat)
			{
				return SaveFile(SaveAsFormat.QSPR);
			}
			return SaveFile(SaveAsFormat.None);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SaveAsFile " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private bool GetSaveFileName(out SaveAsFormat selectedFormat)
	{
		selectedFormat = SaveAsFormat.QSPR_Compressed;
		SaveFileDialog saveFileDialog = new SaveFileDialog();
		saveFileDialog.Filter = "QSPR test tree files (*.cxtt, *.xtt)|*.cxtt;*.xtt|All files (*.*)|*.*";
		if (string.IsNullOrWhiteSpace(TreeDisplayName) || TreeDisplayName.ToLower().EndsWith(".cxtt"))
		{
			saveFileDialog.FilterIndex = 1;
		}
		else
		{
			saveFileDialog.FilterIndex = 2;
		}
		saveFileDialog.AddExtension = true;
		if (XmlTreeName.Trim().Length > 0)
		{
			saveFileDialog.InitialDirectory = TreeDisplayName;
			saveFileDialog.FileName = Path.GetFileNameWithoutExtension(TreeName);
		}
		if (saveFileDialog.ShowDialog() == DialogResult.OK)
		{
			if (Environment.OSVersion.Version.Major >= 6)
			{
				string newSavePath = "";
				if (!CheckForSaveToProgramFiles(saveFileDialog.FileName, out newSavePath))
				{
					return false;
				}
				saveFileDialog.FileName = newSavePath;
			}
			if (QSecurity.LockedQGroup && XmlTreeName == saveFileDialog.FileName)
			{
				AppMessageDialog.Show("You can not overwrite the tree file because the tree is locked.\nPlease choose a different file name.", "Cannot overwrite file", MessageBoxButtons.OK, DialogResult.OK, MessageDialogType.Warning);
				return false;
			}
			string xmlTreeName = (TreeDisplayName = saveFileDialog.FileName);
			XmlTreeName = xmlTreeName;
			return true;
		}
		return false;
	}

	private bool CheckForSaveToProgramFiles(string savePath, out string newSavePath)
	{
		newSavePath = savePath;
		string text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).ToLower();
		string text2 = text;
		text2 = ((!text2.EndsWith(" (x86)")) ? (text2 + " (x86)") : text2.Remove(text2.LastIndexOf(" (x86)")));
		if (savePath.ToLower().StartsWith(text.ToLower()) || savePath.ToLower().StartsWith(text2.ToLower()))
		{
			DialogResult dialogResult = AppMessageDialog.Show("Saving to the Program Files directory is not recommended.\nWould you like to select a different directory?", "QSPR - Message Center", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning);
			if (GlobalStatus.AutomationMode)
			{
				dialogResult = DialogResult.No;
			}
			switch (dialogResult)
			{
			case DialogResult.Cancel:
				return false;
			case DialogResult.Yes:
			{
				string[] array = TreeDisplayName.Split('\\');
				string text3 = array[array.Length - 1];
				string[] array2 = text3.Split('.');
				SaveFileDialog saveFileDialog = new SaveFileDialog();
				saveFileDialog.FileName = array2[0];
				saveFileDialog.Title = "Save Converted file " + array[array.Length - 1] + " as";
				saveFileDialog.Filter = "QSPR test tree files (*.cxtt, *.xtt)|*.cxtt;*.xtt|All files (*.*)|*.*";
				saveFileDialog.FilterIndex = 1;
				if (saveFileDialog.ShowDialog() != DialogResult.OK)
				{
					return false;
				}
				newSavePath = saveFileDialog.FileName;
				break;
			}
			}
		}
		return true;
	}

	private void BreakPointAction(BreakPointTypes action, BaseTest node)
	{
		try
		{
			if (node == null)
			{
				return;
			}
			if (node.Properties.BreakPoint != 0)
			{
				node.Properties.BreakPoint = action;
				ApplyLeftIcons(node);
				TreeChanged = true;
			}
			if (!(node is FolderTest))
			{
				return;
			}
			FolderTest folderTest = (FolderTest)node;
			foreach (BaseTest test in folderTest.TestList)
			{
				BreakPointAction(action, test);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "BreakPointAction " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void EnableLoggingAction(bool action, BaseTest node)
	{
		try
		{
			if (node == null)
			{
				return;
			}
			node.Properties.LoggingEnabled = action;
			ApplyLeftIcons(node);
			TreeChanged = true;
			if (!(node is FolderTest))
			{
				return;
			}
			FolderTest folderTest = node as FolderTest;
			foreach (BaseTest test in folderTest.TestList)
			{
				EnableLoggingAction(action, test);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "EnableLoggingAction " + ex.Message, TraceMessageType.Exception);
		}
	}

	private bool RunTree(bool rerun = false)
	{
		TraceMessage.Write(ToString(), "RunTree", TraceMessageType.Trace);
		try
		{
			if (Root.RootProperties.TreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan)
			{
				if (!(Root.RootProperties is TestPlanProperties))
				{
					string text = "The properties for this Plan are invalid.  Expected <RootProperties xsi:type=\"TestPlanProperties\" NodeType=\"RootProperty\"> was not found.";
					AppMessageDialog.Show(text, "Invalid TestPlan file", DialogResult.OK, MessageDialogType.Error);
					return false;
				}
				if (Scheduler.ContainsDraftTestCases(Root))
				{
					if (AppMessageDialog.Show("This TestPlan contains DRAFT test cases and results will not show in reporting.", "Test Plan contains DRAFT cases", MessageBoxButtons.OKCancel, DialogResult.OK, MessageDialogType.Warning) == DialogResult.Cancel)
					{
						return false;
					}
				}
				else if ((Root.RootProperties as TestPlanProperties).Status != "Approved" && AppMessageDialog.Show("This TestPlan is in DRAFT state and results will not show in reporting.", "Test Plan in DRAFT state", MessageBoxButtons.OKCancel, DialogResult.OK, MessageDialogType.Warning) == DialogResult.Cancel)
				{
					return false;
				}
			}
			if (!ValidateVersion())
			{
				_scheduler.SendGoNoGoDidNotStartMsg();
				return false;
			}
			InitalizeDynamicLimits();
			Analytics.WriteAnalytics("RunTree", "GoNoGo tree run started");
			ResetTestTree(Root);
			GlobalStatus.Reset();
			menuToolBarManager.SetEnabled("Run Test", enabledValue: false);
			menuToolBarManager.SetEnabled("Stop Test", enabledValue: true);
			QTMGlobalVariable.SetGlobalVariable("LOGGING_ENABLED", "");
			if (Root.RootProperties.TreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan && Root.RootProperties is TestPlanProperties)
			{
				string testPlanName = (Root.Properties as TestPlanProperties).TestPlanName;
				QTMGlobalVariable.SetGlobalVariable("TESTPLAN_NAME", testPlanName);
			}
			else
			{
				QTMGlobalVariable.SetGlobalVariable("TESTPLAN_NAME", "");
			}
			TesterConfigurationInfo testerConfigurationInfo = new TesterConfigurationInfo();
			testerConfigurationInfo.Name = "TreeFileName";
			testerConfigurationInfo.Value = TreeDisplayName;
			testerConfigurationInfo.IncludeInTestResults = true;
			TesterConfigurationList.Add(testerConfigurationInfo);
			testerConfigurationInfo = new TesterConfigurationInfo();
			testerConfigurationInfo.IncludeInTestResults = true;
			testerConfigurationInfo.Name = "TreeType";
			if (!GlobalStatus.SimulatorMode)
			{
				testerConfigurationInfo.Value = (GlobalStatus.DVTMode ? QC.QsprTestObjects.Tests.Base.TreeTypes.DVT.ToString() : Root.RootProperties.TreeType.ToString());
			}
			else
			{
				AppMessageDialog.Show("Running tests in Simulation Mode.", DialogResult.OK, MessageDialogType.UIWarning);
				testerConfigurationInfo.Value = "Simulation";
			}
			TesterConfigurationList.Add(testerConfigurationInfo);
			if (IsTreeRegistered)
			{
				testerConfigurationInfo = new TesterConfigurationInfo();
				testerConfigurationInfo.IncludeInTestResults = true;
				testerConfigurationInfo.Name = "Server";
				testerConfigurationInfo.Value = Root.RootProperties.Server;
				TesterConfigurationList.Add(testerConfigurationInfo);
				testerConfigurationInfo = new TesterConfigurationInfo();
				testerConfigurationInfo.IncludeInTestResults = true;
				testerConfigurationInfo.Name = "Database";
				testerConfigurationInfo.Value = Root.RootProperties.Database;
				TesterConfigurationList.Add(testerConfigurationInfo);
				testerConfigurationInfo = new TesterConfigurationInfo();
				testerConfigurationInfo.IncludeInTestResults = false;
				testerConfigurationInfo.Name = "SiteTreeID";
				testerConfigurationInfo.Value = Root.RootProperties.SiteTreeID.ToString();
				TesterConfigurationList.Add(testerConfigurationInfo);
				testerConfigurationInfo = new TesterConfigurationInfo();
				testerConfigurationInfo.IncludeInTestResults = false;
				testerConfigurationInfo.Name = "SiteKey";
				testerConfigurationInfo.Value = Root.RootProperties.SiteKey;
				TesterConfigurationList.Add(testerConfigurationInfo);
				testerConfigurationInfo = new TesterConfigurationInfo();
				testerConfigurationInfo.IncludeInTestResults = false;
				testerConfigurationInfo.Name = "RegisteredMachine";
				testerConfigurationInfo.Value = Root.RootProperties.RegisteredMachine;
				TesterConfigurationList.Add(testerConfigurationInfo);
			}
			else if (Root.RootProperties.TreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan && TestCasesPluginsColl.Count > 0)
			{
				testerConfigurationInfo = new TesterConfigurationInfo();
				testerConfigurationInfo.IncludeInTestResults = true;
				testerConfigurationInfo.Name = "Server";
				testerConfigurationInfo.Value = TestCasesPluginsColl["Test Management"].GetTestCaseServerName();
				TesterConfigurationList.Add(testerConfigurationInfo);
				testerConfigurationInfo = new TesterConfigurationInfo();
				testerConfigurationInfo.IncludeInTestResults = true;
				testerConfigurationInfo.Name = "Database";
				testerConfigurationInfo.Value = TestCasesPluginsColl["Test Management"].GetTestCaseDatabaseName();
				TesterConfigurationList.Add(testerConfigurationInfo);
			}
			_scheduler.RerunStarted = delegate
			{
				ResetFailedTestTreeNodes(Root);
			};
			_scheduler.ScheduleTests(Root, Scheduler.TestingType.GoNoGo, rerun);
			if (_scheduler.postConditionAction != PostConditionActions.RestartTestTree && _scheduler.postConditionAction != PostConditionActions.RestartTestTreeWithoutMustRuns && !_scheduler.QTMData.WConfig.SuppressResultsDialog && !GlobalStatus.AutomationMode)
			{
				ShowResultsDialog();
			}
			if (!GlobalStatus.Abort)
			{
				GlobalStatus.Reset();
			}
			GlobalStatus.TestRunning = false;
			GlobalStatus.TestCaseRunning = false;
			if (currBreakPointNode != null)
			{
				currBreakPointNode.TestUserInterfaceProperties.BackColor = Colors.Transparent.ToString();
			}
			menuToolBarManager.SetEnabled("Run Test", enabledValue: true);
			menuToolBarManager.SetEnabled("Stop Test", enabledValue: false);
			Analytics.WriteAnalytics("RunTree", "GoNoGo tree run finished with result: " + GlobalStatus.GlobalTestResult);
			if (_scheduler.postConditionAction == PostConditionActions.RestartTestTree || _scheduler.postConditionAction == PostConditionActions.RestartTestTreeWithoutMustRuns)
			{
				return RunTree();
			}
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "RunTree " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void InitalizeDynamicLimits()
	{
		_scheduler.RootFolder.ReportGenerator = null;
		try
		{
			if (!GenerateDynamicLimitsXmlFile())
			{
				return;
			}
			_scheduler.RootFolder.ReportGenerator = new ReportGenerator();
			if (string.IsNullOrWhiteSpace(Root.RootProperties.DynamicLimitsFileXML) || !File.Exists(Root.RootProperties.DynamicLimitsFileXML))
			{
				return;
			}
			_scheduler.RootFolder.ReportGenerator.LoadLimitDescriptor(Root.RootProperties.DynamicLimitsFileXML);
			List<string> list = (from t in _scheduler.RootFolder.ReportGenerator.GetAllLimitDescriptorGroupType()
				select t.Name).ToList();
			string gvValue = string.Empty;
			if (!QTMGlobalVariable.GetGlobalVariable("LIMIT_GROUP", out gvValue) || !list.Contains(gvValue))
			{
				LimitGroupPicker limitGroupPicker = new LimitGroupPicker(list);
				if (limitGroupPicker.ShowDialog() == DialogResult.OK)
				{
					QTMGlobalVariable.SetGlobalVariable("LIMIT_GROUP", limitGroupPicker.SelectedLimitGroupName);
				}
			}
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("An error occured initializing dynamic limits.\n" + Root.RootProperties.DynamicLimitsFileExcel + "\n" + ex.ToString(), "Dynamic limits file error", DialogResult.OK, MessageDialogType.Error);
		}
	}

	private bool GenerateDynamicLimitsXmlFile()
	{
		try
		{
			if (!string.IsNullOrWhiteSpace(Root.RootProperties.DynamicLimitsFileExcel))
			{
				if (!string.IsNullOrWhiteSpace(Root.RootProperties.DynamicLimitsFileXML))
				{
					FileInfo fileInfo = new FileInfo(Root.RootProperties.DynamicLimitsFileExcel);
					FileInfo fileInfo2 = new FileInfo(Root.RootProperties.DynamicLimitsFileXML);
					if (!fileInfo.Exists)
					{
						AppMessageDialog.Show("The dynamic limits file specified does not exist.\nYou can change the file selection in the Root nodes Properties.\n" + Root.RootProperties.DynamicLimitsFileExcel, "Dynamic limits file not found", DialogResult.OK, MessageDialogType.Error);
						return false;
					}
					if (fileInfo.LastWriteTime > fileInfo2.LastWriteTime)
					{
						ExcelManager.RunMacro(Root.RootProperties.DynamicLimitsFileExcel, "GenerateLimDesc", new string[1] { Root.RootProperties.DynamicLimitsFileXML });
					}
				}
				else
				{
					Root.RootProperties.DynamicLimitsFileXML = Root.RootProperties.DynamicLimitsFileExcel.Replace(".xls", ".xml");
					ExcelManager.RunMacro(Root.RootProperties.DynamicLimitsFileExcel, "GenerateLimDesc", new string[1] { Root.RootProperties.DynamicLimitsFileXML });
				}
				return true;
			}
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("An error occured processing the dynamic limits file.\n" + Root.RootProperties.DynamicLimitsFileExcel + "\n" + ex.ToString(), "Dynamic limits file error", DialogResult.OK, MessageDialogType.Error);
			return false;
		}
		return false;
	}

	private void ShowResultsDialog()
	{
		if (this.InvokeRequired())
		{
			this.Invoke(delegate
			{
				ShowResultsDialog();
			});
			return;
		}
		GoNoGoResults goNoGoResults = new GoNoGoResults();
		goNoGoResults.Result = GlobalStatus.GlobalTestResult;
		goNoGoResults.FailedTests = GlobalStatus.ListOfFailedTests;
		goNoGoResults.ShowFailedTests = GlobalStatus.ShowFailedTests;
		goNoGoResults.ShowDialog(WpfToWin32Window.GetCurrentWin32Window());
	}

	public void ResetTestTreeUsingRootNode()
	{
		ResetTestTree(Root);
	}

	private void ResetFailedTestTreeNodes(BaseTest ParentNode)
	{
		ResetTestTree(ParentNode);
	}

	internal bool ResetTestTree(BaseTest node)
	{
		TraceMessage.Write(ToString(), "ResetTestTree", TraceMessageType.Trace);
		try
		{
			if (!wsc.Font.Bold)
			{
				node.TestUserInterfaceProperties.FontWeight = FontWeights.Normal;
			}
			ApplyLeftIcons(node);
			if (node is RootTest)
			{
				RootTest rootTest = (RootTest)node;
				rootTest.ConfigureNodeImage("/QSPR;component/Icons/Root.png", "/QSPR;component/Icons/Root.png");
				rootTest.TestUserInterfaceProperties.ForeColor = Colors.Black.ToString();
				rootTest.FolderProperties.Failed = false;
				rootTest.FolderProperties.Exception = false;
				rootTest.TestUserInterfaceProperties.ResetRunTimeAttributes();
				foreach (BaseTest test in rootTest.TestList)
				{
					ResetTestTree(test);
				}
			}
			else if (node is FolderTest)
			{
				if (_scheduler.IsInRerunMode && !node.ShouldRerun())
				{
					return false;
				}
				FolderTest folderTest = (FolderTest)node;
				folderTest.TestUserInterfaceProperties.ForeColor = Colors.Black.ToString();
				if (folderTest.Properties.LinkNode && folderTest.Properties.IsLinkActive == true)
				{
					folderTest.ConfigureNodeImage("/QSPR;component/Icons/folder-closed.png", "/QSPR;component/Icons/folder-open.png");
					folderTest.TestUserInterfaceProperties.IsLocked = true;
					folderTest.SetReadOnly(isReadOnly: true);
				}
				else if (folderTest.FolderProperties.LinkRoot && folderTest.FolderProperties.IsLinkActive == true)
				{
					folderTest.ConfigureNodeImage("/QSPR;component/Icons/folder-closed.png", "/QSPR;component/Icons/folder-open.png");
					folderTest.TestUserInterfaceProperties.IsLocked = true;
				}
				else
				{
					folderTest.TestUserInterfaceProperties.IsLocked = false;
					ChangeColorForUnlink(folderTest);
					if (folderTest is TestCaseTest)
					{
						folderTest.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTestCase.png", "/QSPR;component/Icons/TestTreeTestCase.png");
					}
					else
					{
						folderTest.SetReadOnly(Root.TestUserInterfaceProperties.IsReadOnly);
						folderTest.ConfigureNodeImage("/QSPR;component/Icons/folder-closed.png", "/QSPR;component/Icons/folder-open.png");
					}
				}
				folderTest.FolderProperties.Failed = false;
				folderTest.FolderProperties.Exception = false;
				folderTest.TestUserInterfaceProperties.ResetRunTimeAttributes();
				if (node is TestCaseTest)
				{
					RefreshTestCaseNode((TestCaseTest)node);
				}
				foreach (BaseTest test2 in folderTest.TestList)
				{
					ResetTestTree(test2);
				}
			}
			else
			{
				node.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTest.png", "/QSPR;component/Icons/TestTreeTest.png");
				node.TestUserInterfaceProperties.ResetRunTimeAttributes();
				node.TestUserInterfaceProperties.ForeColor = Colors.Black.ToString();
				if (node.Properties.LinkNode && node.Properties.IsLinkActive == true)
				{
					node.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTest.png", "/QSPR;component/Icons/TestTreeTest.png");
					node.TestUserInterfaceProperties.IsLocked = true;
				}
				else
				{
					node.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTest.png", "/QSPR;component/Icons/TestTreeTest.png");
					node.TestUserInterfaceProperties.IsLocked = false;
					ChangeColorForUnlink(node);
					node.TestUserInterfaceProperties.IsReadOnly = Root.TestUserInterfaceProperties.IsReadOnly;
				}
				node.TestUserInterfaceProperties.ResetRunTimeAttributes();
			}
			node.TestUserInterfaceProperties.IsReadOnly |= QSecurity.LockedQGroup || !QSecurity.IsTechnician;
		}
		catch
		{
		}
		return true;
	}

	private static void ChangeColorForUnlink(BaseTest test)
	{
		if (test is FolderTest && ((FolderTest)test).FolderProperties.LinkRoot && ((FolderTest)test).Properties.IsLinkActive == false)
		{
			test.TestUserInterfaceProperties.ForeColor = Colors.DarkOrange.ToString();
		}
		else if (test.Properties.LinkNode && test.Properties.IsLinkActive != true)
		{
			test.TestUserInterfaceProperties.ForeColor = Colors.DarkOrange.ToString();
		}
	}

	private bool OpenTree()
	{
		XmlTreeName = Path.GetFullPath(XmlTreeName);
		string xmlTreeName = XmlTreeName;
		NewTree();
		string xmlTreeName2 = (TreeDisplayName = xmlTreeName);
		XmlTreeName = xmlTreeName2;
		TraceMessage.Write(ToString(), "Open Tree " + XmlTreeName, TraceMessageType.Trace);
		bool result = true;
		FileStream fileStream = null;
		try
		{
			QSPRMainWindow.UltraToolbarsManager.SetVisible("Save", !QSecurity.LockedQGroup);
			QSPRMainWindow.UltraToolbarsManager.SetVisible("SaveAs", visiblilty: true);
			if (!ConvertTree(XmlTreeName, out var oldTreeVersion, out var newTreeName, out isQSPR2Tree))
			{
				TraceMessage.Write(ToString(), "ConvertTree() failed", TraceMessageType.Error);
				return false;
			}
			XmlTreeName = newTreeName;
			string path = XmlTreeName;
			if (XmlTreeName.ToLower().EndsWith(".cxtt"))
			{
				path = GetDecompressedFileName(XmlTreeName);
			}
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(SerializeComponents));
			fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
			if (fileStream != null)
			{
				QSPRMainWindow.DebugConfig.Clear();
				TraceMessage.Write(ToString(), "OpenTree(), Deserializing tree: " + XmlTreeName, TraceMessageType.Trace);
				SerializeComponents serializeComponents = (SerializeComponents)xmlSerializer.Deserialize(fileStream);
				Root = serializeComponents.theRootTest;
				_scheduler.GlobalStatus.PauseOnTestFailure = Root.RootProperties.PauseOnTestFailure;
				_scheduler.GlobalStatus.StopOnFirstTestFailure = Root.RootProperties.StopOnFirstTestFailure;
				_scheduler.Env.GlobalVariable.SetGlobalVariable("TesterConfigFile", Root.RootProperties.ConfigFileName);
				_scheduler.Env.GlobalVariable.SetGlobalVariable("TreeStringID", Root.RootProperties.TreeStringID);
				InitializeParent(Root);
				QTMRegistry theRegistry = serializeComponents.theRegistry;
				theRegistry.scheduler = _scheduler;
				theRegistry.CreateHastable();
				TTInfo = serializeComponents.theTestTreeInfo;
				RegistryRoot = theRegistry;
				QSecurity.LockedQGroup = GetLockedQGroup(serializeComponents.theRootTest.RootProperties.EditQGroups);
				foreach (GlobalVariable item in serializeComponents.theTestTreeInfo.QGlobalVariables.QGlobalVariable)
				{
					if (!QTMGlobalVariable.Contains(item.Name))
					{
						TraceMessage.Write(ToString(), "OpenTree(), Clearing Gv from tree: name=" + item.Name, TraceMessageType.Trace);
						QTMGlobalVariable.SetGlobalVariable(item.Name, "");
					}
				}
				QSPRMainWindow.CurrentTreeName = XmlTreeName;
				QSPRMainWindow.AllPlugInConfig = serializeComponents.thePlugInConfig;
				_scheduler.QTMData.WConfig.CopyDataLoggingConfig(serializeComponents.WConfig);
				QSPRMainWindow.DebugConfig = serializeComponents.DebugConfig;
				fileStream.Close();
				bLoadingTree = true;
				LoadTrees();
				GlobalStatus.RegistrationStatus.Reset();
				UpdateCurrLinkStatus();
				UpdateLinkedTrees(null, reLink: false, openTree: true);
				bool isTreeChanged = TreeChanged;
				ResetTestTree(Root);
				CopiedNodes = null;
				HandleSynchronization(oldTreeVersion, isTreeChanged, null);
				if (oldTreeVersion < 13.0 && TreeConverter.QSPR_TREE_VERSION == oldTreeVersion)
				{
					Root.Properties.TestName = Root.TestList[0].Properties.TestName;
					Root.Properties.Notes = Root.TestList[0].Properties.Notes;
					Root.Properties.Description = Root.TestList[0].Properties.Description;
				}
				_scheduler.KernelMgr.SetTreeName(TreeDisplayName);
				QSecurity_UserAccessLevelChanged(this, new UserAccessLevelChangedEventArgs(QSecurity.UserAccessLevel));
				bLoadingTree = true;
				CollapseExpandAll(collapse: true);
				TreeChanged = isTreeChanged;
				if (isQSPR2Tree)
				{
					TreeChanged = false;
				}
				ttdParameterView.ClearParameterDescriptionBox();
				if (XmlTreeName.ToLower().EndsWith(".cxtt"))
				{
					path = GetDecompressedFileName(XmlTreeName);
					File.Delete(path);
				}
				bLoadingTree = false;
			}
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show(ex.Message + ";\n " + ex.InnerException, "Error Opening Test Tree", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Exception);
			TraceMessage.Write(ToString(), string.Concat("Open Tree ", XmlTreeName, " ", ex.Message, ";\n ", ex.InnerException, ";\n", ex.StackTrace), TraceMessageType.Exception);
			result = false;
			NewTree();
		}
		finally
		{
			fileStream?.Close();
		}
		TraceMessage.Write(ToString(), "OpenTree, returning " + result, TraceMessageType.Trace);
		return result;
	}

	private void UpdateCurrLinkStatus()
	{
		TraceMessage.Write(ToString(), "UpdateCurrLinkStatus()", TraceMessageType.Trace);
		ArrayList linkedFolders = new ArrayList();
		Root.FindAllLinkedFolders(Root, ref linkedFolders);
		if (linkedFolders.Count <= 0)
		{
			return;
		}
		foreach (FolderTest item in linkedFolders)
		{
			if (item.FolderProperties.LinkRoot && !item.Properties.IsLinkActive.HasValue)
			{
				MarkCurrLinkStatus(item, isLink: true, true);
			}
			else if (!item.FolderProperties.LinkRoot && !item.Properties.IsLinkActive.HasValue && !string.IsNullOrEmpty(item.FolderProperties.LinkLocation))
			{
				item.FolderProperties.LinkRoot = true;
				MarkCurrLinkStatus(item, isLink: true, false);
			}
			else if (item.FolderProperties.LinkRoot && item.Properties.IsLinkActive == true)
			{
				MarkCurrLinkStatus(item, isLink: true, true);
			}
			else if (item.FolderProperties.LinkRoot && item.Properties.IsLinkActive == false)
			{
				MarkCurrLinkStatus(item, isLink: true, false);
			}
			else
			{
				TraceMessage.Write(ToString(), "FindAllLinkedFolders returns incorrect link roots", TraceMessageType.Error);
			}
			item.Properties.LinkNode = false;
		}
	}

	private void InitializeParent(FolderTest folderTest)
	{
		foreach (BaseTest test in folderTest.TestList)
		{
			test.Parent = folderTest;
			if (test is FolderTest)
			{
				InitializeParent((FolderTest)test);
			}
		}
	}

	private bool NewTree()
	{
		if (this.InvokeRequired())
		{
			this.Invoke(delegate
			{
				NewTree();
			});
			return true;
		}
		TraceMessage.Write(ToString(), "New Tree", TraceMessageType.Trace);
		try
		{
			QSecurity_UserAccessLevelChanged(this, new UserAccessLevelChangedEventArgs(QSecurity.UserAccessLevel));
			isQSPR2Tree = false;
			InitTestTree();
			RegistryRoot.ClearTargets();
			Registries.Clear();
			Registries.Add(RegistryRoot);
			ConstructRegistryTree(RegistryRoot);
			RegistryTreeBrowser.Expand(RegistryRoot);
			RegistryRoot.IsSelected = true;
			GlobalStatus.RegistrationStatus.Reset();
			QSecurity.LockedQGroup = false;
			ttdPropView.EnableControls(enable: true);
			ttdParameterView.ClearParameterDescriptionBox();
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "New Tree " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public static string GetDecompressedFileName(string compressedFileName)
	{
		string text = Path.GetFileNameWithoutExtension(compressedFileName) + ".xtt";
		return TEMP_DECOMPRESS_TREE_FILE_TEMPLATE_NAME + text;
	}

	private bool ConvertTree(string treeName, out double oldTreeVersion, out string newTreeName, out bool isQSPR2Tree)
	{
		TraceMessage.Write(ToString(), "ConvertTree " + treeName, TraceMessageType.Trace);
		oldTreeVersion = 1.0;
		newTreeName = treeName;
		isQSPR2Tree = false;
		try
		{
			if (treeName.ToLower().EndsWith(".cxtt"))
			{
				string decompressedFileName = GetDecompressedFileName(treeName);
				FileCompressionUtility.DecompressFile(treeName, decompressedFileName);
				treeName = decompressedFileName;
			}
			string sourceFileName = PathUtils.ConvertToAbsolute(TreeName, treeName);
			TreeConverter treeConverter = new TreeConverter(sourceFileName);
			double num = (oldTreeVersion = treeConverter.GetTreeVersion());
			if (num < 13.0)
			{
				if (num == TreeConverter.QSPR_TREE_VERSION && treeName.ToUpper().EndsWith("XTT"))
				{
					isQSPR2Tree = true;
				}
				newTreeName = TEMP_FOLDER + "\\qtmTemp_" + Process.GetCurrentProcess().Id + ".xtt";
				treeConverter.OutputFile = newTreeName;
				TraceMessage.Write(ToString(), "ConvertTree(), newTreeName: " + newTreeName, TraceMessageType.Trace);
				if (!treeConverter.Convert())
				{
					TraceMessage.Write(ToString(), "TreeConverter.Convert() failed", TraceMessageType.Error);
					return false;
				}
				if (!File.Exists(treeConverter.OutputFile))
				{
					AppMessageDialog.Show("Failed to convert the tree, please re-install QSPR v" + System.Windows.Forms.Application.ProductVersion, DialogResult.OK, MessageDialogType.Exception);
					return false;
				}
			}
			else if (num > 13.0)
			{
				AppMessageDialog.Show("This is a newer version of the tree. You may lose information, or have problems opening the tree.", DialogResult.OK, MessageDialogType.Warning);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ConvertTree failed, " + ex.Message, TraceMessageType.Exception);
			return false;
		}
		return true;
	}

	private void RegisterTreeTypeChangedEvent()
	{
		if (Root != null)
		{
			Root.RootProperties.OnTreeTypeChanged += RootProperties_OnTreeTypeChanged;
		}
	}

	private void RootProperties_OnTreeTypeChanged(object sender, RootTestProperties.TreeTypeChangedEventArgs e)
	{
		if (bLoadingTree)
		{
			return;
		}
		if (e.NewTreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan)
		{
			AppMessageDialog.Show("To change a tree to a testplan, drop it in the testplan plugin.", DialogResult.OK, MessageDialogType.Warning);
			e.Cancel = true;
		}
		else if (e.NewTreeType != QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan && e.OldTreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan)
		{
			if (AppMessageDialog.Show("The database will not be affected and a local copy will be created.\nYou can save the local copy to a file for later use.", "Are you sure you want to convert this plan to a gonogo tree?", MessageBoxButtons.YesNo, DialogResult.No, MessageDialogType.Warning) != DialogResult.Yes)
			{
				e.Cancel = true;
				return;
			}
			XmlTreeName = string.Empty;
			TreeDisplayName = string.Empty;
			Root.RootProperties.OnTreeTypeChanged -= RootProperties_OnTreeTypeChanged;
			TestPlanToTreeConverter testPlanToTreeConverter = new TestPlanToTreeConverter();
			RootTest root = testPlanToTreeConverter.Convert(Root);
			Root = root;
			testTreeView.ItemsSource = null;
			testTreeView.ItemsSource = Tests;
			string fileName = "c:\\qualcomm\\qspr\\testplans\\convertedplan.xtt";
			SaveAsFile(fileName, saveAsLatestFormat: true);
			OpenTree();
			RegisterTreeTypeChangedEvent();
		}
	}

	private bool GetLockedQGroup(QGroupsCollection qGroupsCollection)
	{
		try
		{
			if (qGroupsCollection.Count == 0)
			{
				return false;
			}
			BindingList<string> allGroups = QSecurity.GetAllGroups();
			foreach (object item in qGroupsCollection)
			{
				if (allGroups.Contains(item))
				{
					return false;
				}
			}
			return true;
		}
		catch (Exception)
		{
			return true;
		}
	}

	public void LoadTrees()
	{
		if (this.InvokeRequired())
		{
			this.Invoke(delegate
			{
				LoadTrees();
			});
			return;
		}
		TraceMessage.Write(ToString(), "LoadTrees", TraceMessageType.Trace);
		try
		{
			_ = Root;
			Tests.Clear();
			Tests.Add(Root);
			TestTreeSelectionManager = new TestTreeSelectionManager(Root, testTreeView);
			TestTreeSelectionManager.FirstSelectedTestChanged += TestTreeSelectionManager_FirstSelectedTestChanged;
			TestTreeEditor = new TestTreeEditor(testTreeView);
			TestTreeEditor.AfterTestNameEdit += TestTreeEditor_AfterTestNameEdit;
			TestTreeEditor.BeforeTestNameEdit += TestTreeEditor_BeforeTestNameEdit;
			TestTreeEditor.AfterTestCut += TestTreeEditor_AfterTestCut;
			TestTreeEditor.BeforeTestCut += TestTreeEditor_BeforeTestCut;
			TestTreeEditor.BeforeTestCopy += TestTreeEditor_BeforeTestCopy;
			TestTreeEditor.AfterTestCopy += TestTreeEditor_AfterTestCopy;
			ConstructTTDTree(Root);
			TestTreeSelectionManager.SelectTest(Root);
			ttdPropView.CurrentNode = Root;
			ttdParameterView.Parameters = null;
			Registries.Clear();
			ConstructRegistryTree(RegistryRoot);
			Registries.Add(RegistryRoot);
			RegistryTreeBrowser.Expand(RegistryRoot);
			RegistryTreeEditor = new RegistryTreeEditor(treeRegistry);
			RegistryTreeEditor.AfterContainerNameEdit += RegistryTreeEditor_AfterContainerNameEdit;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "LoadTrees " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void RegistryTreeEditor_AfterContainerNameEdit(object sender, RegistryContainerNodeNameChangeEventArgs e)
	{
		QTMTestContainer container = e.Container;
		if (string.Equals(e.NewName, e.OldName, StringComparison.CurrentCultureIgnoreCase))
		{
			return;
		}
		if (!File.Exists(e.NewName) && container.TargetType == QTMTargetType.ThisPC)
		{
			AppMessageDialog.Show(e.NewName + " not found.", " QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			container.Name = e.OldName;
			return;
		}
		try
		{
			FileInfo fileInfo = new FileInfo(e.NewName);
			FileInfo fileInfo2 = new FileInfo(e.OldName);
			QTMTarget target = RegistryRoot.GetTarget(container.TargetName);
			if (fileInfo.Name != fileInfo2.Name)
			{
				DialogResult dialogResult = AppMessageDialog.Show("Renaming may create broken test links.\nDo you want to continue?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.No, MessageDialogType.CriticalWarning);
				if (dialogResult == DialogResult.No)
				{
					container.Name = e.OldName;
					return;
				}
				string oldName = "";
				if (TestContainerExists(target, e.NewName, out oldName))
				{
					string containerStringName = QTMTestContainer.GetContainerStringName(container.ContainerType);
					AppMessageDialog.Show(containerStringName + " already present.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Warning);
					container.Name = e.OldName;
					return;
				}
			}
			target.RenameContainer(e.OldName, e.NewName);
			RegistryNodesColl.Remove(target.Name + e.OldName);
			container = target.GetContainer(e.NewName);
			container.Key = container.TargetName + container.Name;
			RegistryNodesColl[container.Key] = container;
			AddTestNodesToRegistryTree(container);
			GlobalStatus.RegistrationStatus.RegistryChanged = true;
		}
		catch
		{
			container.Name = e.OldName;
			return;
		}
		TreeChanged = true;
	}

	private void ConstructRegistryTree(QTMRegistry qtmRegistry)
	{
		RegistryNodesColl.Clear();
		qtmRegistry.Key = "Registry";
		RegistryNodesColl[qtmRegistry.Key] = qtmRegistry;
		foreach (QTMTarget item in qtmRegistry.Target)
		{
			item.Key = item.Name;
			RegistryNodesColl[item.Key] = item.Key;
			foreach (QTMTestContainer testContainer in item.TestContainers)
			{
				testContainer.Key = item.Name + testContainer.Name;
				RegistryNodesColl[testContainer.Key] = testContainer;
				if (testContainer.Loaded)
				{
					testContainer.UserInterfaceProperties.NodeImageUri = "/QSPR;component/Icons/RegistryTreeLoadedDll.png";
					testContainer.UserInterfaceProperties.FontColor = Colors.Black.ToString();
				}
				else
				{
					testContainer.UserInterfaceProperties.NodeImageUri = "/QSPR;component/Icons/RegistryTreeUnloadedDll.png";
					testContainer.UserInterfaceProperties.FontColor = Colors.Red.ToString();
					testContainer.UserInterfaceProperties.FontStyle = FontStyles.Normal;
				}
				AddTestNodesToRegistryTree(testContainer);
			}
		}
	}

	private void AddTestNodesToRegistryTree(QTMTestContainer testContainer)
	{
		string[] array = null;
		string key = string.Empty;
		string text = "";
		testContainer.UserInterfaceProperties.Items.Clear();
		foreach (QTMTest test in testContainer.Tests)
		{
			ObservableCollection<QTMTestContainerItem> items = testContainer.UserInterfaceProperties.Items;
			if (testContainer.ContainerType != QC.QsprTestObjects.Tests.Base.QTMTestTypes.LabVIEWTest && testContainer.ContainerType != QC.QsprTestObjects.Tests.Base.QTMTestTypes.ScriptTest)
			{
				array = test.Name.Split('.');
				key = testContainer.Name;
				if (array.Length > 1)
				{
					for (int i = 0; i < array.Length; i++)
					{
						if (array[i] == "QC")
						{
							text = array[i];
							continue;
						}
						text = ((!(text == "QC")) ? array[i] : ("QC." + array[i]));
						key += text;
						if (i < array.Length - 1)
						{
							string empty = string.Empty;
							empty = ((i != array.Length - 2) ? "/QSPR;component/Icons/RegistryNamespace.png" : "/QSPR;component/Icons/RegistryClass.png");
							QTMTestContainerItem qTMTestContainerItem = items.FirstOrDefault((QTMTestContainerItem item) => item.Key == key);
							if (qTMTestContainerItem == null)
							{
								qTMTestContainerItem = new QTMTestContainerItem(key, text, empty, testContainer);
								items.Add(qTMTestContainerItem);
								RegistryNodesColl[key] = qTMTestContainerItem;
							}
							if (testContainer.Loaded)
							{
								qTMTestContainerItem.FontColor = Colors.Black.ToString();
							}
							else
							{
								qTMTestContainerItem.FontColor = Colors.Gray.ToString();
							}
							items = qTMTestContainerItem.Items;
						}
						else
						{
							QTMTestContainerItem qTMTestContainerItem2 = items.FirstOrDefault((QTMTestContainerItem item) => item.Key == key);
							if (qTMTestContainerItem2 == null)
							{
								qTMTestContainerItem2 = new QTMTestContainerItem(key, text, "/QSPR;component/Icons/TestTreeTest.png", test, testContainer);
								items.Add(qTMTestContainerItem2);
								RegistryNodesColl[key] = qTMTestContainerItem2;
							}
							if (testContainer.Loaded)
							{
								qTMTestContainerItem2.NodeImageUri = "/QSPR;component/Icons/RegistryTreeLoadedTest.png";
								qTMTestContainerItem2.FontColor = Colors.Black.ToString();
							}
							else
							{
								qTMTestContainerItem2.NodeImageUri = "/QSPR;component/Icons/RegistryTreeUnloadedTest.png";
								qTMTestContainerItem2.FontColor = Colors.Gray.ToString();
							}
						}
					}
				}
				else
				{
					text = test.Name;
					key += text;
					QTMTestContainerItem qTMTestContainerItem3 = items.FirstOrDefault((QTMTestContainerItem item) => item.Key == key);
					if (qTMTestContainerItem3 == null)
					{
						qTMTestContainerItem3 = new QTMTestContainerItem(key, text, string.Empty, test, testContainer);
						items.Add(qTMTestContainerItem3);
						RegistryNodesColl[key] = qTMTestContainerItem3;
					}
					if (testContainer.Loaded)
					{
						qTMTestContainerItem3.NodeImageUri = "/QSPR;component/Icons/RegistryTreeLoadedTest.png";
						qTMTestContainerItem3.FontColor = Colors.Black.ToString();
					}
					else
					{
						qTMTestContainerItem3.NodeImageUri = "/QSPR;component/Icons/RegistryTreeUnloadedTest.png";
						qTMTestContainerItem3.FontColor = Colors.Gray.ToString();
					}
				}
			}
			else
			{
				text = test.Name;
				key += text;
				QTMTestContainerItem qTMTestContainerItem4 = items.FirstOrDefault((QTMTestContainerItem item) => item.Key == key);
				if (qTMTestContainerItem4 == null)
				{
					qTMTestContainerItem4 = new QTMTestContainerItem(key, text, "/QSPR;component/Icons/TestTreeTest.png", test, testContainer);
					items.Add(qTMTestContainerItem4);
					RegistryNodesColl[key] = qTMTestContainerItem4;
				}
				if (testContainer.Loaded)
				{
					qTMTestContainerItem4.NodeImageUri = "/QSPR;component/Icons/RegistryTreeLoadedTest.png";
					qTMTestContainerItem4.FontColor = Colors.Black.ToString();
				}
				else
				{
					qTMTestContainerItem4.NodeImageUri = "/QSPR;component/Icons/RegistryTreeUnloadedTest.png";
					qTMTestContainerItem4.FontColor = Colors.Gray.ToString();
				}
			}
		}
	}

	public void ConstructNodesFromFolder(FolderTest folderTest)
	{
		ConstructTTDTree(folderTest);
		RefreshTreeViewList(Root.TestList.ToList());
		ResetTestTree(Root);
	}

	private void ConstructTTDTree(FolderTest folderTest)
	{
		TestNodesColl[folderTest.Index] = folderTest;
		foreach (BaseTest test in folderTest.TestList)
		{
			test.Parent = folderTest;
			if (folderTest is TestCaseTest)
			{
				test.TestUserInterfaceProperties.Visible = _scheduler.QTMData.WConfig.ShowSingleStepTestCaseSteps || folderTest.TestList.Count > 1;
			}
			if (folderTest.Properties.LinkNode || folderTest.FolderProperties.LinkRoot)
			{
				test.Properties.LinkNode = true;
				test.Properties.IsLinkActive = folderTest.Properties.IsLinkActive;
				test.TestUserInterfaceProperties.IsReadOnly = true;
			}
			if (test.IsTestStep)
			{
				test.TestUserInterfaceProperties.IsReadOnly = true;
			}
		}
		if (folderTest is RootTest)
		{
			folderTest.ConfigureNodeImage("/QSPR;component/Icons/Root.png", "/QSPR;component/Icons/Root.png");
		}
		else if (folderTest is TestCaseTest)
		{
			folderTest.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTestCase.png", "/QSPR;component/Icons/TestTreeTestCase.png");
		}
		else
		{
			folderTest.ConfigureNodeImage("/QSPR;component/Icons/folder-closed.png", "/QSPR;component/Icons/folder-open.png");
		}
		foreach (BaseTest test2 in folderTest.TestList)
		{
			if (test2 is FolderTest)
			{
				ConstructTTDTree((FolderTest)test2);
				continue;
			}
			test2.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTest.png", "/QSPR;component/Icons/TestTreeTest.png");
			TestNodesColl[test2.Index] = test2;
			ApplyLeftIcons(test2);
		}
		ApplyLeftIcons(folderTest);
	}

	private void testTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
	{
		System.Windows.Controls.TreeView treeView = (System.Windows.Controls.TreeView)sender;
		if (treeView.Tag != null)
		{
			((TreeViewItem)treeView.Tag).IsSelected = false;
			treeView.Tag = null;
		}
	}

	public void ApplyLeftIcons(BaseTest treeNode)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				ApplyLeftIcons(treeNode);
			});
			return;
		}
		if (treeNode == null)
		{
			treeNode = Root;
		}
		BaseTest baseTest = treeNode;
		treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Clear();
		if (!string.IsNullOrEmpty(baseTest.Properties.Comment))
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/Comments.png");
		}
		if (baseTest.Properties.BreakPoint == BreakPointTypes.Enable)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/breakPoint.png");
		}
		if (baseTest.Properties.BreakPoint == BreakPointTypes.Disable)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/DisableBreakPoint.png");
		}
		if (!baseTest.Properties.LoggingEnabled && _scheduler.QTMData.WConfig.ShowDebugMessages)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeLoggingDisabled.png");
		}
		if (baseTest.Properties.LoggingEnabled && !_scheduler.QTMData.WConfig.ShowDebugMessages)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeLoggingEnabled.png");
		}
		if (baseTest.Properties.ToolTest)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeToolTest.png");
		}
		if (baseTest is FolderTest)
		{
			FolderTest folderTest = (FolderTest)baseTest;
			if (folderTest.FolderProperties.IsSetupFolder)
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/SetupFolder.png");
			}
			if (folderTest.FolderProperties.IsCleanupFolder)
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/CleanupFolder.png");
			}
		}
		if (baseTest.Properties.StopOnError != 0)
		{
			if (baseTest.Properties.StopOnError == StopOnErrorTypes.IgnoreSession)
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/IgnoreSessions.png");
			}
			else
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeStopOnError.png");
			}
		}
		if (baseTest.Properties.TreeMustRun)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeMustRun.png");
		}
		if (baseTest.Properties.FolderMustRun)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeFolderMustRun.png");
		}
		if (baseTest.Properties.BranchOnError.Trim() != "")
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeBranchOnError.png");
		}
		if (baseTest.Properties.Metadata != null && baseTest.Properties.Metadata.Items.Count > 0)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeMetadata.png");
		}
		if (baseTest.Properties.PreCondition != null && baseTest.Properties.PreCondition.IsValid)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreePreCondition.png");
		}
		if (baseTest.Properties.PostCondition != null && baseTest.Properties.PostCondition.Enabled && baseTest.Properties.PostCondition.Action != 0)
		{
			if (baseTest.Properties.PostCondition.Action == PostConditionActions.IgnoreSession)
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/IgnoreSessions.png");
			}
			else
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreePostCondition.png");
			}
		}
		if (baseTest.Properties.BookKeeping)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/BookKeeping.png");
		}
		if (baseTest.Properties.Scenarios != null)
		{
			treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/loop.png");
		}
		if (baseTest is FolderTest)
		{
			FolderTest folderTest2 = (FolderTest)baseTest;
			if (folderTest2.FolderProperties.Scenarios != null && folderTest2.FolderProperties.Scenarios.Condition != null && folderTest2.FolderProperties.Scenarios.Condition.IsValid)
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeBreakCondition.png");
			}
		}
		if (baseTest is RootTest)
		{
			if (baseTest.Properties.NodeRID != -1)
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/TestTreeRegistration.png");
			}
			RootTest rootTest = baseTest as RootTest;
			if (rootTest.RootProperties.StopOnFirstTestFailure)
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/Stop.png");
			}
			else if (rootTest.RootProperties.PauseOnTestFailure)
			{
				treeNode.TestUserInterfaceProperties.NodeImagesUriCollection.Add("/QSPR;component/Icons/Pause.png");
			}
		}
	}

	private void testTreeView_ItemSelected(object sender, RoutedEventArgs e)
	{
		testTreeView.Tag = e.OriginalSource;
		TreeViewItem treeViewItem = (TreeViewItem)e.OriginalSource;
		Keyboard.Focus(treeViewItem);
		if (treeViewItem.DataContext is RootTest)
		{
			rootTreeViewItem = treeViewItem;
		}
	}

	private int MatchString(List<string> strList, string strToMatch)
	{
		int result = 0;
		if (strList.Contains(strToMatch))
		{
			return 1;
		}
		if (strList.Count == 1 && strList[0] == "*")
		{
			return 3;
		}
		foreach (string str in strList)
		{
			string text = str.Trim();
			if (!str.Contains("*"))
			{
				continue;
			}
			if (text == "*")
			{
				result = 3;
			}
			if (text.StartsWith("*") && text.Length > 1)
			{
				if (text.EndsWith("*") && text.Length > 2 && strToMatch.Contains(text.Substring(1, text.Length - 2)))
				{
					return 2;
				}
				if (strToMatch.EndsWith(text.Substring(1)))
				{
					return 2;
				}
			}
			else if (text.EndsWith("*") && strToMatch.StartsWith(text.Substring(0, text.Length - 1)))
			{
				return 2;
			}
		}
		return result;
	}

	private void testTreeView_Expanded(object sender, RoutedEventArgs e)
	{
		TreeViewItem treeViewItem = (TreeViewItem)e.OriginalSource;
		BaseTest baseTest = (BaseTest)treeViewItem.DataContext;
		if (baseTest is FolderTest)
		{
			FolderTest folderTest = (FolderTest)baseTest;
			folderTest.TestUserInterfaceProperties.NodeImageUri = folderTest.TestUserInterfaceProperties.NodeExpandedImageUri;
		}
	}

	private void testTreeView_Collapsed(object sender, RoutedEventArgs e)
	{
		TreeViewItem treeViewItem = (TreeViewItem)e.OriginalSource;
		BaseTest baseTest = (BaseTest)treeViewItem.DataContext;
		if (baseTest is FolderTest)
		{
			FolderTest folderTest = (FolderTest)baseTest;
			folderTest.TestUserInterfaceProperties.NodeImageUri = folderTest.TestUserInterfaceProperties.NodeCollapsedImageUri;
		}
	}

	private void testTreeView_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
	{
		bool shiftPressed = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
		bool ctrlPressed = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);
		BaseTest lastSelectedTest = TestTreeSelectionManager.LastSelectedTest;
		if (e.Key == Key.Down)
		{
			if (lastSelectedTest.TestUserInterfaceProperties.IsInEditMode)
			{
				TestTreeEditor.EndTestNameEdit(lastSelectedTest, commit: true);
			}
			BaseTest baseTest = TestTreeSelectionManager.SelectedTests.LastOrDefault();
			if (baseTest != null)
			{
				BaseTest nextTest = TestTreeBrowser.GetNextTest(baseTest);
				if (nextTest != null)
				{
					TestTreeSelectionManager.SelectTest(nextTest, shiftPressed, ctrlPressed);
				}
			}
			else
			{
				TestTreeSelectionManager.SelectTest(lastSelectedTest, shiftPressed, ctrlPressed);
			}
			e.Handled = true;
		}
		else if (e.Key == Key.Up)
		{
			if (lastSelectedTest.TestUserInterfaceProperties.IsInEditMode)
			{
				TestTreeEditor.EndTestNameEdit(lastSelectedTest, commit: true);
			}
			BaseTest baseTest2 = TestTreeSelectionManager.SelectedTests.LastOrDefault();
			if (baseTest2 != null)
			{
				BaseTest previousTest = TestTreeBrowser.GetPreviousTest(baseTest2);
				if (previousTest != null)
				{
					TestTreeSelectionManager.SelectTest(previousTest, shiftPressed, ctrlPressed);
				}
			}
			else
			{
				TestTreeSelectionManager.SelectTest(lastSelectedTest, shiftPressed, ctrlPressed);
			}
			e.Handled = true;
		}
		else if (e.Key == Key.Right)
		{
			if (lastSelectedTest is FolderTest && !lastSelectedTest.TestUserInterfaceProperties.IsInEditMode)
			{
				FolderTest folderTest = lastSelectedTest as FolderTest;
				if (!folderTest.Properties.Expanded)
				{
					folderTest.Properties.Expanded = true;
				}
				e.Handled = true;
			}
		}
		else if (e.Key == Key.Left && lastSelectedTest is FolderTest && !lastSelectedTest.TestUserInterfaceProperties.IsInEditMode)
		{
			FolderTest folderTest2 = lastSelectedTest as FolderTest;
			if (folderTest2.Properties.Expanded)
			{
				folderTest2.Properties.Expanded = false;
			}
			e.Handled = true;
		}
	}

	private void treeRegistry_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
	{
	}

	private void testTreeView_Drop(object sender, System.Windows.DragEventArgs e)
	{
		if (QSecurity.LockedQGroup || !QSecurity.IsTechnician)
		{
			return;
		}
		DependencyObject depObject = e.OriginalSource as DependencyObject;
		TreeViewItem treeViewItem = depObject.FindParent<TreeViewItem>();
		if (treeViewItem == null || !(treeViewItem.DataContext is BaseTest baseTest) || baseTest.Properties.LinkNode || GlobalStatus.TestRunning)
		{
			return;
		}
		if (IsTestCaseDrop(e))
		{
			if (tempDrag != null)
			{
				tempDrag.ClearValue(System.Windows.Controls.Control.BackgroundProperty);
			}
			if (!IsInvalidTestCaseDrop(baseTest, draggedSourceIsTestcase: true))
			{
				_testCaseDragDrop.HandleTestCaseDrop(e, baseTest);
			}
			return;
		}
		if (tempDrag != null)
		{
			tempDrag.ClearValue(System.Windows.Controls.Control.BackgroundProperty);
		}
		if (e.Data.GetDataPresent(typeof(QTMTest).ToString()))
		{
			object data = e.Data.GetData(typeof(QTMTest).ToString());
			QTMTest qTMTest = data as QTMTest;
			QTMTestContainer tContainer = new QTMTestContainer();
			RegistryRoot.GetContainerForTest(qTMTest.Name, qTMTest.TargetName, out tContainer);
			BaseTest baseTest2 = null;
			switch (tContainer.ContainerType)
			{
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.HiveTest:
			{
				string[] array = tContainer.Name.Split('\\');
				HiveTest hiveTest = new HiveTest(qTMTest.Name, tContainer.TargetName, Root);
				hiveTest.HiveProperties.DLLName = array[array.Length - 1];
				ApplyParameterLogging(hiveTest);
				baseTest2 = hiveTest;
				break;
			}
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.ScriptTest:
			{
				ScriptTest scriptTest = new ScriptTest(qTMTest.Name, tContainer.TargetName, Root);
				ApplyParameterLogging(scriptTest);
				baseTest2 = scriptTest;
				break;
			}
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.LabVIEWTest:
			{
				LabVIEWTest labVIEWTest = new LabVIEWTest(qTMTest.Name, tContainer.TargetName, Root);
				ApplyParameterLogging(labVIEWTest);
				baseTest2 = labVIEWTest;
				break;
			}
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTest:
			{
				DotNetTest dotNetTest = new DotNetTest(qTMTest.Name, tContainer.TargetName, Root);
				FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(tContainer.Name);
				dotNetTest.DotNetProperties.MinDllVersion = versionInfo.FileVersion;
				dotNetTest.DotNetProperties.DllName = Path.GetFileName(versionInfo.FileName);
				ApplyParameterLogging(dotNetTest);
				baseTest2 = dotNetTest;
				break;
			}
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTestEx:
			{
				DotNetTestEx dotNetTestEx = new DotNetTestEx(qTMTest.Name, tContainer.TargetName, Root);
				ApplyParameterLogging(dotNetTestEx);
				baseTest2 = dotNetTestEx;
				break;
			}
			}
			if (baseTest2 == null)
			{
				return;
			}
			if (baseTest is RootTest)
			{
				AppMessageDialog.Show(baseTest2.Properties.TestName + " cannot be added to ROOT Level (Only Folders can be added)", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Warning);
			}
			else if (baseTest.Parent == Root && !baseTest.Properties.Expanded && !(baseTest2 is FolderTest))
			{
				if (baseTest is FolderTest)
				{
					_ = ((FolderTest)baseTest).TestList.Count;
					_ = 0;
				}
				if (!AddNewNode(baseTest, baseTest2, Position.First))
				{
					AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
				}
			}
			else if (!AddNewNode(baseTest, baseTest2, Position.First))
			{
				AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			RefreshTreeViewList(Root.TestList.ToList());
			BaseTest baseTest3 = baseTest2;
			if (baseTest3.Parent != null && ApplyParentProperties(baseTest3))
			{
				ApplyLeftIcons(baseTest2);
			}
			ResetTestTree(Root);
			if (baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count > 0)
			{
				UpdateCheckState(((FolderTest)baseTest).TestList[0]);
			}
			else
			{
				UpdateCheckState(baseTest);
			}
		}
		else
		{
			if (!e.Data.GetDataPresent(System.Windows.DataFormats.Serializable))
			{
				return;
			}
			object data2 = e.Data.GetData(System.Windows.DataFormats.Serializable);
			List<BaseTest> list = data2 as List<BaseTest>;
			foreach (BaseTest item in list)
			{
				if (ContainsNode(item, baseTest))
				{
					return;
				}
			}
			dListGlobal = new ArrayList();
			ArrayList arrayList = new ArrayList();
			foreach (BaseTest item2 in list)
			{
				if (item2 == tempDragNode)
				{
					tempDragNode = null;
					return;
				}
				if (item2 != null)
				{
					BaseTest baseTest4 = item2;
					BaseTest baseTest5 = baseTest4.Clone();
					if (IsInvalidTestCaseDrop(baseTest4, baseTest4 is TestCaseTest))
					{
						return;
					}
					if (baseTest is FolderTest)
					{
						baseTest5.Parent = (FolderTest)baseTest;
					}
					else
					{
						baseTest5.Parent = baseTest.Parent;
					}
					baseTest5.CreateLoopParentList(dListGlobal);
					arrayList.Add(baseTest5);
					bDragFromRegistry = false;
				}
				else
				{
					bDragFromRegistry = true;
				}
			}
			if (dListGlobal.Count > 0)
			{
				string text = "";
				foreach (DeletedLink item3 in dListGlobal)
				{
					text = text + "\n" + TestNodesColl[item3.ChildIndex].UltraTreeNodePath;
				}
				DialogResult dialogResult = AppMessageDialog.Show("Following Tests will be deleted from the Loop Conditions: " + text + "\nDo you want to continue..", "Loop Tests Deletion", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, DialogResult.OK, MessageDialogType.Warning);
				if (dialogResult == DialogResult.Cancel)
				{
					RefreshTreeViewList(Root.TestList.ToList());
					return;
				}
			}
			RemoveLoopTests(dListGlobal);
			RemoveLoopLinkTest(arrayList);
			if (TestTreeSelectionManager.SelectedTests[0].Parent != null)
			{
				FolderTest parent = TestTreeSelectionManager.SelectedTests[0].Parent;
				if (parent.FolderProperties.Scenarios != null && parent.FolderProperties.HasValidLoopDescription())
				{
					DialogResult dialogResult2 = AppMessageDialog.Show("Loop Descriptions should be modified for " + parent.Properties.TestName + ".\n               Do you want to continue?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning);
					if (dialogResult2 == DialogResult.No)
					{
						return;
					}
				}
			}
			if (!CheckDroppedNodeForLoopDescription(baseTest))
			{
				return;
			}
			_ = baseTest.Parent;
			FolderTest folderTest = new FolderTest();
			if (list[0] != baseTest && !IsValidCleanupFolderPosition(list[0], baseTest))
			{
				DialogResult dialogResult3 = AppMessageDialog.Show("Cleanup folder must be placed on the root.\nMoving this folder will clear the cleanup property.\nDo you want to move it and clear the cleanup property?", "Invalid Cleanup folder position", MessageBoxButtons.YesNo, DialogResult.Yes, MessageDialogType.Information);
				if (dialogResult3 != DialogResult.Yes)
				{
					return;
				}
				((FolderTest)list[0]).FolderProperties.IsCleanupFolder = false;
			}
			for (int i = 0; i < list.Count; i++)
			{
				BaseTest baseTest6 = list[list.Count - 1 - i];
				folderTest = baseTest6.Parent;
				BaseTest baseTest7 = baseTest6.Clone();
				if (baseTest != null && !baseTest6.Equals(baseTest))
				{
					if (baseTest == Root)
					{
						if (baseTest7 is FolderTest)
						{
							if (((FolderTest)baseTest6).FolderProperties.Scenarios != null)
							{
								if (((FolderTest)baseTest6).FolderProperties.Scenarios.Count == 0)
								{
									if (!bDragFromRegistry)
									{
										baseTest6.Parent.TestList.Remove(baseTest6);
										if (folderTest.TestList.Count > 0)
										{
											UpdateCheckState(folderTest.TestList[0]);
										}
										else
										{
											folderTest.Properties.CheckStateTest = CheckState.Unchecked;
										}
									}
									if (!AddNewNode(baseTest, baseTest7, Position.First))
									{
										AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
									}
								}
								else
								{
									AppMessageDialog.Show("Folder " + baseTest7.Properties.TestName + " with Loop cannot be added to ROOT level", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Warning);
								}
							}
							else
							{
								if (!bDragFromRegistry)
								{
									baseTest6.Parent.TestList.Remove(baseTest6);
									if (folderTest.TestList.Count > 0)
									{
										UpdateCheckState(folderTest.TestList[0]);
									}
									else
									{
										folderTest.Properties.CheckStateTest = CheckState.Unchecked;
									}
								}
								if (!AddNewNode(baseTest, baseTest7, Position.First))
								{
									AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
								}
							}
						}
						else
						{
							AppMessageDialog.Show(baseTest7.Properties.TestName + " cannot be added to ROOT level (Only Folders can be added)", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Warning);
						}
					}
					else if (baseTest.Parent == Root && !baseTest.Properties.Expanded && !(baseTest6 is FolderTest))
					{
						if (!(baseTest is FolderTest) || ((FolderTest)baseTest).TestList.Count <= 0)
						{
							if (!bDragFromRegistry)
							{
								baseTest6.Parent.TestList.Remove(baseTest6);
								if (folderTest.TestList.Count > 0)
								{
									UpdateCheckState(folderTest.TestList[0]);
								}
								else
								{
									folderTest.Properties.CheckStateTest = CheckState.Unchecked;
								}
							}
							if (!AddNewNode(baseTest, baseTest7, Position.First))
							{
								AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
							}
							baseTest7.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTest.png", "/QSPR;component/Icons/TestTreeTest.png");
						}
					}
					else
					{
						if (baseTest.Parent == Root && !baseTest.Properties.Expanded && baseTest6 is FolderTest && ((FolderTest)baseTest6).FolderProperties.Scenarios != null)
						{
							AppMessageDialog.Show("Folder " + baseTest6.Properties.TestName + " with Loop cannot be added to ROOT level", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Warning);
							continue;
						}
						if (!bDragFromRegistry)
						{
							baseTest6.Parent.TestList.Remove(baseTest6);
							if (folderTest.TestList.Count > 0)
							{
								UpdateCheckState(folderTest.TestList[0]);
							}
							else
							{
								folderTest.Properties.CheckStateTest = CheckState.Unchecked;
							}
						}
						if (!AddNewNode(baseTest, baseTest7, Position.First))
						{
							AppMessageDialog.Show("ERROR: Cannot Add a new node.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
						}
						if (baseTest7.TestUserInterfaceProperties.NodeImageUri == null)
						{
							baseTest7.ConfigureNodeImage("/QSPR;component/Icons/TestTreeTest.png", "/QSPR;component/Icons/TestTreeTest.png");
						}
					}
				}
				baseTest.Properties.Expanded = false;
				RefreshTreeViewList(Root.TestList.ToList());
				BaseTest baseTest8 = baseTest7;
				if (baseTest8.Parent != null && ApplyParentProperties(baseTest8))
				{
					ApplyLeftIcons(baseTest7);
				}
				ResetTestTree(Root);
				if (baseTest is FolderTest && ((FolderTest)baseTest).TestList.Count > 0)
				{
					UpdateCheckState(((FolderTest)baseTest).TestList[0]);
				}
				else
				{
					UpdateCheckState(baseTest);
				}
				TestTreeEditor.BeginTestNameEdit(baseTest7);
				TestTreeEditor.EndTestNameEdit(baseTest7, commit: false);
				TestTreeSelectionManager.SelectTest(baseTest7);
				CheckBranchOnTestIndex(baseTest8, baseTest);
				ApplyLeftIcons(baseTest7);
			}
		}
	}

	private bool IsInvalidTestCaseDrop(BaseTest DropNode, bool draggedSourceIsTestcase)
	{
		if (IsNodeInsideTestCase(DropNode))
		{
			if (draggedSourceIsTestcase)
			{
				AppMessageDialog.Show("Can not add a testcase inside another testcase.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
				return true;
			}
			if (IsNodeApprovedTestCase(DropNode))
			{
				AppMessageDialog.Show("This test case cannot be modified because it is in Approved state.\nSwith it to draft before making changes.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
				return true;
			}
		}
		return false;
	}

	private static bool IsTestCaseDrop(System.Windows.DragEventArgs e)
	{
		return !IsDraggedItemFromRegistryTree(e) && !IsDraggedItemFromTestTree(e);
	}

	private static bool IsDraggedItemFromRegistryTree(System.Windows.DragEventArgs e)
	{
		return e.Data.GetDataPresent(typeof(QTMTest));
	}

	private static bool IsDraggedItemFromTestTree(System.Windows.DragEventArgs e)
	{
		object data = e.Data.GetData(System.Windows.DataFormats.Serializable);
		return data is List<BaseTest>;
	}

	public bool AddScriptParameter(AddScriptParamInfo scriptParamInfo)
	{
		try
		{
			QTMTest testNode = null;
			QTMTestContainer containerNode = null;
			if (GetRegistryTestNode(scriptParamInfo.scriptTestName, matchCase: true, partialMatch: false, ref testNode, ref containerNode))
			{
				ParameterCls parameterCls = new ParameterCls();
				parameterCls.Name = scriptParamInfo.paramName.Trim();
				parameterCls.LowerLimit = scriptParamInfo.lowerLimit.Trim();
				parameterCls.Value = scriptParamInfo.value;
				parameterCls.UpperLimit = scriptParamInfo.upperLimit.Trim();
				parameterCls.Type = scriptParamInfo.ioType;
				parameterCls.DataType = scriptParamInfo.dataType;
				parameterCls.Unit = scriptParamInfo.unit.Trim();
				parameterCls.Description = scriptParamInfo.description.Trim();
				parameterCls.DisplayHint = 0;
				parameterCls.NoOfElements = 1;
				testNode.Parameters.Add(parameterCls);
				return true;
			}
			throw new Exception(scriptParamInfo.scriptTestName + " node can't be found in the test registry tree.");
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "AddScriptParameter failed, " + ex.Message, TraceMessageType.Exception);
			throw ex;
		}
	}

	internal bool EnableLoopRow(LoopRowInfo loopRowInfo, bool enableBasedOnValues = false)
	{
		bool result = false;
		try
		{
			if (Root.TestList.Count > 0 && loopRowInfo != null && !string.IsNullOrEmpty(loopRowInfo.TestName))
			{
				if (loopRowInfo.IsTestIndex)
				{
					BaseTest baseTest = TestNodesColl[loopRowInfo.TestName];
					if (baseTest != null)
					{
						List<int> list = new List<int>();
						if (enableBasedOnValues)
						{
							list = GetLoopRowIDsFromCondition(baseTest, loopRowInfo);
						}
						else
						{
							list.Add(loopRowInfo.RowID - 1);
						}
						foreach (int item in list)
						{
							if (baseTest.Properties.Scenarios.ConditionCheck.Count > item)
							{
								baseTest.Properties.Scenarios.ConditionCheck[item] = loopRowInfo.EnableRow;
								result = true;
							}
						}
						return result;
					}
					return false;
				}
				TestTreeSelectionManager.ClearSelections();
				loopRowInfo.TestName = GetRegexMatchString(loopRowInfo.TestName);
				BaseTest baseTest2 = Root;
				TestTreeSelectionManager.SelectTest(baseTest2);
				while (SearchNodes(baseTest2, loopRowInfo.TestName, WorkspaceConfig.SearchOptions.TestName, childrenOnly: false))
				{
					baseTest2 = TestTreeSelectionManager.SelectedTests[0];
					if (baseTest2 == null)
					{
						continue;
					}
					List<int> list2 = new List<int>();
					if (enableBasedOnValues)
					{
						list2 = GetLoopRowIDsFromCondition(baseTest2, loopRowInfo);
					}
					else
					{
						list2.Add(loopRowInfo.RowID - 1);
					}
					foreach (int item2 in list2)
					{
						if (baseTest2.Properties.Scenarios.ConditionCheck.Count > item2)
						{
							baseTest2.Properties.Scenarios.ConditionCheck[item2] = loopRowInfo.EnableRow;
							result = true;
						}
					}
				}
				return result;
			}
			throw new Exception("TestName or LoopRowInfo object is not valid.");
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "EnableLoopRow failed, " + ex.Message, TraceMessageType.Exception);
			throw ex;
		}
	}

	internal bool EnableDataLogging(DataLoggingInfo dataLogInfo)
	{
		bool flag = false;
		try
		{
			if (Root.TestList.Count > 0 && dataLogInfo != null && !string.IsNullOrEmpty(dataLogInfo.TestName))
			{
				if (dataLogInfo.IsTestIndex)
				{
					BaseTest baseTest = TestNodesColl[dataLogInfo.TestName];
					if (baseTest != null)
					{
						if (dataLogInfo.ParamName == string.Empty)
						{
							foreach (ParameterCls parameter2 in baseTest.Properties.Parameters)
							{
								parameter2.bEnableDataLogging = dataLogInfo.Enable;
							}
							flag = true;
						}
						else
						{
							ParameterCls parameter = baseTest.Properties.Parameters.GetParameter(dataLogInfo.ParamName);
							if (parameter == null)
							{
								return false;
							}
							parameter.bEnableDataLogging = dataLogInfo.Enable;
							flag = true;
						}
						return flag;
					}
					return false;
				}
				return false;
			}
			throw new Exception("TestName or DataLoggingInfo object is not valid.");
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "EnableDataLogging failed, " + ex.Message, TraceMessageType.Exception);
			throw ex;
		}
	}

	private List<int> GetLoopRowIDsFromCondition(BaseTest node, LoopRowInfo loopRowInfo)
	{
		List<int> list = new List<int>();
		if (node == null)
		{
			return list;
		}
		LoopScenarioValues scenarios = node.Properties.Scenarios;
		string[] source = loopRowInfo.LoopValues.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
		if (scenarios != null && scenarios.LoopConditions != null)
		{
			foreach (LoopCondition loopCondition in scenarios.LoopConditions)
			{
				if (!(loopCondition.LoopName == loopRowInfo.LoopName))
				{
					continue;
				}
				for (int i = 0; i < loopCondition.LoopValues.Count; i++)
				{
					string displayString = loopCondition.GetDisplayString(Root, loopCondition.LoopValues[i].ToString());
					if (source.Contains(displayString))
					{
						list.Add(i);
					}
				}
				break;
			}
		}
		return list;
	}

	internal string GetLoopValues(LoopRowInfo loopRowInfo)
	{
		string text = "";
		try
		{
			if (Root.TestList.Count > 0 && loopRowInfo != null && !string.IsNullOrEmpty(loopRowInfo.TestName))
			{
				if (loopRowInfo.IsTestIndex)
				{
					BaseTest baseTest = TestNodesColl[loopRowInfo.TestName];
					if (baseTest == null)
					{
						return null;
					}
					LoopScenarioValues scenarios = baseTest.Properties.Scenarios;
					if (scenarios != null && scenarios.LoopConditions != null)
					{
						foreach (LoopCondition loopCondition3 in scenarios.LoopConditions)
						{
							if (!(loopCondition3.LoopName == loopRowInfo.LoopName))
							{
								continue;
							}
							if (loopCondition3.LoopType == QC.QsprTestObjects.Loops.LoopTypes.BYSEQUENCE)
							{
								for (int i = 0; i < loopCondition3.LoopValues.Count; i++)
								{
									text = ((i != 0) ? (text + "," + loopCondition3.GetDisplayString(Root, loopCondition3.LoopValues[i].ToString())) : loopCondition3.GetDisplayString(Root, loopCondition3.LoopValues[i].ToString()));
								}
							}
							else
							{
								text = loopCondition3.LoopValuesAsString;
							}
						}
					}
				}
				TestTreeSelectionManager.ClearSelections();
				loopRowInfo.TestName = GetRegexMatchString(loopRowInfo.TestName);
				BaseTest baseTest2 = Root;
				TestTreeSelectionManager.SelectTest(baseTest2);
				while (SearchNodes(baseTest2, loopRowInfo.TestName, WorkspaceConfig.SearchOptions.TestName, childrenOnly: false))
				{
					baseTest2 = TestTreeSelectionManager.SelectedTests[0];
					if (baseTest2 == null)
					{
						continue;
					}
					LoopScenarioValues scenarios2 = baseTest2.Properties.Scenarios;
					foreach (LoopCondition loopCondition4 in scenarios2.LoopConditions)
					{
						if (!(loopCondition4.LoopName == loopRowInfo.LoopName))
						{
							continue;
						}
						if (loopCondition4.LoopType == QC.QsprTestObjects.Loops.LoopTypes.BYSEQUENCE)
						{
							for (int j = 0; j < loopCondition4.LoopValues.Count; j++)
							{
								text = ((j != 0) ? (text + "," + loopCondition4.GetDisplayString(Root, loopCondition4.LoopValues[j].ToString())) : loopCondition4.GetDisplayString(Root, loopCondition4.LoopValues[j].ToString()));
							}
						}
						else
						{
							text = loopCondition4.LoopValuesAsString;
						}
					}
				}
				return text;
			}
			throw new Exception("TestName or LoopRowInfo object is not valid.");
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "EnableLoopRow failed, " + ex.Message, TraceMessageType.Exception);
			throw ex;
		}
	}

	public string AddTestExcelUpload(AddTestInfo newTestInfo, BaseTest node)
	{
		if (!string.IsNullOrEmpty(newTestInfo.realName) && newTestInfo.newTestName != null && newTestInfo.destinationIndex != null && node != null)
		{
			if (node != null && !(node is RootTest))
			{
				if (node is FolderTest)
				{
					if (newTestInfo.position == Position.NextSibling || newTestInfo.position == Position.PreviousSibling)
					{
						node.Properties.Expanded = false;
					}
					else
					{
						node.Properties.Expanded = true;
					}
				}
				else if (newTestInfo.position != Position.PreviousSibling)
				{
					newTestInfo.position = Position.NextSibling;
				}
				QTMTest testNode = null;
				BaseTest newTest = null;
				QTMTestContainer containerNode = null;
				if (GetRegistryTestNode(newTestInfo.realName, matchCase: true, partialMatch: false, ref testNode, ref containerNode))
				{
					if (!containerNode.Loaded)
					{
						LoadContainer(containerNode, newContainer: false);
					}
					bDragFromRegistry = true;
					if (AddNewNode(node, testNode, out newTest, newTestInfo.position))
					{
						if (newTestInfo.newTestName != "")
						{
							newTest.Properties.TestName = newTestInfo.newTestName;
						}
						TreeChanged = true;
						TreeChangedDataCollection = true;
						ResetTestTree(newTest);
						return newTest.Index;
					}
					return null;
				}
				throw new Exception(newTestInfo.realName + " node can't be found in the test registry tree.");
			}
			throw new Exception("A valid test node was not selected. Valid nodes are tests or folders, excluding the root node.");
		}
		throw new Exception("RealName, TestName, and/or DestinationIndex object(s) are not valid.");
	}

	public string AddTest(AddTestInfo newTestInfo)
	{
		if (!string.IsNullOrEmpty(newTestInfo.realName) && newTestInfo.newTestName != null && newTestInfo.destinationIndex != null)
		{
			BaseTest baseTest = TestNodesColl[newTestInfo.destinationIndex];
			if (baseTest != null && !(baseTest is RootTest))
			{
				if (baseTest is FolderTest)
				{
					if (newTestInfo.position == Position.NextSibling || newTestInfo.position == Position.PreviousSibling)
					{
						baseTest.Properties.Expanded = false;
					}
					else
					{
						baseTest.Properties.Expanded = true;
					}
				}
				else if (newTestInfo.position != Position.PreviousSibling)
				{
					newTestInfo.position = Position.NextSibling;
				}
				QTMTest testNode = null;
				BaseTest newTest = null;
				QTMTestContainer containerNode = null;
				if (GetRegistryTestNode(newTestInfo.realName, matchCase: true, partialMatch: false, ref testNode, ref containerNode))
				{
					if (!containerNode.Loaded)
					{
						LoadContainer(containerNode, newContainer: false);
					}
					bDragFromRegistry = true;
					if (AddNewNode(baseTest, testNode, out newTest, newTestInfo.position))
					{
						if (newTestInfo.newTestName != "")
						{
							newTest.Properties.TestName = newTestInfo.newTestName;
						}
						TreeChanged = true;
						TreeChangedDataCollection = true;
						ResetTestTree(newTest);
						RefreshTreeViewList(Root.TestList.ToList());
						return newTest.Index;
					}
					return null;
				}
				throw new Exception(newTestInfo.realName + " node can't be found in the test registry tree.");
			}
			throw new Exception("A valid test node was not selected. Valid nodes are tests or folders, excluding the root node.");
		}
		throw new Exception("RealName, TestName, and/or DestinationIndex object(s) are not valid.");
	}

	public bool AddNewNode(BaseTest parentNode, QTMTest registryTest, out BaseTest newTest, Position insertPosition, bool isTestStep = false)
	{
		newTest = null;
		TraceMessage.Write(ToString(), "AddNewNode", TraceMessageType.Trace);
		try
		{
			bool flag = false;
			bool flag2 = false;
			int num = 0;
			bDragFromRegistry = true;
			QTMTestContainer tContainer = new QTMTestContainer();
			RegistryRoot.GetContainerForTest(registryTest.Name, registryTest.TargetName, out tContainer);
			switch (tContainer.ContainerType)
			{
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.HiveTest:
			{
				string[] array = tContainer.Name.Split('\\');
				HiveTest hiveTest = new HiveTest(registryTest.Name, tContainer.TargetName, Root);
				hiveTest.HiveProperties.DLLName = array[array.Length - 1];
				ApplyParameterLogging(hiveTest);
				newTest = hiveTest;
				break;
			}
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.ScriptTest:
			{
				ScriptTest scriptTest = new ScriptTest(registryTest.Name, tContainer.TargetName, Root);
				ApplyParameterLogging(scriptTest);
				newTest = scriptTest;
				break;
			}
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.LabVIEWTest:
			{
				LabVIEWTest labVIEWTest = new LabVIEWTest(registryTest.Name, tContainer.TargetName, Root);
				ApplyParameterLogging(labVIEWTest);
				newTest = labVIEWTest;
				break;
			}
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTest:
			{
				DotNetTest dotNetTest = new DotNetTest(registryTest.Name, tContainer.TargetName, Root);
				FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(tContainer.Name);
				dotNetTest.DotNetProperties.MinDllVersion = versionInfo.FileVersion;
				dotNetTest.DotNetProperties.DllName = Path.GetFileName(versionInfo.FileName);
				ApplyParameterLogging(dotNetTest);
				newTest = dotNetTest;
				break;
			}
			case QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTestEx:
			{
				DotNetTestEx dotNetTestEx = new DotNetTestEx(registryTest.Name, tContainer.TargetName, Root);
				ApplyParameterLogging(dotNetTestEx);
				newTest = dotNetTestEx;
				break;
			}
			}
			if (newTest != null)
			{
				newTest.Properties.CheckStateTest = CheckState.Checked;
			}
			if (Root.RootProperties.TreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan && !newTest.Properties.CanAddToTestPlan && !CanAddToTestPlan(parentNode, newTest))
			{
				AppMessageDialog.Show("Warning: This test is not set to add into a testplan. It should be put into a testcase.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			if (parentNode == Root)
			{
				if (parentNode.Properties.Expanded)
				{
					if (insertPosition == Position.Last)
					{
						num = ((FolderTest)parentNode).TestList.Count;
						flag = true;
					}
					else
					{
						num = 0;
						flag = true;
					}
				}
				else
				{
					num = ((FolderTest)parentNode).TestList.Count;
					flag = true;
				}
			}
			else if ((parentNode is FolderTest && !isTestStep) || (parentNode is TestCaseTest && (isTestStep || (parentNode as TestCaseTest).TestList.Count == 0)))
			{
				if (parentNode.Properties.Expanded || ((FolderTest)parentNode).TestList.Count == 0)
				{
					switch (insertPosition)
					{
					case Position.Last:
						num = ((FolderTest)parentNode).TestList.Count;
						flag = true;
						break;
					case Position.First:
						num = 0;
						flag = true;
						break;
					default:
						if (parentNode.Parent == Root && !(newTest is FolderTest))
						{
							return false;
						}
						switch (insertPosition)
						{
						case Position.NextSibling:
							num = parentNode.Parent.TestList.IndexOf((FolderTest)parentNode) + 1;
							flag2 = true;
							break;
						case Position.PreviousSibling:
							num = parentNode.Parent.TestList.IndexOf((FolderTest)parentNode);
							flag2 = true;
							break;
						}
						break;
					}
				}
				else if (parentNode.Parent is RootTest && !(newTest is FolderTest))
				{
					if (insertPosition == Position.NextSibling || insertPosition == Position.PreviousSibling)
					{
						return false;
					}
					num = 0;
					flag = true;
				}
				else
				{
					switch (insertPosition)
					{
					case Position.NextSibling:
						num = parentNode.Parent.TestList.IndexOf((FolderTest)parentNode) + 1;
						flag2 = true;
						break;
					case Position.PreviousSibling:
						num = parentNode.Parent.TestList.IndexOf((FolderTest)parentNode);
						flag2 = true;
						break;
					default:
						num = parentNode.Parent.TestList.IndexOf((FolderTest)parentNode) + 1;
						parentNode = parentNode.Parent;
						flag = true;
						break;
					}
				}
			}
			else
			{
				switch (insertPosition)
				{
				case Position.NextSibling:
					num = parentNode.Parent.TestList.IndexOf(parentNode) + 1;
					flag2 = true;
					break;
				case Position.PreviousSibling:
					num = parentNode.Parent.TestList.IndexOf(parentNode);
					flag2 = true;
					break;
				default:
					num = parentNode.Parent.TestList.IndexOf(parentNode) + 1;
					parentNode = parentNode.Parent;
					flag = true;
					break;
				}
			}
			if (flag)
			{
				if (num > 0)
				{
					BaseTest baseTest = ((FolderTest)parentNode).TestList[num - 1];
					if (num > 0 && baseTest is FolderTest && ((FolderTest)baseTest).FolderProperties.IsCleanupFolder)
					{
						num--;
					}
				}
				((FolderTest)parentNode).TestList.Insert(num, newTest);
				newTest.Parent = (FolderTest)parentNode;
			}
			else if (flag2)
			{
				parentNode.Parent.TestList.Insert(num, newTest);
				newTest.Parent = parentNode.Parent;
			}
			else
			{
				((FolderTest)parentNode).TestList.Add(newTest);
				newTest.Parent = (FolderTest)parentNode;
			}
			GlobalStatus.RegistrationStatus.TreeChanged = true;
			return true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "AddNewNode " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public bool GetRegistryTestNode(string realName, bool matchCase, bool partialMatch, ref QTMTest testNode, ref QTMTestContainer containerNode)
	{
		if (RegistryRoot.Targets.Count > 0)
		{
			QTMTarget qTMTarget = RegistryRoot.Target[0];
			bool flag = false;
			int num = 0;
			if (containerNode != null)
			{
				num = qTMTarget.TestContainers.IndexOf(containerNode);
			}
			for (int i = num; i < qTMTarget.TestContainers.Count; i++)
			{
				QTMTestContainer qTMTestContainer = qTMTarget.TestContainers[i];
				int num2 = 0;
				if (testNode != null)
				{
					num2 = qTMTestContainer.Tests.IndexOf(testNode);
					flag = true;
				}
				for (int j = num2; j < qTMTestContainer.Tests.Count; j++)
				{
					if (flag && j == num2)
					{
						continue;
					}
					QTMTest qTMTest = qTMTestContainer.Tests[j] as QTMTest;
					string text = qTMTest.Name;
					if ((qTMTestContainer.ContainerType == QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTest || qTMTestContainer.ContainerType == QC.QsprTestObjects.Tests.Base.QTMTestTypes.DotNetTestEx) && text.Contains('.'))
					{
						string[] array = null;
						array = text.Split('.');
						text = array[array.Length - 1];
					}
					if (partialMatch)
					{
						if (matchCase)
						{
							if (text.Contains(realName))
							{
								containerNode = qTMTestContainer;
								testNode = qTMTest;
								return true;
							}
						}
						else if (text.ToLower().Contains(realName.ToLower()))
						{
							containerNode = qTMTestContainer;
							testNode = qTMTest;
							return true;
						}
					}
					else if (string.Compare(text, realName, !matchCase) == 0)
					{
						containerNode = qTMTestContainer;
						testNode = qTMTest;
						return true;
					}
				}
			}
		}
		return false;
	}

	private bool ContainsNode(BaseTest node1, BaseTest node2)
	{
		TraceMessage.Write(ToString(), "ContainsNode", TraceMessageType.Trace);
		try
		{
			if (node2.Parent == null)
			{
				return false;
			}
			if (node2.Parent.Equals(node1))
			{
				return true;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ContainsNode " + ex.Message, TraceMessageType.Exception);
		}
		return ContainsNode(node1, node2.Parent);
	}

	private bool IsValidCleanupFolderPosition(object nodeTag, BaseTest DroppedNode)
	{
		if (!(nodeTag is FolderTest))
		{
			return true;
		}
		if (!((FolderTest)nodeTag).FolderProperties.IsCleanupFolder)
		{
			return true;
		}
		if (IsBeforeNonCleanupFolder(DroppedNode))
		{
			return false;
		}
		if (DroppedNode.Parent == null || DroppedNode.Properties.Expanded || DroppedNode.Parent.Parent != null)
		{
			return false;
		}
		return true;
	}

	private bool ApplyParentProperties(BaseTest tDragged)
	{
		bool result = false;
		if (!tDragged.Parent.Properties.LoggingEnabled)
		{
			tDragged.Properties.LoggingEnabled = false;
			result = true;
		}
		if (tDragged.Parent.Properties.ToolTest)
		{
			tDragged.Properties.ToolTest = true;
			result = true;
		}
		if (tDragged.Parent.Properties.FolderMustRun)
		{
			tDragged.Properties.FolderMustRun = true;
			result = true;
		}
		if (tDragged.Parent.Properties.TreeMustRun)
		{
			tDragged.Properties.TreeMustRun = true;
			result = true;
		}
		return result;
	}

	private static bool IsNodeInsideTestCase(BaseTest node)
	{
		if (node is TestCaseTest)
		{
			return false;
		}
		return node.TestCase != null;
	}

	private static bool IsNodeApprovedTestCase(BaseTest node)
	{
		if (node.TestCase != null)
		{
			return node.TestCase.TestCaseProperties.Status != ApprovalStates.Draft;
		}
		return false;
	}

	private static bool CanAddToTestPlan(BaseTest ParentNode, BaseTest NewNode)
	{
		if (NewNode is TestCaseTest)
		{
			return true;
		}
		if (ParentNode is TestCaseTest)
		{
			return false;
		}
		if (NewNode is FolderTest)
		{
			return true;
		}
		if (NewNode is DotNetTest)
		{
			DotNetTest dotNetTest = NewNode as DotNetTest;
			if (dotNetTest.DotNetProperties.CanAddToTestPlan)
			{
				return true;
			}
			if (dotNetTest.DotNetProperties.IsSetupTestStep)
			{
				return true;
			}
			if (dotNetTest.DotNetProperties.IsTearDownTestStep)
			{
				return true;
			}
		}
		return false;
	}

	private void ApplyParameterLogging(BaseTest tTest)
	{
		foreach (string globalInclude in TTInfo.GlobalIncludeList)
		{
			tTest.Properties.Parameters.DataLogging(globalInclude, bEnableLogging: true);
		}
		foreach (string globalExclude in TTInfo.GlobalExcludeList)
		{
			tTest.Properties.Parameters.DataLogging(globalExclude, bEnableLogging: false);
		}
	}

	private void testContextMenu_Run_Test_Click(object sender, RoutedEventArgs e)
	{
		_ = ((System.Windows.Controls.MenuItem)sender).DataContext;
		RunDebugTests();
	}

	public bool RenameNode(TestInfo testInfo)
	{
		try
		{
			if (!string.IsNullOrEmpty(testInfo.CurrTestName) && !string.IsNullOrEmpty(testInfo.NewTestName))
			{
				bool result = false;
				TestTreeSelectionManager.ClearSelections();
				TestTreeSelectionManager.SelectTest(Root);
				testInfo.CurrTestName = GetRegexMatchString(testInfo.CurrTestName);
				BaseTest baseTest = Root;
				while (SearchNodes(baseTest, testInfo.CurrTestName, WorkspaceConfig.SearchOptions.TestName, childrenOnly: false))
				{
					result = true;
					baseTest = TestTreeSelectionManager.SelectedTests[0];
					if (baseTest != null)
					{
						baseTest.Properties.TestName = testInfo.NewTestName;
					}
				}
				return result;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "RenameNode failed, " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public CallbackResultInfo SyncTest(string testName)
	{
		CallbackResultInfo result = default(CallbackResultInfo);
		try
		{
			TestTreeSelectionManager.ClearSelections();
			if (!string.IsNullOrEmpty(testName))
			{
				TestTreeSelectionManager.SelectTest(Root);
				BaseTest baseTest = Root;
				testName = GetRegexMatchString(testName);
				while (SearchNodes(baseTest, testName, WorkspaceConfig.SearchOptions.TestName, childrenOnly: false))
				{
					baseTest = TestTreeSelectionManager.SelectedTests[0];
					if (baseTest != null)
					{
						result.Result = true;
						Synchronize(null);
					}
				}
			}
			else
			{
				TestTreeSelectionManager.SelectTest(Root);
				result.Result = true;
				Synchronize(null);
			}
			return result;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SyncTest failed, " + ex.Message, TraceMessageType.Exception);
		}
		result.Result = false;
		return result;
	}

	internal CallbackResultInfo SetTestParamLimits(ParamInfo paramInfo)
	{
		CallbackResultInfo result = default(CallbackResultInfo);
		try
		{
			if (!string.IsNullOrEmpty(paramInfo.ParameterName) && !string.IsNullOrEmpty(paramInfo.TestName) && Root.TestList.Count > 0)
			{
				TestTreeSelectionManager.ClearSelections();
				TestTreeSelectionManager.SelectTest(Root);
				if (paramInfo.IsTestIndex)
				{
					BaseTest baseTest = TestNodesColl[paramInfo.TestName];
					if (baseTest != null)
					{
						if (baseTest.Properties.Parameters.HasParameter(paramInfo.ParameterName, exactMatch: true, out var _))
						{
							result.Message = UpdateParamLimits(paramInfo, baseTest);
						}
						if (string.IsNullOrEmpty(result.Message.ToString()))
						{
							result.Result = true;
						}
						else
						{
							result.Result = false;
						}
						return result;
					}
					result.Message = "SetTestParamLimits failed, invalid test index specified";
					result.Result = false;
					return result;
				}
				paramInfo.TestName = GetRegexMatchString(paramInfo.TestName);
				BaseTest baseTest2 = Root;
				while (SearchNodes(baseTest2, paramInfo.TestName, WorkspaceConfig.SearchOptions.TestName, childrenOnly: false))
				{
					baseTest2 = TestTreeSelectionManager.SelectedTests[0];
					if (baseTest2 != null && baseTest2.Properties.Parameters.HasParameter(paramInfo.ParameterName, exactMatch: true, out var _))
					{
						result.Message = UpdateParamLimits(paramInfo, baseTest2);
					}
				}
				if (string.IsNullOrEmpty(result.Message.ToString()))
				{
					result.Result = true;
				}
				else
				{
					result.Result = false;
				}
				return result;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SetTestParamLimits failed, " + ex.Message, TraceMessageType.Exception);
		}
		result.Result = false;
		return result;
	}

	private string UpdateParamLimits(ParamInfo paramInfo, BaseTest temp)
	{
		try
		{
			if (!string.IsNullOrEmpty(paramInfo.LowerLimit))
			{
				temp.Properties.Parameters.SetParamLowerLimit(paramInfo.ParameterName, paramInfo.LowerLimit, paramInfo.Index);
			}
			if (!string.IsNullOrEmpty(paramInfo.UpperLimit))
			{
				temp.Properties.Parameters.SetParamUpperLimit(paramInfo.ParameterName, paramInfo.UpperLimit, paramInfo.Index);
			}
		}
		catch (Exception ex)
		{
			return $"Failed to update parameter {paramInfo.ParameterName}; Error {ex.Message}: ";
		}
		return "";
	}

	internal CallbackResultInfo RunTest(string TestName)
	{
		CallbackResultInfo result = default(CallbackResultInfo);
		result.Result = false;
		try
		{
			if (string.IsNullOrEmpty(TestName))
			{
				TestTreeSelectionManager.ClearSelections();
				TestTreeSelectionManager.SelectTest(Root);
				result.Result = RunDebugTests();
				result.Message = "Root test ran.";
				return result;
			}
			if (Root.TestList.Count > 0)
			{
				TestTreeSelectionManager.ClearSelections();
				TestTreeSelectionManager.SelectTest(Root);
				string regexMatchString = GetRegexMatchString(TestName);
				BaseTest currentNode = TestTreeSelectionManager.SelectedTests[0];
				if (SearchNodes(currentNode, regexMatchString, WorkspaceConfig.SearchOptions.TestName, childrenOnly: false))
				{
					currentNode = TestTreeSelectionManager.SelectedTests[0];
					if (currentNode != null)
					{
						result.Result = RunDebugTests();
						result.Message = TestName + " ran.";
						return result;
					}
				}
				result.Result = false;
				result.Message = "RunTest failed: testName was not found in the tree.";
			}
		}
		catch (Exception ex)
		{
			result.Result = false;
			result.Message = ex.Message;
			TraceMessage.Write(ToString(), "RunTest failed, " + ex.Message, TraceMessageType.Exception);
		}
		return result;
	}

	private bool RunDebugTests()
	{
		TraceMessage.Write(ToString(), "RunDebugTests", TraceMessageType.Trace);
		try
		{
			QTMGlobalVariable.SetGlobalVariable("LOGGING_ENABLED", "");
			if (TestTreeSelectionManager.SelectedTests.Count > 0)
			{
				TraceMessage.Write(ToString(), "RunTest", TraceMessageType.Trace);
				try
				{
					FolderTest folderTest = new FolderTest("MultipleSelect");
					foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
					{
						ResetTestTree(selectedTest);
						folderTest.AddDummyTest(selectedTest);
					}
					Analytics.WriteAnalytics("RunDebugTests", "Debug test run (right-click) started");
					_scheduler.ScheduleTests(folderTest, Scheduler.TestingType.Debug);
					if (TestTreeSelectionManager.SelectedTests.Count > 0)
					{
						UpdateTestTreeSelections(TestTreeSelectionManager.SelectedTests[0]);
					}
					Analytics.WriteAnalytics("RunDebugTests", "Debug test run (right-click) finished");
					return true;
				}
				catch (Exception ex)
				{
					TraceMessage.Write(ToString(), "RunTest " + ex.Message, TraceMessageType.Exception);
				}
			}
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "RunDebugTests " + ex2.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private bool RunSetupTests()
	{
		TraceMessage.Write(ToString(), "RunSetupTests", TraceMessageType.Trace);
		try
		{
			try
			{
				RootTest root = Root;
				FolderTest folderTest;
				try
				{
					folderTest = (FolderTest)root.TestList[0];
					ResetTestTree(Root);
				}
				catch
				{
					return true;
				}
				if (folderTest.FolderProperties.IsSetupFolder)
				{
					FolderTest folderTest2 = new FolderTest("MultipleSelect");
					ResetTestTree(Root);
					folderTest2.AddDummyTest(folderTest);
					_scheduler.ResetGlobals(Root);
					if (!_scheduler.ScheduleTests(folderTest2, Scheduler.TestingType.Debug))
					{
						GlobalStatus.SetupTestStatus = TestResult.Failed;
					}
					else
					{
						GlobalStatus.SetupTestStatus = TestResult.Passed;
					}
				}
				return true;
			}
			catch (Exception ex)
			{
				TraceMessage.Write(ToString(), "RunSetupTests " + ex.Message, TraceMessageType.Exception);
			}
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "RunSetupTests " + ex2.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private void testTreeView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
	{
		isDblClicked = true;
		TreeViewItem treeViewItem = null;
		DependencyObject depObject = (DependencyObject)e.OriginalSource;
		treeViewItem = depObject.FindParent<TreeViewItem>();
		if (treeViewItem != null && treeViewItem.DataContext is BaseTest)
		{
			if (nodeExpandedStateBeforeDoubleClick.HasValue)
			{
				treeViewItem.IsExpanded = nodeExpandedStateBeforeDoubleClick.Value;
			}
			nodeExpandedStateBeforeDoubleClick = null;
			BaseTest baseTest = treeViewItem.DataContext as BaseTest;
			if (_scheduler.QTMData.WConfig.DoubleClickRunsTest && e.ChangedButton == MouseButton.Left && !baseTest.TestUserInterfaceProperties.IsInEditMode)
			{
				RunDebugTests();
			}
		}
	}

	private void TestNameEditTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
	{
		if (sender is System.Windows.Controls.TextBox textBox)
		{
			BaseTest baseTest = textBox.DataContext as BaseTest;
			if (e.Key == Key.Return)
			{
				TestTreeEditor.EndTestNameEdit(baseTest, commit: true);
			}
			else if (e.Key == Key.Escape)
			{
				TestTreeEditor.EndTestNameEdit(baseTest, commit: false);
			}
		}
	}

	private void TestNameEditTextBox_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
	{
		System.Windows.Controls.TextBox textBox = sender as System.Windows.Controls.TextBox;
		BaseTest baseTest = textBox.DataContext as BaseTest;
		if (baseTest.TestUserInterfaceProperties.IsInEditMode)
		{
			textBox.Dispatcher.BeginInvoke((Action)delegate
			{
				textBox.Focus();
				Keyboard.Focus(textBox);
				textBox.CaretIndex = baseTest.Properties.TestName.Length;
			}, DispatcherPriority.Render);
		}
	}

	private void RegistryTreeContextMenuItem_Click(object sender, RoutedEventArgs e)
	{
		System.Windows.Controls.MenuItem menuItem = sender as System.Windows.Controls.MenuItem;
		RegistryTreeContextMenuMessages(Convert.ToString(menuItem.Tag));
	}

	private void RegistryContainerNameEditTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
	{
		if (sender is System.Windows.Controls.TextBox textBox)
		{
			QTMTestContainer qtmTestContainer = textBox.DataContext as QTMTestContainer;
			if (e.Key == Key.Return)
			{
				RegistryTreeEditor.EndContainerNameEdit(qtmTestContainer, commit: true);
			}
			else if (e.Key == Key.Escape)
			{
				RegistryTreeEditor.EndContainerNameEdit(qtmTestContainer, commit: false);
			}
		}
	}

	private void RegistryContainerNameEditTextBox_LostFocus(object sender, RoutedEventArgs e)
	{
		System.Windows.Controls.TextBox textBox = sender as System.Windows.Controls.TextBox;
		if (textBox.DataContext is QTMTestContainer)
		{
			QTMTestContainer qTMTestContainer = textBox.DataContext as QTMTestContainer;
			if (qTMTestContainer.UserInterfaceProperties.IsInEditMode)
			{
				RegistryTreeEditor.EndContainerNameEdit(qTMTestContainer, commit: true);
			}
		}
	}

	private void RegistryContainerNameEditTextBox_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
	{
		System.Windows.Controls.TextBox textBox = sender as System.Windows.Controls.TextBox;
		if (textBox.Visibility == Visibility.Visible)
		{
			textBox.Dispatcher.BeginInvoke((Action)delegate
			{
				textBox.Focus();
				Keyboard.Focus(textBox);
				textBox.CaretIndex = textBox.Text.Length;
			}, DispatcherPriority.Render);
		}
	}

	private void testTreeView_DragOver(object sender, System.Windows.DragEventArgs e)
	{
		if (QSecurity.LockedQGroup || !QSecurity.IsTechnician)
		{
			return;
		}
		TreeViewItem treeViewItem = null;
		DependencyObject dependencyObject = e.OriginalSource as DependencyObject;
		if (dependencyObject is TextBlock || dependencyObject is System.Windows.Controls.Image)
		{
			treeViewItem = dependencyObject.FindParent<TreeViewItem>();
		}
		if (treeViewItem == null || !(treeViewItem.DataContext is BaseTest))
		{
			return;
		}
		if (QSecurity.LockedQGroup)
		{
			e.Effects = System.Windows.DragDropEffects.None;
			return;
		}
		if (tempDrag != null)
		{
			tempDrag.ClearValue(System.Windows.Controls.Control.BackgroundProperty);
		}
		BaseTest baseTest = treeViewItem.DataContext as BaseTest;
		if (baseTest != null)
		{
			if (baseTest.Properties.LinkNode)
			{
				baseTest = null;
				tempDrag = null;
				e.Effects = System.Windows.DragDropEffects.None;
			}
			else
			{
				e.Effects = System.Windows.DragDropEffects.All;
			}
			if (baseTest != null && baseTest is FolderTest && !baseTest.Properties.LinkNode)
			{
				if (((FolderTest)baseTest).FolderProperties.LinkRoot)
				{
					bool? isLinkActive = ((FolderTest)baseTest).FolderProperties.IsLinkActive;
					if (isLinkActive.GetValueOrDefault() && isLinkActive.HasValue && baseTest.Properties.Expanded)
					{
						baseTest = null;
						tempDrag = null;
						e.Effects = System.Windows.DragDropEffects.None;
						goto IL_0122;
					}
				}
				e.Effects = System.Windows.DragDropEffects.All;
			}
			goto IL_0122;
		}
		goto IL_014a;
		IL_0122:
		if (baseTest != null && !TestTreeSelectionManager.SelectedTests.Contains(baseTest))
		{
			treeViewItem.Background = System.Windows.Media.Brushes.CornflowerBlue;
			tempDrag = treeViewItem;
		}
		goto IL_014a;
		IL_014a:
		if (lastTreeViewItemDragOver == treeViewItem)
		{
			if (DateTime.Now.Subtract(lastDragOverTime).TotalSeconds > 1.5 && !treeViewItem.IsExpanded)
			{
				treeViewItem.IsExpanded = true;
			}
		}
		else
		{
			lastDragOverTime = DateTime.Now;
			lastTreeViewItemDragOver = treeViewItem;
		}
	}

	private void testTreeView_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
	{
	}

	private void testTreeViewItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
	{
		TreeViewItem treeViewItem = null;
		RaiseTreeFocusChanged(focused: true);
		DependencyObject dependencyObject = e.OriginalSource as DependencyObject;
		if (dependencyObject is TextBlock || dependencyObject is System.Windows.Controls.Image)
		{
			treeViewItem = dependencyObject.FindParent<TreeViewItem>();
		}
		if (treeViewItem == null || !(treeViewItem.DataContext is BaseTest))
		{
			return;
		}
		BaseTest baseTest = treeViewItem.DataContext as BaseTest;
		nodeExpandedStateBeforeDoubleClick = baseTest.Properties.Expanded;
		if (e.ClickCount == 1)
		{
			if (TestTreeSelectionManager.SelectedTests.Contains(baseTest) && TestTreeSelectionManager.SelectedTests.Count == 1 && e.ChangedButton == MouseButton.Left)
			{
				WaitForDoubleClick(baseTest);
			}
			else if (e.ChangedButton == MouseButton.Left || (e.ChangedButton == MouseButton.Right && TestTreeSelectionManager.SelectedTests.Count == 1))
			{
				bool shiftPressed = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
				bool ctrlPressed = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);
				TestTreeSelectionManager.SelectTest(baseTest, shiftPressed, ctrlPressed);
			}
		}
	}

	private void WaitForDoubleClick(BaseTest baseTest)
	{
		Task.Factory.StartNew(delegate
		{
			int num = 100;
			while (num > 0 && !isDblClicked)
			{
				num--;
				Thread.Sleep(10);
			}
			if (!isDblClicked && baseTest.CanRename)
			{
				TestTreeEditor.BeginTestNameEdit(baseTest);
			}
			else
			{
				isDblClicked = false;
			}
		});
	}

	private void treeRegistry_MouseDown(object sender, MouseButtonEventArgs e)
	{
		if (e.ChangedButton != MouseButton.Right)
		{
			return;
		}
		TreeViewItem treeViewItem = null;
		DependencyObject dependencyObject = e.OriginalSource as DependencyObject;
		if (dependencyObject is TextBlock || dependencyObject is System.Windows.Controls.Image)
		{
			while (dependencyObject != null && !(dependencyObject is TreeViewItem))
			{
				dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
			}
			treeViewItem = dependencyObject as TreeViewItem;
		}
		if (treeViewItem != null)
		{
			treeViewItem.IsSelected = true;
		}
	}

	private void testTreeViewItem_StackPanel_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
	{
		TraceMessage.Write(ToString(), "ultraTreeTTDView_SelectionDragStart", TraceMessageType.Trace);
		try
		{
			TreeViewItem treeViewItem = null;
			DependencyObject dependencyObject = e.OriginalSource as DependencyObject;
			if (dependencyObject is TextBlock || dependencyObject is System.Windows.Controls.Image || dependencyObject is StackPanel)
			{
				while (dependencyObject != null && !(dependencyObject is TreeViewItem))
				{
					dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
				}
				treeViewItem = dependencyObject as TreeViewItem;
			}
			if (treeViewItem == null || testTreeView == null || e.LeftButton != MouseButtonState.Pressed)
			{
				return;
			}
			BaseTest baseTest = TestTreeSelectionManager.SelectedTests[0];
			if (baseTest.Properties.LinkNode || GlobalStatus.TestRunning)
			{
				return;
			}
			System.Windows.DataObject dataObject = new System.Windows.DataObject(System.Windows.DataFormats.Serializable, TestTreeSelectionManager.SelectedTests.ToList());
			List<TestCaseMaster> list = new List<TestCaseMaster>();
			List<string> list2 = new List<string>();
			foreach (BaseTest selectedTest in TestTreeSelectionManager.SelectedTests)
			{
				if (selectedTest is RootTest)
				{
					if (!Directory.Exists("c:\\qualcomm\\qspr\\testplans\\"))
					{
						Directory.CreateDirectory("c:\\qualcomm\\qspr\\testplans\\");
					}
					string text = "c:\\qualcomm\\qspr\\testplans\\testplan.xtt";
					if (File.Exists(text))
					{
						File.Delete(text);
					}
					GenerateDynamicLimitsXmlFile();
					TestPlanMaster data = _testPlanDragDrop.CreateTestPlanData((RootTest)selectedTest, text);
					dataObject.SetData(typeof(TestPlanMaster), data);
					dataObject.SetData("DragSource", "QSPR");
					DragDrop.DoDragDrop(testTreeView, dataObject, System.Windows.DragDropEffects.Copy);
					return;
				}
				baseTest = selectedTest;
				if (TestCasesPluginsColl.Count > 0)
				{
					TestCaseMaster testCaseMaster = TestCaseDragDrop.CreateTestCaseData(baseTest);
					if (testCaseMaster != null)
					{
						list.Add(testCaseMaster);
						list2.Add(baseTest.Index);
					}
				}
			}
			if (list.Count > 0)
			{
				dataObject.SetData(typeof(List<TestCaseMaster>), list);
			}
			dataObject.SetData(typeof(List<string>), list2);
			dataObject.SetData("DragSource", "QSPR");
			DragDrop.DoDragDrop(testTreeView, dataObject, System.Windows.DragDropEffects.Copy);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ultraTreeTTDView_SelectionDragStart " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void registryTreeViewItem_StackPanel_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
	{
		if (sender == null || !(sender is StackPanel))
		{
			return;
		}
		StackPanel depObject = sender as StackPanel;
		TreeViewItem treeViewItem = depObject.FindParent<TreeViewItem>();
		if (treeViewItem == null || treeRegistry == null || e.LeftButton != MouseButtonState.Pressed || treeRegistry.SelectedItem == null || !(treeRegistry.SelectedItem is QTMTestContainerItem))
		{
			return;
		}
		QTMTestContainerItem qTMTestContainerItem = treeRegistry.SelectedItem as QTMTestContainerItem;
		if (qTMTestContainerItem.Object != null && qTMTestContainerItem.Object is QTMTest)
		{
			QTMTestContainer testContainer = qTMTestContainerItem.TestContainer;
			if (testContainer.Loaded)
			{
				QTMTest data = qTMTestContainerItem.Object as QTMTest;
				DragDrop.DoDragDrop(treeRegistry, data, System.Windows.DragDropEffects.Copy);
			}
			else
			{
				LoadContainer(testContainer, newContainer: false);
				RegistryTreeBrowser.ExpandAll(testContainer);
			}
		}
	}

	private void TestNameEditTextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
	{
		System.Windows.Controls.TextBox textBox = sender as System.Windows.Controls.TextBox;
		if (textBox.DataContext is BaseTest)
		{
			BaseTest baseTest = textBox.DataContext as BaseTest;
			if (baseTest.TestUserInterfaceProperties.IsInEditMode)
			{
				TestTreeEditor.EndTestNameEdit(baseTest, commit: true);
			}
		}
	}

	private void TreeGrid_MouseDown(object sender, MouseButtonEventArgs e)
	{
		TreeGrid.Focus();
		bool focused = true;
		if ((FrameworkElement)e.Source is Expander expander && expander == TreePropertiesExpander)
		{
			focused = false;
		}
		else
		{
			Expander expander2 = ((FrameworkElement)e.Source).FindParent<Expander>();
			if (expander2 != null && expander2 == TreePropertiesExpander)
			{
				focused = false;
			}
		}
		RaiseTreeFocusChanged(focused);
	}

	private void TestNameEditTextBox_LostFocus(object sender, RoutedEventArgs e)
	{
		System.Windows.Controls.TextBox textBox = sender as System.Windows.Controls.TextBox;
		if (textBox.DataContext is BaseTest)
		{
			BaseTest baseTest = textBox.DataContext as BaseTest;
			if (baseTest.TestUserInterfaceProperties.IsInEditMode)
			{
				TestTreeEditor.EndTestNameEdit(baseTest, commit: true);
			}
		}
	}

	private void TestNameEditTextBox_Initialized(object sender, EventArgs e)
	{
		System.Windows.Controls.TextBox textBox = sender as System.Windows.Controls.TextBox;
		if (!(textBox.Text == "Folder"))
		{
			return;
		}
		BaseTest baseTest = textBox.DataContext as BaseTest;
		if (baseTest.TestUserInterfaceProperties.IsInEditMode)
		{
			textBox.Dispatcher.BeginInvoke((Action)delegate
			{
				textBox.Focus();
				Keyboard.Focus(textBox);
				textBox.CaretIndex = baseTest.Properties.TestName.Length;
			}, DispatcherPriority.Render);
		}
	}

	private void testTreeView_DragLeave(object sender, System.Windows.DragEventArgs e)
	{
		if (tempDrag != null)
		{
			tempDrag.ClearValue(System.Windows.Controls.Control.BackgroundProperty);
		}
	}

	private void TreePropertiesExpander_Collapsed(object sender, RoutedEventArgs e)
	{
		treeViewColumn.Width = new GridLength(1.0, GridUnitType.Star);
		treePropertiesColumn.Width = new GridLength(1.0, GridUnitType.Auto);
		e.Handled = true;
	}

	private void TreePropertiesExpander_Expanded(object sender, RoutedEventArgs e)
	{
		treePropertiesColumn.Width = new GridLength(1.0, GridUnitType.Star);
		e.Handled = true;
	}

	public void CollapseTreeProperties()
	{
		TreePropertiesExpander.IsExpanded = false;
	}

	public void ExpandTreeProperties()
	{
		TreePropertiesExpander.IsExpanded = true;
	}

	public void RaiseTreeFocusChanged(bool focused)
	{
		if (OnTestTreeFocusChanged != null)
		{
			OnTestTreeFocusChanged(focused);
		}
	}

	private void testTreeView_GotFocus(object sender, RoutedEventArgs e)
	{
		RaiseTreeFocusChanged(focused: true);
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.TestTree;
	}

	private void testTreeView_LostFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.None;
	}

	private void treeViewSubTabControl_GotFocus(object sender, RoutedEventArgs e)
	{
		RaiseTreeFocusChanged(focused: false);
	}

	private void treeViewSubTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		if (e.RemovedItems.Contains(tabItemParameters))
		{
			ttdParameterView.SaveCurrentDataGridSettings();
			ttdParameterView.SaveLayout();
		}
		RaiseTreeFocusChanged(focused: false);
	}

	private void treeRegistry_Selected(object sender, RoutedEventArgs e)
	{
		TreeViewItem element = (TreeViewItem)e.OriginalSource;
		Keyboard.Focus(element);
	}

	internal void SetTreeType(QC.QsprTestObjects.Tests.Base.TreeTypes treeTypes)
	{
		bLoadingTree = true;
		Root.RootProperties.TreeType = treeTypes;
		if (treeTypes == QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan)
		{
			if (!(Root.RootProperties is TestPlanProperties))
			{
				Root.RootProperties = new TestPlanProperties(Root.RootProperties);
				testTreeView.ItemsSource = null;
				testTreeView.ItemsSource = Tests;
			}
		}
		else if (Root.RootProperties == null)
		{
			Root.RootProperties = new RootTestProperties(Root.RootProperties);
			testTreeView.ItemsSource = null;
			testTreeView.ItemsSource = Tests;
		}
		bLoadingTree = false;
	}

	private void CheckBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
	{
		TreeViewItem treeViewItem = null;
		DependencyObject dependencyObject = e.Source as DependencyObject;
		if (dependencyObject is System.Windows.Controls.CheckBox)
		{
			treeViewItem = dependencyObject.FindParent<TreeViewItem>();
		}
		if (treeViewItem != null && treeViewItem.DataContext is BaseTest)
		{
			BaseTest baseTest = treeViewItem.DataContext as BaseTest;
			if (baseTest.IsTestStep)
			{
				e.Handled = true;
			}
		}
	}

	private void treeRegistry_GotFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.TreeRegistry;
	}

	private void treeRegistry_LostFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.None;
	}

	private void PropertiesTab_GotFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.PropertyView;
	}

	private void PropertiesTab_LostFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.None;
	}

	private void RegistryTab_GotFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.TreeRegistry;
	}

	private void RegistryTab_LostFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.None;
	}

	private void ParametersTab_GotFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.ParameterView;
	}

	private void ParametersTab_LostFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.None;
	}

	private void LoopTab_GotFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.LoopView;
	}

	private void LoopTab_LostFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.None;
	}

	[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
	[DebuggerNonUserCode]
	internal Delegate _CreateDelegate(Type delegateType, string handler)
	{
		return Delegate.CreateDelegate(delegateType, this, handler);
	}
}
