using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using QC.QDM.Libraries.DataAccessLibrary;
using QC.QSPRLogSchema;
using QC.QTMTreeXMLHandler;
using QC.QTMXmlSchema;
using QC.XmlToDBPreProcess;

namespace XmlForDB;

public class ConvertQTMToDB
{
	private SqlConnection sqlConnection = new SqlConnection();

	private XmlDocument xmlMainDoc = new XmlDocument();

	private ROOT xmlFile = new ROOT();

	private string strFileToBeConverted = string.Empty;

	private bool ignoreDBSettings;

	private Dictionary<NodeInfo, string> hashNodeInfo = new Dictionary<NodeInfo, string>();

	private DataAccess dataAccess;

	private QTMTreeXMLRegistration qtmTreeXMLRegistration = new QTMTreeXMLRegistration();

	private RunTitleOptonsRID runTitleOptionsRID;

	private ResultOptionsRID resultOptionsRID;

	private ErrorCodeOptonsRID errorCodeOptionsRID;

	private SubErrorCodeCombinedOptionsRID subErrorCodeCombinedOptionsRID;

	private SubErrorCodeDetailsRID subErrorCodeDetailsRID;

	private SubErrorCodeOptionsRID subErrorCodeOptionsRID;

	private SessionSubErrorCodeData sessionSubErrorCodeData;

	private ParamResultOptionsRID paramResultOptionsRID;

	private ScenarioSplitOptionsRID scenarioSplitOptionsRID;

	private ScenarioCombinedOptionsRID scenarioCombinedOptionsRID;

	private ScenarioSplitConditionsRID scenarioSplitConditionsRID;

	private NodeRID nodeRID;

	private NodeDetailsRID nodeDetailsRID;

	private ParamDetailsRID paramDetailsRID;

	private ParamRID paramRID;

	private ParamArrayRID paramArrayRID;

	private ParamAttributesRID paramAttributesRID;

	private System.Data.DataSet databasePropertiesDs;

	private static bool isDatabaseEvaluated = false;

	public static bool isV3File = false;

	private string runtitleOptionsString = Constants.STPROC_GETRUNTITLEOPTIONS;

	private string resultOptionsRIDString = Constants.STPROC_GETRESULTOPTIONSRID;

	private string errorCodeRIDString = Constants.STPROC_GETERRORCODE;

	private string paramResultOptionsRIDString = Constants.STPROC_GETPARAMRESULTOPTIONS;

	private string scenarioSplitOptionsRIDString = Constants.STPROC_GETSCENARIOSPLITOPTIONS;

	private string scenarioCombinedOptionsRIDString = Constants.STPROC_GETSCENARIOCOMBINEDOPTIONS;

	private static List<string> nodeDetailsTreeRIDList = new List<string>();

	private static List<string> nodeRIDTreeList = new List<string>();

	private static List<string> paramDetailsRIDTreeList = new List<string>();

	private static List<string> paramRIDTreeList = new List<string>();

	private static List<string> paramArrayRIDTreeList = new List<string>();

	private static List<string> scenarioSplitConditionsTreeList = new List<string>();

	private static bool isNewSchema = false;

	private static bool processParamAttributes = false;

	private static bool processParamArrayData = false;

	public bool DatabaseEvaluated
	{
		get
		{
			return isDatabaseEvaluated;
		}
		set
		{
			isDatabaseEvaluated = value;
		}
	}

	public bool IgnoreFileDBSetting
	{
		get
		{
			return ignoreDBSettings;
		}
		set
		{
			ignoreDBSettings = value;
		}
	}

	public string DatabaseName
	{
		get
		{
			return dataAccess.DatabaseName;
		}
		set
		{
			dataAccess.DatabaseName = value;
		}
	}

	public string ServerName
	{
		get
		{
			return dataAccess.ServerName;
		}
		set
		{
			dataAccess.ServerName = value;
		}
	}

	public int ConnectionTimeout
	{
		get
		{
			return dataAccess.ConnectionTimeout;
		}
		set
		{
			dataAccess.ConnectionTimeout = value;
		}
	}

	public int CommandTimeout
	{
		get
		{
			return dataAccess.CommandTimeout;
		}
		set
		{
			dataAccess.CommandTimeout = value;
		}
	}

	public string UserName
	{
		get
		{
			return dataAccess.UserName;
		}
		set
		{
			if (value != string.Empty || value != null)
			{
				dataAccess.UserName = value;
			}
			else
			{
				dataAccess.UserName = Constants.USER_NAME;
			}
		}
	}

	public string Password
	{
		get
		{
			return dataAccess.Password;
		}
		set
		{
			if (value != string.Empty || value != null)
			{
				dataAccess.Password = value;
			}
			else
			{
				dataAccess.Password = Constants.PASSWORD;
			}
		}
	}

	public bool IsNewSchema
	{
		get
		{
			return isNewSchema;
		}
		set
		{
			isNewSchema = value;
		}
	}

	public bool ProcessParamAttributes
	{
		get
		{
			return processParamAttributes;
		}
		set
		{
			processParamAttributes = value;
		}
	}

	public bool ProcessParamArrayData
	{
		get
		{
			return processParamArrayData;
		}
		set
		{
			processParamArrayData = value;
		}
	}

	public bool IgnoreLookupTables { get; set; }

	public bool IgnoreScenarioCombinedLookupTable { get; set; }

	public ConvertQTMToDB(string XmlFileName)
	{
		strFileToBeConverted = XmlFileName;
		dataAccess = new DataAccess();
	}

	public ConvertQTMToDB()
		: this(string.Empty)
	{
	}

	public System.Data.DataSet RunStoredProcAsQuery(string query, out string warningString)
	{
		warningString = string.Empty;
		System.Data.DataSet result = null;
		try
		{
			result = dataAccess.RunQuery(query);
		}
		catch (Exception ex)
		{
			warningString = ex.Message + "\nQuery:\n" + query;
		}
		return result;
	}

	public System.Data.DataSet RunStoredProcWithWarningStringDS(string StProcName, string Arg1Name, string Arg1Value, string Arg2Name, int iRID, out string WarningString)
	{
		WarningString = string.Empty;
		List<SqlParameter> list = new List<SqlParameter>();
		List<SqlParameter> outSqlParameter = null;
		System.Data.DataSet result = new System.Data.DataSet();
		try
		{
			SqlParameter sqlParameter = new SqlParameter(Arg1Name, SqlDbType.VarChar);
			sqlParameter.Value = Arg1Value;
			list.Add(sqlParameter);
			if (iRID != -1)
			{
				SqlParameter sqlParameter2 = new SqlParameter(Arg2Name, SqlDbType.Int);
				sqlParameter2.Value = iRID;
				list.Add(sqlParameter2);
			}
			SqlParameter sqlParameter3 = new SqlParameter(Constants.WARNING, SqlDbType.VarChar, 1000);
			sqlParameter3.Value = string.Empty;
			sqlParameter3.Direction = ParameterDirection.InputOutput;
			list.Add(sqlParameter3);
			SqlParameter sqlParameter4 = new SqlParameter(Constants.SUCCESS, SqlDbType.Int);
			sqlParameter4.Value = -1;
			sqlParameter4.Direction = ParameterDirection.InputOutput;
			list.Add(sqlParameter4);
			result = dataAccess.RunStoredProcedure(StProcName, list, out outSqlParameter);
			WarningString = outSqlParameter[outSqlParameter.Count - 2].Value.ToString();
		}
		catch (Exception ex)
		{
			WarningString = ex.Message;
		}
		return result;
	}

	public ROOT LoadXmlFile(string path)
	{
		ROOT result = null;
		XmlSerializer xmlSerializer = new XmlSerializer(typeof(ROOT));
		FileStream fileStream = null;
		if (File.Exists(path))
		{
			try
			{
				fileStream = new FileStream(path, FileMode.Open);
				XmlTextReader xmlReader = new XmlTextReader(fileStream);
				result = (ROOT)xmlSerializer.Deserialize(xmlReader);
			}
			finally
			{
				fileStream.Close();
			}
		}
		return result;
	}

	public bool StartConversion(string strFileToBeConverted, out string WarningString, out bool badFile)
	{
		long identity;
		return StartConversionReturnIdentity(strFileToBeConverted, out WarningString, out badFile, out identity);
	}

	public bool StartConversion(string strFileToBeConverted, out string WarningString, out bool badFile, out long identity)
	{
		return StartConversionReturnIdentity(strFileToBeConverted, out WarningString, out badFile, out identity);
	}

	private bool StartConversionReturnIdentity(string strFileToBeConverted, out string WarningString, out bool badFile, out long identity)
	{
		badFile = false;
		bool flag = false;
		string Warning = string.Empty;
		WarningString = string.Empty;
		identity = -1L;
		try
		{
			if (!File.Exists(strFileToBeConverted))
			{
				WarningString = WarningString + "The File Does not Exist \"" + strFileToBeConverted + "\"";
				return false;
			}
			if (HasText(strFileToBeConverted, Constants.V3_XML_FILE_IDENTIFICATION_MARKER))
			{
				isV3File = true;
				Run run = null;
				run = new Run(strFileToBeConverted);
				if (!IgnoreFileDBSetting)
				{
					string text = DatabaseName;
					string text2 = ServerName;
					try
					{
						text = run.RunInfo.RunConfig.Find((DataItem C) => C.Name.Equals(Constants.DATABASE)).Value;
						text2 = run.RunInfo.RunConfig.Find((DataItem C) => C.Name.Equals(Constants.SERVER)).Value;
					}
					catch
					{
					}
					if (text != DatabaseName || text2 != ServerName)
					{
						DatabaseName = text;
						ServerName = text2;
					}
				}
				MapV3Schema(strFileToBeConverted, run);
			}
			else
			{
				isV3File = false;
				xmlMainDoc.Load(strFileToBeConverted);
				XmlNode documentElement = xmlMainDoc.DocumentElement;
				XmlNode xmlNode = documentElement.SelectSingleNode(Constants.TREE_XML_FILE_IDENTIFIER);
				if (xmlNode != null)
				{
					flag = true;
				}
				if (!isDatabaseEvaluated && !IgnoreFileDBSetting)
				{
					string text = DatabaseName;
					string text2 = ServerName;
					if (flag)
					{
						try
						{
							XmlNode documentElement2 = xmlMainDoc.DocumentElement;
							XmlNode xmlNode2 = documentElement2.SelectSingleNode("/SerializeComponents/theRootTest/RootProperties");
							text = xmlNode2.SelectSingleNode(Constants.DATABASE).InnerText;
							text2 = xmlNode2.SelectSingleNode(Constants.SERVER).InnerText;
						}
						catch
						{
						}
					}
					else
					{
						try
						{
							xmlFile = LoadXmlFile(strFileToBeConverted);
							text = xmlFile.ConfigInfo.Database;
							text2 = xmlFile.ConfigInfo.Server;
						}
						catch
						{
						}
					}
					if (text != DatabaseName || text2 != ServerName)
					{
						DatabaseName = text;
						ServerName = text2;
					}
				}
			}
			EvaluateDatabaseProperties();
			if (flag)
			{
				return ConvertTree(out WarningString);
			}
			if (IsNewSchema)
			{
				InitializeLookupTables(out Warning);
				if (!string.IsNullOrEmpty(Warning))
				{
					badFile = true;
					throw new Exception("Error initializing lookup tables:" + Environment.NewLine + Warning);
				}
				bool result = ConvertDynamicDataNewSchema(strFileToBeConverted, ref WarningString, out badFile, out identity);
				GC.Collect();
				GC.WaitForPendingFinalizers();
				return result;
			}
			return ConvertDynamicDataOldSchema(ref WarningString, out badFile, out identity);
		}
		catch (SqlException ex)
		{
			badFile = true;
			WarningString = ex.Message;
			if (ex.Number == 53 || ex.Number == 4060)
			{
				throw ex;
			}
			return false;
		}
		catch (Exception ex2)
		{
			badFile = true;
			WarningString = ex2.Message;
			if (ex2 is SqlException && ((SqlException)ex2).Number == 53)
			{
				throw ex2;
			}
			return false;
		}
	}

	private void EvaluateDatabaseProperties()
	{
		databasePropertiesDs = new System.Data.DataSet();
		if (isDatabaseEvaluated)
		{
			return;
		}
		try
		{
			databasePropertiesDs = dataAccess.RunQuery("Execute " + Constants.STPROC_DATABASEPROPERTIES);
		}
		catch (Exception ex)
		{
			if ((ex is SqlException && ((SqlException)ex).Number == 53) || ((SqlException)ex).Number == 4060)
			{
				throw ex;
			}
			IsNewSchema = false;
		}
		if (databasePropertiesDs != null && databasePropertiesDs.Tables.Count > 0)
		{
			foreach (DataRow row in databasePropertiesDs.Tables[0].Rows)
			{
				if (string.Compare(row["Name"].ToString(), Constants.ISNEWSCHEMAPROPERTYNAME, ignoreCase: true) == 0 && string.Compare(row["Value"].ToString(), Constants.ISNEWSCHEMAPROPERTYVALUE, ignoreCase: true) == 0)
				{
					IsNewSchema = true;
				}
				if (string.Compare(row["Name"].ToString(), Constants.PROCESSPARAMATTRIBUTESPROPERTYNAME, ignoreCase: true) == 0 && string.Compare(row["Value"].ToString(), Constants.PROCESSPARAMATTRIBUTESPROPERTYVALUE, ignoreCase: true) == 0)
				{
					ProcessParamAttributes = true;
				}
				if (string.Compare(row["Name"].ToString(), Constants.PROCESSPARAMARRAYPROPERTYNAME, ignoreCase: true) == 0 && string.Compare(row["Value"].ToString(), Constants.PROCESSPARAMARRAYPROPERTYVALUE, ignoreCase: true) == 0)
				{
					ProcessParamArrayData = true;
				}
			}
		}
		isDatabaseEvaluated = true;
	}

	public long RunStoredProcWithWarningString(string StProcName, string Arg1Name, string Arg1Value, string Arg2Name, int iRID, out string WarningString)
	{
		long result = -1L;
		WarningString = "";
		List<SqlParameter> list = new List<SqlParameter>();
		List<SqlParameter> outSqlParameter = null;
		try
		{
			SqlParameter sqlParameter = new SqlParameter(Arg1Name, SqlDbType.VarChar);
			sqlParameter.Value = Arg1Value;
			list.Add(sqlParameter);
			if (iRID != -1)
			{
				SqlParameter sqlParameter2 = new SqlParameter(Arg2Name, SqlDbType.Int);
				sqlParameter2.Value = iRID;
				list.Add(sqlParameter2);
			}
			SqlParameter sqlParameter3 = new SqlParameter("Warning", SqlDbType.VarChar, 1000);
			sqlParameter3.Value = string.Empty;
			sqlParameter3.Direction = ParameterDirection.InputOutput;
			list.Add(sqlParameter3);
			SqlParameter sqlParameter4 = new SqlParameter("Success", SqlDbType.Int);
			sqlParameter4.Value = -1;
			sqlParameter4.Direction = ParameterDirection.InputOutput;
			list.Add(sqlParameter4);
			System.Data.DataSet dataSet = dataAccess.RunStoredProcedure(StProcName, list, out outSqlParameter);
			WarningString = outSqlParameter[outSqlParameter.Count - 2].Value.ToString();
			result = ((int.Parse(outSqlParameter[outSqlParameter.Count - 1].Value.ToString()) != 0) ? long.Parse(dataSet.Tables[0].Rows[0]["Identity"].ToString()) : (-1));
		}
		catch (Exception ex)
		{
			WarningString += ex.Message;
		}
		return result;
	}

	private bool ConvertDynamicDataOldSchemaReturnIdentity(ref string WarningString, out bool badFile, out long identity)
	{
		badFile = false;
		identity = -1L;
		try
		{
			XmlNode documentElement = xmlMainDoc.DocumentElement;
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Start();
			XmlNode xmlNode = documentElement.SelectSingleNode("/ROOT/Config");
			string arg1Value = string.Empty;
			string innerText = xmlNode.SelectSingleNode("StartTime").InnerText;
			string value = "<StartTime>" + innerText + "</StartTime>";
			if (xmlNode != null)
			{
				arg1Value = xmlNode.OuterXml;
			}
			string text = "Config prep Time:" + stopwatch.Elapsed.Seconds + "s ";
			if (!IgnoreFileDBSetting)
			{
				try
				{
					string innerText2 = xmlNode.SelectSingleNode("Database").InnerText;
					string innerText3 = xmlNode.SelectSingleNode("Server").InnerText;
					if (innerText2 != DatabaseName || innerText3 != ServerName)
					{
						DatabaseName = innerText2;
						ServerName = innerText3;
					}
				}
				catch
				{
				}
			}
			long num = RunStoredProcWithWarningString("[" + Constants.OLDSTPROC_INSERTSESSIONDATA + "]", "@XmlInput", arg1Value, "", -1, out WarningString);
			if (!string.IsNullOrEmpty(WarningString) && (WarningString.Contains("Extend data set, but the base data not found yet") || WarningString.Contains("timeout")))
			{
				badFile = false;
				return false;
			}
			if (num < 0)
			{
				badFile = true;
				return false;
			}
			XmlNodeList xmlNodeList = documentElement.SelectNodes("/ROOT/Config/Information/Info");
			StringBuilder stringBuilder = new StringBuilder("<Root>");
			foreach (XmlNode item in xmlNodeList)
			{
				string outerXml = item.OuterXml;
				int startIndex = outerXml.IndexOf("<Key>");
				outerXml = outerXml.Insert(startIndex, value);
				stringBuilder.Append(outerXml);
			}
			stringBuilder.Append("</Root>");
			stringBuilder = stringBuilder.Replace("'", "''");
			string query = "Execute  " + Constants.OLDSTPROC_INSERTRUNTITLEDATA + "  '" + stringBuilder.ToString() + "', " + num;
			System.Data.DataSet dataSet = RunStoredProcAsQuery(query, out WarningString);
			if (dataSet == null)
			{
				badFile = true;
				return false;
			}
			XmlNodeList xmlNodeList2 = documentElement.SelectNodes("/ROOT/TEST");
			StringBuilder stringBuilder2 = new StringBuilder("<Root>");
			foreach (XmlNode item2 in xmlNodeList2)
			{
				string outerXml2 = item2.OuterXml;
				int startIndex = outerXml2.IndexOf("<TNAME>");
				outerXml2 = outerXml2.Insert(startIndex, value);
				stringBuilder2.Append(outerXml2);
			}
			stringBuilder2.Append("</Root>");
			stringBuilder2 = stringBuilder2.Replace("'", "''");
			query = "Execute  " + Constants.OLDSTPROC_INSERTNODEDATA + "  '" + stringBuilder2.ToString() + "', " + num;
			System.Data.DataSet dataSet2 = RunStoredProcAsQuery(query, out WarningString);
			if (dataSet2 == null)
			{
				badFile = true;
				return false;
			}
			int num2 = 0;
			StringBuilder stringBuilder3 = new StringBuilder("<Root>");
			StringBuilder stringBuilder4 = new StringBuilder("<Root>");
			StringBuilder stringBuilder5 = new StringBuilder("<Root>");
			DataTable dataTable = dataSet2.Tables[0];
			foreach (XmlNode item3 in xmlNodeList2)
			{
				string value2 = "<NRID>" + dataTable.Rows[num2][0].ToString() + "</NRID>";
				XmlNodeList childNodes = item3.ChildNodes;
				for (int i = 0; i < childNodes.Count; i++)
				{
					if (childNodes[i].Name == "ParamResults")
					{
						string outerXml3 = childNodes[i].OuterXml;
						int startIndex = outerXml3.IndexOf("<N>");
						outerXml3 = outerXml3.Insert(startIndex, value2);
						outerXml3 = outerXml3.Insert(startIndex, value);
						stringBuilder3.Append(outerXml3);
					}
					if (childNodes[i].Name == "LOOPVALUES")
					{
						string outerXml4 = childNodes[i].OuterXml;
						int startIndex = outerXml4.IndexOf("<V>");
						outerXml4 = outerXml4.Insert(startIndex, value2);
						outerXml4 = outerXml4.Insert(startIndex, value);
						stringBuilder4.Append(outerXml4);
					}
					if (!(childNodes[i].Name == "Inputs"))
					{
						continue;
					}
					XmlNodeList xmlNodeList3 = item3.SelectNodes("Inputs/Input");
					foreach (XmlNode item4 in xmlNodeList3)
					{
						string outerXml5 = item4.OuterXml;
						int startIndex = outerXml5.IndexOf("<Key>");
						outerXml5 = outerXml5.Insert(startIndex, value2);
						outerXml5 = outerXml5.Insert(startIndex, value);
						stringBuilder5.Append(outerXml5);
					}
				}
				num2++;
			}
			stringBuilder3.Append("</Root>");
			stringBuilder4.Append("</Root>");
			stringBuilder5.Append("</Root>");
			stringBuilder3 = stringBuilder3.Replace("'", "''");
			query = "Execute  " + Constants.OLDSTPROC_INSERTPARAMDATA + "  '" + stringBuilder3.ToString() + " '";
			System.Data.DataSet dataSet3 = RunStoredProcAsQuery(query, out WarningString);
			if (dataSet3 == null)
			{
				badFile = true;
				WarningString = "Param data error " + WarningString;
				return false;
			}
			stringBuilder4 = stringBuilder4.Replace("'", "''");
			query = "Execute  " + Constants.OLDSTPROC_INSERTSCENARIOCONDITIONSDATA + "  '" + stringBuilder4.ToString() + " '";
			System.Data.DataSet dataSet4 = RunStoredProcAsQuery(query, out WarningString);
			if (dataSet4 == null)
			{
				badFile = true;
				WarningString = "Scrnerio conditions data error " + WarningString;
				return false;
			}
			stringBuilder5 = stringBuilder5.Replace("'", "''");
			query = "Execute  " + Constants.OLDSTPROC_INSERTSCENARIOCONDITIONSDATA + "  '" + stringBuilder5.ToString() + " '";
			System.Data.DataSet dataSet5 = RunStoredProcAsQuery(query, out WarningString);
			if (dataSet5 == null)
			{
				badFile = true;
				WarningString = "Scrnerio Split conditions data error " + WarningString;
				return false;
			}
			dataTable = dataSet3.Tables[0];
			string text2 = "";
			StringBuilder stringBuilder6 = new StringBuilder("<Root>");
			num2 = 0;
			foreach (XmlNode item5 in xmlNodeList2)
			{
				XmlNodeList childNodes2 = item5.ChildNodes;
				for (int i = 0; i < childNodes2.Count; i++)
				{
					if (!(childNodes2[i].Name == "ParamResults"))
					{
						continue;
					}
					text2 = "<PID>" + dataTable.Rows[num2][0].ToString() + "</PID>";
					XmlNodeList childNodes3 = childNodes2[i].ChildNodes;
					for (int j = 0; j < childNodes3.Count; j++)
					{
						if (childNodes3[j].Name == Constants.PARAMARRAYRESULTS_TAG)
						{
							string outerXml6 = childNodes3[j].OuterXml;
							int startIndex = outerXml6.IndexOf("<N>");
							outerXml6 = outerXml6.Insert(startIndex, text2);
							outerXml6 = outerXml6.Insert(startIndex, value);
							stringBuilder6.Append(outerXml6);
						}
					}
					num2++;
				}
			}
			stringBuilder6.Append("</Root>");
			stringBuilder6 = stringBuilder6.Replace("'", "''");
			query = "Execute  " + Constants.OLDSTPROC_INSERTPARAMARRAYDATA + "  '" + stringBuilder6.ToString() + " '";
			System.Data.DataSet dataSet6 = RunStoredProcAsQuery(query, out WarningString);
			if (dataSet6 == null)
			{
				badFile = true;
				WarningString = "Array data error " + WarningString;
				return false;
			}
			if (!string.IsNullOrEmpty(WarningString) && !WarningString.Contains("timeout"))
			{
				badFile = true;
				return false;
			}
			badFile = false;
			return true;
		}
		catch (Exception ex)
		{
			WarningString = WarningString + "\n" + ex.Message;
			badFile = true;
			return false;
		}
	}

	private bool ConvertDynamicDataOldSchema(ref string WarningString, out bool badFile)
	{
		long identity;
		return ConvertDynamicDataOldSchemaReturnIdentity(ref WarningString, out badFile, out identity);
	}

	private bool ConvertDynamicDataOldSchema(ref string WarningString, out bool badFile, out long identity)
	{
		return ConvertDynamicDataOldSchemaReturnIdentity(ref WarningString, out badFile, out identity);
	}

	public static void ClearLookupTables()
	{
		ParamDetailsRID.ClearLookupValues();
		RunTitleOptonsRID.ClearLookupValues();
		RunTitleOptonsRID.ClearNewValues();
		NodeDetailsRID.ClearLookupValues();
		NodeDetailsRID.ClearNewValues();
		ParamRID.ClearLookupValues();
		ParamArrayRID.ClearLookupValues();
		GC.Collect();
		GC.WaitForPendingFinalizers();
	}

	private void InitializeLookupTables(out string Warning)
	{
		Warning = string.Empty;
		string Warning2 = string.Empty;
		runTitleOptionsRID = new RunTitleOptonsRID();
		resultOptionsRID = new ResultOptionsRID();
		subErrorCodeCombinedOptionsRID = new SubErrorCodeCombinedOptionsRID();
		subErrorCodeDetailsRID = new SubErrorCodeDetailsRID();
		errorCodeOptionsRID = new ErrorCodeOptonsRID();
		subErrorCodeOptionsRID = new SubErrorCodeOptionsRID();
		paramResultOptionsRID = new ParamResultOptionsRID();
		scenarioSplitOptionsRID = new ScenarioSplitOptionsRID();
		scenarioCombinedOptionsRID = new ScenarioCombinedOptionsRID();
		if (!runTitleOptionsRID.LookupHasValues())
		{
			string sTPROC_GETRUNTITLEOPTIONS = Constants.STPROC_GETRUNTITLEOPTIONS;
			runTitleOptionsRID.PopulateValues(GetLookupValues(sTPROC_GETRUNTITLEOPTIONS, out Warning2));
			Warning += Warning2;
		}
		if (!resultOptionsRID.LookupHasValues())
		{
			string sTPROC_GETRESULTOPTIONSRID = Constants.STPROC_GETRESULTOPTIONSRID;
			resultOptionsRID.PopulateValues(GetLookupValues(sTPROC_GETRESULTOPTIONSRID, out Warning2));
			Warning += Warning2;
		}
		if (!subErrorCodeCombinedOptionsRID.LookupHasValues())
		{
			subErrorCodeCombinedOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETSUBERRORCODECOMBINEDOPTIONS, out Warning2));
			Warning += Warning2;
		}
		if (!subErrorCodeDetailsRID.LookupHasValues())
		{
			subErrorCodeDetailsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETSUBERRORCODEDETAILS, out Warning2));
			Warning += Warning2;
		}
		if (!subErrorCodeOptionsRID.LookupHasValues())
		{
			subErrorCodeOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETSUBERRORCODEOPTIONS, out Warning2));
			Warning += Warning2;
		}
		if (!paramResultOptionsRID.LookupHasValues())
		{
			string sTPROC_GETPARAMRESULTOPTIONS = Constants.STPROC_GETPARAMRESULTOPTIONS;
			paramResultOptionsRID.PopulateValues(GetLookupValues(sTPROC_GETPARAMRESULTOPTIONS, out Warning2));
			Warning += Warning2;
		}
		if (!scenarioSplitOptionsRID.LookupHasValues())
		{
			string sTPROC_GETSCENARIOSPLITOPTIONS = Constants.STPROC_GETSCENARIOSPLITOPTIONS;
			scenarioSplitOptionsRID.PopulateValues(GetLookupValues(sTPROC_GETSCENARIOSPLITOPTIONS, out Warning2));
			Warning += Warning2;
		}
		if (!scenarioCombinedOptionsRID.LookupHasValues() && !IgnoreScenarioCombinedLookupTable)
		{
			string sTPROC_GETSCENARIOCOMBINEDOPTIONS = Constants.STPROC_GETSCENARIOCOMBINEDOPTIONS;
			scenarioCombinedOptionsRID.PopulateValues(GetLookupValues(sTPROC_GETSCENARIOCOMBINEDOPTIONS, out Warning2));
			Warning += Warning2;
		}
		if (ProcessParamAttributes)
		{
			paramAttributesRID = new ParamAttributesRID();
			paramAttributesRID.PopulateValues(GetLookupValues(Constants.STPROC_GETPARAMATTRIBUTES, out Warning2));
			Warning += Warning2;
		}
	}

	private int Sum(int[] maxCount)
	{
		int num = 0;
		foreach (int num2 in maxCount)
		{
			num += num2;
		}
		return num;
	}

	private int Max(params int[] newValueCounts)
	{
		int num = 0;
		foreach (int num2 in newValueCounts)
		{
			if (num2 > num)
			{
				num = num2;
			}
		}
		return num;
	}

	private bool ConvertTree(out string WarningString)
	{
		WarningString = "";
		try
		{
			if (!IgnoreFileDBSetting)
			{
				try
				{
					XmlNode documentElement = xmlMainDoc.DocumentElement;
					XmlNode xmlNode = documentElement.SelectSingleNode("/SerializeComponents/theRootTest/RootProperties");
					string innerText = xmlNode.SelectSingleNode(Constants.DATABASE).InnerText;
					string innerText2 = xmlNode.SelectSingleNode(Constants.SERVER).InnerText;
					if (innerText != DatabaseName || innerText2 != ServerName)
					{
						DatabaseName = innerText;
						ServerName = innerText2;
					}
				}
				catch
				{
				}
			}
			sqlConnection.ConnectionString = dataAccess.ConnectionString;
			return qtmTreeXMLRegistration.RegisterTree(sqlConnection, xmlMainDoc.OuterXml, "", "", out WarningString);
		}
		catch (Exception ex)
		{
			WarningString = ex.ToString();
			return false;
		}
	}

	public System.Data.DataSet InsertNewLookupValues(string newValue, string storedProcedure, out string WarningString)
	{
		string query = "Execute " + storedProcedure + " '" + newValue.Replace("'", "''") + "'";
		WarningString = string.Empty;
		return RunStoredProcAsQuery(query, out WarningString);
	}

	public System.Data.DataSet GetLookupValues(string storedProcedureString, out string Warning)
	{
		string query = "Execute  " + storedProcedureString;
		string warningString = string.Empty;
		System.Data.DataSet result = RunStoredProcAsQuery(query, out warningString);
		Warning = warningString;
		return result;
	}

	private void MapV3Schema(string strFileToBeConverted, Run run)
	{
		xmlFile.ConfigInfo = new Config();
		UUT uUT = null;
		uUT = ((run.RunInfo.UUTItems.Count <= 0) ? new UUT() : run.RunInfo.UUTItems.Last());
		xmlFile.ConfigInfo.ExtendedData = run.ExtendedData;
		xmlFile.ConfigInfo.Database = DatabaseName;
		xmlFile.ConfigInfo.ERROR_CODE = run.RunInfo.Status.ErrorCode.Error;
		xmlFile.ConfigInfo.MachineName = run.RunInfo.MachineName;
		xmlFile.ConfigInfo.MCN = uUT.HardwareConfiguration.Id;
		xmlFile.ConfigInfo.Result = run.RunInfo.Status.Value;
		xmlFile.ConfigInfo.Server = ServerName;
		xmlFile.ConfigInfo.SessionDataGUID = run.RunInfo.SessionDataGUID;
		xmlFile.ConfigInfo.Comments = run.RunInfo.Comments;
		xmlFile.ConfigInfo.StartTime = run.RunInfo.DateTime.StartTime;
		xmlFile.ConfigInfo.StopTime = (string.IsNullOrEmpty(run.RunInfo.DateTime.StopTime) ? DateTime.Now.ToString() : run.RunInfo.DateTime.StopTime);
		xmlFile.ConfigInfo.SW_MCN = uUT.SoftwareConfiguration.SoftwareBuildID;
		xmlFile.ConfigInfo.SW_VER = uUT.SoftwareConfiguration.Version;
		xmlFile.ConfigInfo.TESTERID = run.RunInfo.Tester.TesterID;
		xmlFile.ConfigInfo.TPByVerRID = run.RunInfo.TestPlan.Id;
		xmlFile.ConfigInfo.TreeType = run.RunInfo.Tester.Type;
		xmlFile.ConfigInfo.UUT_SN = uUT.Id;
		xmlFile.ConfigInfo.WORKSTATION = run.RunInfo.Tester.WorkStation;
		xmlFile.ConfigInfo.TreeID = run.RunInfo.Tester.TreeID;
		xmlFile.ConfigInfo.IsRunning = (bool.Parse(run.IsRunning) ? "true" : "false");
		xmlFile.ConfigInfo.SessionName = strFileToBeConverted;
		GenerateRunTitle(run);
		UnWindDataSetRefrences(ref run);
		MapTestsInfo(run);
		xmlFile.ConfigInfo.RunInfo = run.RunInfo;
	}

	private void MapTestsInfo(Run run)
	{
		List<ROOTTEST> list = new List<ROOTTEST>();
		foreach (QC.QSPRLogSchema.Test item in run.TestCollection)
		{
			ROOTTEST rOOTTEST = new ROOTTEST();
			rOOTTEST.TNAME = item.Name;
			rOOTTEST.LOOPVALUES = new ROOTTESTLOOPVALUES();
			rOOTTEST.LOOPVALUES.LV = new ROOTTESTLOOPVALUESLV();
			rOOTTEST.LOOPVALUES.LV.V = GetLoopValues(rOOTTEST, item);
			rOOTTEST.RES = item.Status.StatusValue;
			rOOTTEST.ERROR_CODE = item.Status.ErrorCode.Error;
			rOOTTEST.TestStartTime = item.StartTime;
			rOOTTEST.TestStopTime = item.StopTime;
			rOOTTEST.TestDuration = item.Duration;
			rOOTTEST.TestCaseRID = item.TestCase.TCCaseID;
			rOOTTEST.Comments = item.Status.Comments;
			rOOTTEST.LogFilePath = item.Status.LogFilePath;
			rOOTTEST.TestCaseRefRID = item.TCCaseRefId;
			rOOTTEST.CRID = item.CRNumber;
			rOOTTEST.ErrorDescription = item.Status.ErrorCode.Description;
			rOOTTEST.RealName = item.NodeName;
			rOOTTEST.TestPath = item.FullPath;
			rOOTTEST.ParamResults = GetParamResults(item.DataSet.Output);
			rOOTTEST.TestConfig = item.TestConfig;
			rOOTTEST.GroupId = item.GroupId;
			rOOTTEST.SkipReason = item.Status.SkipReason;
			rOOTTEST.TestSpecification = item.TestCase.TestSpecification;
			rOOTTEST.NI = "-1";
			list.Add(rOOTTEST);
		}
		xmlFile.TEST = list.ToArray();
	}

	private ROOTTESTParamResults[] GetParamResults(Output output)
	{
		List<ROOTTESTParamResults> list = new List<ROOTTESTParamResults>();
		float result;
		foreach (OutputItem output2 in output.Outputs)
		{
			ROOTTESTParamResults rOOTTESTParamResults = new ROOTTESTParamResults();
			rOOTTESTParamResults.N = output2.Name;
			if (float.TryParse(output2.Value, out result))
			{
				rOOTTESTParamResults.V = output2.Value;
			}
			else
			{
				rOOTTESTParamResults.CHAR_V = output2.Value;
			}
			rOOTTESTParamResults.UL = output2.Maximum;
			rOOTTESTParamResults.LL = output2.Minimum;
			rOOTTESTParamResults.UOM = output2.Unit;
			list.Add(rOOTTESTParamResults);
		}
		foreach (ArrayOutputItem arrayOutput in output.ArrayOutputs)
		{
			ROOTTESTParamResults rOOTTESTParamResults = new ROOTTESTParamResults();
			rOOTTESTParamResults.N = arrayOutput.Name;
			rOOTTESTParamResults.UOM = arrayOutput.Unit;
			List<ROOTTESTParamArrayResults> list2 = new List<ROOTTESTParamArrayResults>();
			string[] array = arrayOutput.Value.Split(',');
			int i;
			for (i = 0; i < array.Length; i++)
			{
				ROOTTESTParamArrayResults rOOTTESTParamArrayResults = new ROOTTESTParamArrayResults();
				if (float.TryParse(arrayOutput.Value, out result))
				{
					rOOTTESTParamArrayResults.V = array[i];
				}
				else
				{
					rOOTTESTParamArrayResults.CHAR_V = array[i];
				}
				rOOTTESTParamArrayResults.N = arrayOutput.Name;
				ArrayOutputLimitItem arrayOutputLimitItem = arrayOutput.Limits.Find((ArrayOutputLimitItem L) => i >= int.Parse(L.StartIndex) && i <= int.Parse(L.StopIndex));
				rOOTTESTParamArrayResults.UL = arrayOutputLimitItem.Maximum;
				rOOTTESTParamArrayResults.LL = arrayOutputLimitItem.Minimum;
				rOOTTESTParamArrayResults.I = i.ToString();
				list2.Add(rOOTTESTParamArrayResults);
			}
			rOOTTESTParamResults.ParamArrayResults = list2.ToArray();
			list.Add(rOOTTESTParamResults);
		}
		return list.ToArray();
	}

	private string GetLoopValues(ROOTTEST rootTest, QC.QSPRLogSchema.Test test)
	{
		string text = string.Empty;
		List<ROOTTESTInput> list = new List<ROOTTESTInput>();
		foreach (InputItem input in test.DataSet.Input.Inputs)
		{
			string text2 = text;
			text = text2 + input.Name + "__" + input.Value + "_ _";
			ROOTTESTInput rOOTTESTInput = new ROOTTESTInput();
			rOOTTESTInput.Key = input.Name;
			rOOTTESTInput.Value = input.Value;
			list.Add(rOOTTESTInput);
		}
		foreach (ArrayInputItem arrayInput in test.DataSet.Input.ArrayInputs)
		{
			string text2 = text;
			text = text2 + arrayInput.Name + "__" + arrayInput.Value + "_ _";
			ROOTTESTInput rOOTTESTInput = new ROOTTESTInput();
			rOOTTESTInput.Key = arrayInput.Name;
			rOOTTESTInput.Value = arrayInput.Value;
			list.Add(rOOTTESTInput);
		}
		rootTest.Inputs = list.ToArray();
		return text;
	}

	private void GenerateRunTitle(Run run)
	{
		string text = string.Empty;
		List<ROOTConfigInfo> list = new List<ROOTConfigInfo>();
		foreach (TestLibrary softwareConfigurationInfoItem in run.RunInfo.Tester.SoftwareConfigurationInfoItems)
		{
			string text2 = text;
			text = text2 + softwareConfigurationInfoItem.Name + "__" + softwareConfigurationInfoItem.Version + "_ _";
			ROOTConfigInfo rOOTConfigInfo = new ROOTConfigInfo();
			rOOTConfigInfo.Key = softwareConfigurationInfoItem.Name;
			rOOTConfigInfo.Value = softwareConfigurationInfoItem.Version;
			list.Add(rOOTConfigInfo);
		}
		foreach (DataItem item in run.RunInfo.RunConfig)
		{
			string text2 = text;
			text = text2 + item.Name + "__" + item.Value + "_ _";
			ROOTConfigInfo rOOTConfigInfo = new ROOTConfigInfo();
			rOOTConfigInfo.Key = item.Name;
			rOOTConfigInfo.Value = item.Value;
			list.Add(rOOTConfigInfo);
		}
		text = (string.IsNullOrEmpty(text) ? ("ParamResult__ParamResult_ _QSPR Version__" + run.RunInfo.Tester.Version) : ("ParamResult__ParamResult_ _" + text + "QSPR Version__" + run.RunInfo.Tester.Version));
		xmlFile.ConfigInfo.Information = list.ToArray();
		xmlFile.ConfigInfo.RunTitle = text;
	}

	private void UnWindDataSetRefrences(ref Run run)
	{
		Dictionary<string, QC.QSPRLogSchema.DataSet> dictionary = new Dictionary<string, QC.QSPRLogSchema.DataSet>();
		foreach (QC.QSPRLogSchema.Test item in run.TestCollection)
		{
			if (item.DataSet != null && item.DataSet.DataSetReferences != null)
			{
				if (item.DataSet.DataSetReferences.Count > 0)
				{
					item.DataSet = dictionary[item.DataSet.DataSetReferences[0].Id].DeepClone();
				}
				else if (!string.IsNullOrEmpty(item.DataSet.Id) && !dictionary.ContainsKey(item.DataSet.Id))
				{
					dictionary.Add(item.DataSet.Id, item.DataSet);
				}
			}
		}
	}

	public static bool HasText(string filePath, string text, int bufferSizeToSearch = 1024)
	{
		using StreamReader streamReader = new StreamReader(filePath);
		try
		{
			char[] array = new char[bufferSizeToSearch];
			streamReader.ReadBlock(array, 0, bufferSizeToSearch);
			string text2 = new string(array);
			if (text2.ToLower().Contains(text.ToLower()))
			{
				return true;
			}
			return false;
		}
		catch
		{
			return false;
		}
	}

	public void UpdateProcessedFileLocation(long sessionDataRID, string processesFileLocation, out string WarningString)
	{
		WarningString = string.Empty;
		try
		{
			string empty = string.Empty;
			empty = "Execute  " + Constants.STPROC_UPDATEPROCESSEDFILELOCATION + "  '" + sessionDataRID + "', '" + processesFileLocation.Replace("'", "''") + "'";
			RunStoredProcAsQuery(empty, out WarningString);
		}
		catch (Exception ex)
		{
			WarningString = WarningString + "\n Error Updating Processed File Location Info in Session Data Table : " + ex.ToString();
		}
	}

	private StringBuilder SerializeObject(object t)
	{
		try
		{
			return Serialize(t, doCharacterChecking: true);
		}
		catch
		{
			return SerializeObjectWithIllegalCharactersRemoved(t);
		}
	}

	private static StringBuilder Serialize(object t, bool doCharacterChecking)
	{
		StringBuilder stringBuilder = new StringBuilder();
		XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
		XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
		xmlSerializerNamespaces.Add("", "");
		xmlWriterSettings.CheckCharacters = doCharacterChecking;
		xmlWriterSettings.OmitXmlDeclaration = true;
		StringWriter stringWriter = new StringWriter(stringBuilder);
		XmlSerializer xmlSerializer = new XmlSerializer(t.GetType());
		using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
		{
			xmlSerializer.Serialize(xmlWriter, t, xmlSerializerNamespaces);
		}
		stringWriter.Close();
		return stringBuilder;
	}

	private StringBuilder SerializeObjectWithIllegalCharactersRemoved(object t)
	{
		StringBuilder sb = Serialize(t, doCharacterChecking: false);
		return RemoveIllegalCharacters(sb);
	}

	private StringBuilder RemoveIllegalCharacters(StringBuilder sb)
	{
		return new StringBuilder(Regex.Replace(sb.ToString(), "&#x\\d+[A-F]?|[BCE];", "", RegexOptions.IgnoreCase));
	}

	private bool ConvertDynamicDataNewSchemaReturnIdentity(string xmlFilePath, ref string WarningString, out bool badFile, out long identity)
	{
		badFile = false;
		identity = -1L;
		string WarningString2 = string.Empty;
		long num = -1L;
		ConversionType conversionType = ConversionType.All;
		try
		{
			if (!isV3File)
			{
				xmlFile = LoadXmlFile(xmlFilePath);
			}
			if (GlobalConfiguration.NeedPreProcess())
			{
				conversionType = BaseProcess.ApplyPreProcessType(ref xmlFile, GlobalConfiguration.GetPreProcessList());
			}
			AddParamResultRuntitle(ref xmlFile, conversionType);
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Start();
			if (conversionType >= ConversionType.Session)
			{
				if (xmlFile.ConfigInfo != null)
				{
					stopwatch.Start();
					if (!isV3File && !IgnoreFileDBSetting)
					{
						try
						{
							string database = xmlFile.ConfigInfo.Database;
							string server = xmlFile.ConfigInfo.Server;
							if (database != DatabaseName || server != ServerName)
							{
								DatabaseName = database;
								ServerName = server;
							}
						}
						catch
						{
						}
					}
					System.Data.DataSet dataSet = RunStoredProcWithWarningStringDS(Constants.STPROC_SESSIONDATA, "@XmlInput", SerializeObject(xmlFile.ConfigInfo).Replace("'", "''").ToString(), string.Empty, -1, out WarningString2);
					WarningString += WarningString2;
					if (!string.IsNullOrEmpty(WarningString) && (WarningString.Contains("Extend data set, but the base data not found yet") || WarningString.Contains("timeout")))
					{
						badFile = false;
						return false;
					}
					if (dataSet == null || dataSet.Tables.Count == 0)
					{
						badFile = true;
						return false;
					}
					foreach (DataRow row in dataSet.Tables[0].Rows)
					{
						num = long.Parse(row[Constants.SESSIONDATARID].ToString());
						xmlFile.ConfigInfo.SessionDataRID = row[Constants.SESSIONDATARID].ToString();
						xmlFile.ConfigInfo.TreeID = row[Constants.TREEID].ToString();
					}
					identity = num;
					if (num < 0)
					{
						WarningString += " SessionDataRID < 0 ";
						badFile = true;
						return false;
					}
					if (!errorCodeOptionsRID.LookupHasValues())
					{
						string sTPROC_GETERRORCODECOPTIONS = Constants.STPROC_GETERRORCODECOPTIONS;
						errorCodeOptionsRID.PopulateValues(GetLookupValues(sTPROC_GETERRORCODECOPTIONS, out WarningString2));
						WarningString += WarningString2;
					}
					if (string.Compare(xmlFile.ConfigInfo.ExtendedData, "yes", ignoreCase: true) != 0 && !string.IsNullOrEmpty(xmlFile.ConfigInfo.ERROR_CODE))
					{
						InsertErrorCodeDetails(num, ref WarningString);
					}
					if (xmlFile.ConfigInfo.Information != null)
					{
						bool flag = false;
						bool flag2 = true;
						List<ROOTConfigInfo> list = new List<ROOTConfigInfo>();
						try
						{
							int num2 = 0;
							int num3 = 0;
							while (!flag && num2 <= num3)
							{
								flag = true;
								list.Clear();
								RunTitleOptonsRID.ClearNewValues();
								ROOTConfigInfo[] information = xmlFile.ConfigInfo.Information;
								foreach (ROOTConfigInfo rOOTConfigInfo in information)
								{
									if (rOOTConfigInfo.Key != Constants.MEID && rOOTConfigInfo.Key != Constants.IMEI)
									{
										string iDFromLookup = runTitleOptionsRID.GetIDFromLookup(rOOTConfigInfo.Key, rOOTConfigInfo.Value);
										if (iDFromLookup != string.Empty)
										{
											rOOTConfigInfo.RunTitleOptionsRID = iDFromLookup;
											rOOTConfigInfo.StartTime = xmlFile.ConfigInfo.StartTime;
											list.Add(rOOTConfigInfo);
										}
										else
										{
											flag2 = false;
											runTitleOptionsRID.AddToNewLookUpList(rOOTConfigInfo.Key, rOOTConfigInfo.Value);
										}
									}
								}
								flag = flag2;
								if (!flag)
								{
									if (num2 == 0)
									{
										num3 = runTitleOptionsRID.NewValueCount();
									}
									System.Data.DataSet dataSet2 = InsertNewLookupValues(runTitleOptionsRID.GetNewValues().Replace("'", "''"), Constants.STPROC_INSERTRUNTITLEOPTIONS, out WarningString2);
									WarningString += WarningString2;
									if (dataSet2 != null && dataSet2.Tables[0].Rows.Count > 0)
									{
										runTitleOptionsRID.PopulateValues(dataSet2);
									}
									else
									{
										runTitleOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETRUNTITLEOPTIONS, out WarningString2));
									}
									WarningString += WarningString2;
									flag2 = true;
									num2++;
								}
							}
							if (num2 > num3)
							{
								WarningString = WarningString + "Warning: Not all runtitleoptions were inserted properly" + Environment.NewLine;
								if (runTitleOptionsRID.NewValueCount() > 0)
								{
									WarningString = WarningString + "New RunTitleOptions which failed insertion are" + Environment.NewLine;
									WarningString += runTitleOptionsRID.GetNewValues();
								}
							}
							string query = string.Concat("Execute  ", Constants.STPROC_RUNTITLEDATA, "  '", SerializeObject(list).Replace("'", "''"), "', ", num.ToString());
							System.Data.DataSet dataSet3 = RunStoredProcAsQuery(query, out WarningString2);
							WarningString += WarningString2;
							if (dataSet3 == null)
							{
								badFile = true;
								return false;
							}
						}
						catch (Exception ex)
						{
							WarningString = WarningString + "\n Error inserting RunTitle data " + ex.ToString();
						}
					}
					if (xmlFile.TEST != null && conversionType >= ConversionType.Test)
					{
						nodeRID = new NodeRID(xmlFile.ConfigInfo.TreeID);
						if (!nodeRIDTreeList.Contains(xmlFile.ConfigInfo.TreeID))
						{
							nodeRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETNODERID} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
							WarningString += WarningString2;
							nodeRIDTreeList.Add(xmlFile.ConfigInfo.TreeID);
						}
						nodeDetailsRID = new NodeDetailsRID();
						if (!nodeDetailsTreeRIDList.Contains(xmlFile.ConfigInfo.TreeID))
						{
							nodeDetailsRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETNODEDETAILS} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
							WarningString += WarningString2;
							nodeDetailsTreeRIDList.Add(xmlFile.ConfigInfo.TreeID);
						}
						scenarioSplitConditionsRID = new ScenarioSplitConditionsRID();
						if (conversionType >= ConversionType.Parametric)
						{
							paramRID = new ParamRID();
							if (!paramRIDTreeList.Contains(xmlFile.ConfigInfo.TreeID))
							{
								paramRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETPARAMRID} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
								WarningString += WarningString2;
								paramRIDTreeList.Add(xmlFile.ConfigInfo.TreeID);
							}
							paramDetailsRID = new ParamDetailsRID();
							paramArrayRID = new ParamArrayRID();
							if (!IgnoreLookupTables)
							{
								if (!paramDetailsRIDTreeList.Contains(xmlFile.ConfigInfo.TreeID))
								{
									paramDetailsRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETPARAMDETAILS} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
									WarningString += WarningString2;
									paramDetailsRIDTreeList.Add(xmlFile.ConfigInfo.TreeID);
								}
								if (ProcessParamArrayData && conversionType >= ConversionType.Array)
								{
									paramArrayRID = new ParamArrayRID();
									if (!paramArrayRIDTreeList.Contains(xmlFile.ConfigInfo.TreeID))
									{
										paramArrayRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETPARAMARRAYRID} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
										WarningString += WarningString2;
										paramArrayRIDTreeList.Add(xmlFile.ConfigInfo.TreeID);
									}
								}
							}
							InsertTestData(out var dsNodeDataIRDs, out WarningString2, out badFile);
							WarningString += WarningString2;
							if (badFile)
							{
								return false;
							}
							if (conversionType >= ConversionType.Parametric)
							{
								InsertParamData(dsNodeDataIRDs, out var dsParamDataRIDs, out WarningString2, out badFile);
								WarningString += WarningString2;
								if (badFile)
								{
									return false;
								}
								if (ProcessParamArrayData && conversionType >= ConversionType.Parametric)
								{
									InsertParamArrayData(dsParamDataRIDs, out var _, out WarningString2, out badFile);
									WarningString += WarningString2;
									if (badFile)
									{
										return false;
									}
								}
							}
						}
					}
				}
				else
				{
					WarningString += "No configuration found";
				}
			}
			xmlFile = null;
			if (!string.IsNullOrEmpty(WarningString) && !WarningString.Contains("timeout"))
			{
				badFile = true;
				return false;
			}
			badFile = false;
			return true;
		}
		catch (Exception ex)
		{
			WarningString = WarningString + "\n" + ex.ToString();
			badFile = true;
		}
		return false;
	}

	private bool ConvertDynamicDataNewSchema(string xmlFilePath, ref string WarningString, out bool badFile)
	{
		long identity;
		return ConvertDynamicDataNewSchemaReturnIdentity(xmlFilePath, ref WarningString, out badFile, out identity);
	}

	private bool ConvertDynamicDataNewSchema(string xmlFilePath, ref string WarningString, out bool badFile, out long identity)
	{
		return ConvertDynamicDataNewSchemaReturnIdentity(xmlFilePath, ref WarningString, out badFile, out identity);
	}

	private void InsertErrorCodeDetails(long sessionDataRID, ref string WarningString)
	{
		try
		{
			string mainErrorCode = "";
			string subErrorCode = "";
			if (xmlFile.ConfigInfo.Information != null)
			{
				ROOTConfigInfo[] information = xmlFile.ConfigInfo.Information;
				foreach (ROOTConfigInfo rOOTConfigInfo in information)
				{
					if (rOOTConfigInfo.Key == Constants.MAIN_ERRORCODE)
					{
						mainErrorCode = rOOTConfigInfo.Value;
					}
					else if (rOOTConfigInfo.Key == Constants.SUB_ERRORCODE)
					{
						subErrorCode = rOOTConfigInfo.Value;
					}
				}
			}
			InsertSubErrorCodeCombinedOptions(subErrorCode, out var combinedRID, ref WarningString);
			InsertErrorCodeOptions(mainErrorCode, combinedRID, out var errorCodeOptRID, ref WarningString);
			RelateErrorCodeToSessionInformation(sessionDataRID, errorCodeOptRID, ref WarningString);
			InsertSubErrorCodeDetails(errorCodeOptRID, subErrorCode, sessionDataRID, ref WarningString);
		}
		catch (Exception ex)
		{
			WarningString = WarningString + "\n Error inserting Error code data " + ex.ToString();
		}
	}

	private void RelateErrorCodeToSessionInformation(long sessionDataRID, string errorCodeOptRID, ref string WarningString)
	{
		string newValue = "<Root><NewValue><SessionDataRID>" + sessionDataRID + "</SessionDataRID><ErrorCodeOptionsRID>" + errorCodeOptRID + "</ErrorCodeOptionsRID></NewValue></Root>";
		InsertNewLookupValues(newValue, Constants.STPROC_INSERTERRORCODEOPTIONSINSESSIONDATA, out var WarningString2);
		WarningString += WarningString2;
	}

	private void InsertSubErrorCodeCombinedOptions(string subErrorCode, out string combinedRID, ref string WarningString)
	{
		combinedRID = subErrorCodeCombinedOptionsRID.GetIDFromLookup(subErrorCode);
		if (combinedRID == string.Empty)
		{
			subErrorCodeCombinedOptionsRID.AddToNewLookUpList(subErrorCode);
			string WarningString2;
			System.Data.DataSet dataSet = InsertNewLookupValues(subErrorCodeCombinedOptionsRID.GetNewValues(), Constants.STPROC_INSERTSUBERRORCODECOMBINEDOPTIONS, out WarningString2);
			WarningString += WarningString2;
			if (dataSet == null || dataSet.Tables[0].Rows.Count <= 0)
			{
				throw new Exception("Cannot insert new data to SubErrorCodeCombinedOptions   " + subErrorCode);
			}
			subErrorCodeCombinedOptionsRID.PopulateValues(dataSet);
			subErrorCodeCombinedOptionsRID.ClearNewValues();
			combinedRID = subErrorCodeCombinedOptionsRID.GetIDFromLookup(subErrorCode);
		}
	}

	private void InsertSubErrorCodeDetails(string errorCodeOptRID, string subErrorCode, long sessionDataRId, ref string WarningString)
	{
		string WarningString2 = string.Empty;
		int num = -1;
		byte[] array = new byte[2];
		if (subErrorCode == string.Empty)
		{
			array[0] = 0;
			array[1] = 0;
		}
		else
		{
			array[0] = (byte)int.Parse(subErrorCode.Substring(1), NumberStyles.HexNumber);
			array[1] = (byte)int.Parse(subErrorCode.Substring(0, 1), NumberStyles.HexNumber);
		}
		BitArray bitArray = new BitArray(array);
		bool flag = false;
		if (subErrorCode == string.Empty)
		{
			string iDFromLookup = subErrorCodeOptionsRID.GetIDFromLookup(num.ToString());
			string iDFromLookup2 = subErrorCodeDetailsRID.GetIDFromLookup(errorCodeOptRID, iDFromLookup);
			if (iDFromLookup2 == string.Empty)
			{
				subErrorCodeDetailsRID.AddToNewLookUpList(errorCodeOptRID, iDFromLookup);
				flag = true;
			}
		}
		else
		{
			for (int num2 = bitArray.Length - 4 - 1; num2 >= 0; num2--)
			{
				if (bitArray[num2])
				{
					string iDFromLookup = subErrorCodeOptionsRID.GetIDFromLookup(num2.ToString());
					string iDFromLookup2 = subErrorCodeDetailsRID.GetIDFromLookup(errorCodeOptRID, iDFromLookup);
					if (iDFromLookup2 == string.Empty)
					{
						subErrorCodeDetailsRID.AddToNewLookUpList(errorCodeOptRID, iDFromLookup);
						flag = true;
					}
				}
			}
		}
		if (flag)
		{
			System.Data.DataSet dataSet = InsertNewLookupValues(subErrorCodeDetailsRID.GetNewValues(), Constants.STPROC_INSERTSUBERRORCODEDETAILS, out WarningString2);
			WarningString += WarningString2;
			if (dataSet == null || dataSet.Tables[0].Rows.Count <= 0)
			{
				throw new Exception("Cannot insert new data to suberrorCodeOptions   " + subErrorCode);
			}
			subErrorCodeDetailsRID.PopulateValues(dataSet);
			subErrorCodeDetailsRID.ClearNewValues();
		}
		bool flag2 = false;
		sessionSubErrorCodeData = new SessionSubErrorCodeData();
		if (subErrorCode == string.Empty)
		{
			string iDFromLookup = subErrorCodeOptionsRID.GetIDFromLookup(num.ToString());
			string iDFromLookup2 = subErrorCodeDetailsRID.GetIDFromLookup(errorCodeOptRID, iDFromLookup);
			sessionSubErrorCodeData.AddToNewLookUpList(iDFromLookup2, sessionDataRId.ToString(), xmlFile.ConfigInfo.StartTime);
		}
		else
		{
			for (int num2 = bitArray.Length - 4 - 1; num2 >= 0; num2--)
			{
				if (bitArray[num2])
				{
					string iDFromLookup = subErrorCodeOptionsRID.GetIDFromLookup(num2.ToString());
					string iDFromLookup2 = subErrorCodeDetailsRID.GetIDFromLookup(errorCodeOptRID, iDFromLookup);
					sessionSubErrorCodeData.AddToNewLookUpList(iDFromLookup2, sessionDataRId.ToString(), xmlFile.ConfigInfo.StartTime);
					flag2 = true;
				}
			}
		}
		if (flag2)
		{
			System.Data.DataSet dataSet = InsertNewLookupValues(sessionSubErrorCodeData.GetNewValues(), Constants.STPROC_INSERTSESSIONSUBERRORCODEDATA, out WarningString2);
			if (dataSet == null || dataSet.Tables[0].Rows.Count == 0)
			{
				throw new Exception("Cannot insert new data to sessionSubErrorCodeData  " + subErrorCode);
			}
		}
		WarningString += WarningString2;
		sessionSubErrorCodeData.ClearNewValues();
		sessionSubErrorCodeData = null;
	}

	private void InsertErrorCodeOptions(string mainErrorCode, string combinedRID, out string errorCodeOptRID, ref string warningString)
	{
		errorCodeOptRID = errorCodeOptionsRID.GetIDFromLookup(mainErrorCode, combinedRID);
		if (errorCodeOptRID == string.Empty)
		{
			errorCodeOptionsRID.AddToNewLookUpList(mainErrorCode, combinedRID);
			string WarningString;
			System.Data.DataSet dataSet = InsertNewLookupValues(errorCodeOptionsRID.GetNewValues(), Constants.STPROC_INSERTERRORCODEOPTIONS, out WarningString);
			warningString += WarningString;
			if (dataSet == null || dataSet.Tables[0].Rows.Count <= 0)
			{
				throw new Exception("Cannot insert new data to errorCodeOptions   " + mainErrorCode);
			}
			errorCodeOptionsRID.PopulateValues(dataSet);
			errorCodeOptionsRID.ClearNewValues();
			errorCodeOptRID = errorCodeOptionsRID.GetIDFromLookup(mainErrorCode, combinedRID);
		}
	}

	private string CalculateResultOptions(string lLimit, string uLimit, string value, string charValue)
	{
		double result = -9999.0;
		double result2 = -9999.0;
		double result3 = -9999.0;
		string result4 = Constants.UNDEFINED;
		try
		{
			if (!string.IsNullOrEmpty(lLimit))
			{
				double.TryParse(lLimit, out result);
			}
		}
		catch
		{
		}
		try
		{
			if (!string.IsNullOrEmpty(uLimit))
			{
				double.TryParse(uLimit, out result2);
			}
		}
		catch
		{
		}
		try
		{
			if (!string.IsNullOrEmpty(value))
			{
				double.TryParse(value, out result3);
			}
		}
		catch
		{
		}
		string text = "";
		try
		{
			if (!string.IsNullOrEmpty(charValue))
			{
				text = charValue;
			}
		}
		catch
		{
		}
		if (result == -9999.0 && result2 == -9999.0 && text.Length == 0)
		{
			result4 = Constants.UNDEFINED;
		}
		else if (text.Trim().Length > 0)
		{
			result4 = Constants.PASSED;
		}
		else if (result3 >= result && result3 <= result2)
		{
			result4 = Constants.PASSED;
		}
		else if (result3 <= result2 && result == -9999.0)
		{
			result4 = Constants.PASSED;
		}
		else if (result3 >= result && result2 == -9999.0)
		{
			result4 = Constants.PASSED;
		}
		else if (result3 < result && result != -9999.0)
		{
			result4 = Constants.FAILEDLOW;
		}
		else if (result3 > result2 && result2 != -9999.0)
		{
			result4 = Constants.FAILEDHIGH;
		}
		return result4;
	}

	private void InsertParamArrayData(System.Data.DataSet dsParamDataRIDs, out System.Data.DataSet dsParamArrayDataRIDs, out string WarningString, out bool badFile)
	{
		int num = 0;
		string WarningString2 = string.Empty;
		string empty = string.Empty;
		WarningString = string.Empty;
		badFile = false;
		DataTable dataTable = dsParamDataRIDs.Tables[0];
		DataRow[] array = dataTable.Select("", " paramdatarid asc");
		string empty2 = string.Empty;
		dsParamArrayDataRIDs = null;
		bool flag = false;
		bool flag2 = true;
		bool flag3 = true;
		int num2 = 0;
		int num3 = 0;
		int[] array2 = new int[2];
		ROOTTEST[] tEST;
		while (!flag && num3 <= num2)
		{
			paramArrayRID.ClearNewValues();
			paramResultOptionsRID.ClearNewValues();
			tEST = xmlFile.TEST;
			foreach (ROOTTEST rOOTTEST in tEST)
			{
				if (rOOTTEST.ParamResults == null)
				{
					continue;
				}
				ROOTTESTParamResults[] paramResults = rOOTTEST.ParamResults;
				foreach (ROOTTESTParamResults rOOTTESTParamResults in paramResults)
				{
					if (rOOTTESTParamResults.ParamArrayResults == null)
					{
						continue;
					}
					ROOTTESTParamArrayResults[] paramArrayResults = rOOTTESTParamResults.ParamArrayResults;
					foreach (ROOTTESTParamArrayResults rOOTTESTParamArrayResults in paramArrayResults)
					{
						string iDFromLookup = paramArrayRID.GetIDFromLookup(rOOTTESTParamResults.ParamRID, rOOTTESTParamArrayResults.N, rOOTTESTParamArrayResults.I, rOOTTESTParamArrayResults.CI, rOOTTESTParamArrayResults.LL, rOOTTESTParamArrayResults.UL);
						if (iDFromLookup != string.Empty)
						{
							rOOTTESTParamArrayResults.ParamArrayRID = iDFromLookup;
						}
						else
						{
							flag2 = false;
							paramArrayRID.AddToNewLookUpList(rOOTTESTParamResults.ParamRID, rOOTTESTParamArrayResults.N, rOOTTESTParamArrayResults.I, rOOTTESTParamArrayResults.CI, rOOTTESTParamArrayResults.LL, rOOTTESTParamArrayResults.UL);
						}
						string text = CalculateResultOptions(rOOTTESTParamArrayResults.LL, rOOTTESTParamArrayResults.UL, rOOTTESTParamArrayResults.V, string.Empty);
						string iDFromLookup2 = paramResultOptionsRID.GetIDFromLookup(text);
						if (iDFromLookup2 != string.Empty)
						{
							rOOTTESTParamArrayResults.ParamResultOptionRID = iDFromLookup2;
							continue;
						}
						flag3 = false;
						paramResultOptionsRID.AddToNewLookUpList(text);
					}
				}
			}
			flag = flag2 && flag3;
			if (flag)
			{
				continue;
			}
			if (!flag2)
			{
				if (array2[0] < paramArrayRID.NewValueCount())
				{
					array2[0] = paramArrayRID.NewValueCount();
				}
				System.Data.DataSet dataSet = InsertNewLookupValues(paramArrayRID.GetNewValues(), Constants.STPROC_INSERTPARAMARRAYRID, out WarningString2);
				WarningString += WarningString2;
				if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
				{
					paramArrayRID.PopulateValues(dataSet);
				}
				else
				{
					paramArrayRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETPARAMARRAYRID} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
				}
				WarningString += WarningString2;
			}
			if (!flag3)
			{
				if (array2[1] < paramResultOptionsRID.NewValueCount())
				{
					array2[1] = paramResultOptionsRID.NewValueCount();
				}
				System.Data.DataSet dataSet = InsertNewLookupValues(paramResultOptionsRID.GetNewValues(), Constants.STPROC_INSERTPARAMRESULTOPTIONS, out WarningString2);
				WarningString += WarningString2;
				if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
				{
					paramResultOptionsRID.PopulateValues(dataSet);
				}
				else
				{
					paramResultOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETPARAMRESULTOPTIONS, out WarningString2));
				}
				WarningString += WarningString2;
			}
			flag3 = true;
			flag2 = true;
			num2 = Sum(array2);
			num3++;
		}
		if (!IgnoreLookupTables && num3 > num2)
		{
			WarningString = WarningString + "Warning: not all paramlookup information was inserted properly" + Environment.NewLine;
			if (paramRID.NewValueCount() > 0)
			{
				WarningString = WarningString + "New parameters which failed insertion are" + Environment.NewLine;
				WarningString += paramRID.GetNewValues();
			}
			if (paramResultOptionsRID.NewValueCount() > 0)
			{
				WarningString = WarningString + "New paramresults which failed insertion are" + Environment.NewLine;
				WarningString += paramResultOptionsRID.GetNewValues();
			}
		}
		flag = false;
		bool flag4 = true;
		num3 = 0;
		num2 = 0;
		array2 = new int[1];
		List<ROOTTESTParamArrayResults> list = new List<ROOTTESTParamArrayResults>();
		string empty3 = string.Empty;
		list.Clear();
		num = -1;
		tEST = xmlFile.TEST;
		foreach (ROOTTEST rOOTTEST in tEST)
		{
			if (rOOTTEST.ParamResults == null)
			{
				continue;
			}
			ROOTTESTParamResults[] paramResults = rOOTTEST.ParamResults;
			foreach (ROOTTESTParamResults rOOTTESTParamResults in paramResults)
			{
				num++;
				if (rOOTTESTParamResults.ParamArrayResults != null)
				{
					ROOTTESTParamArrayResults[] paramArrayResults = rOOTTESTParamResults.ParamArrayResults;
					foreach (ROOTTESTParamArrayResults rOOTTESTParamArrayResults in paramArrayResults)
					{
						rOOTTESTParamArrayResults.ParamDataRID = array[num][0].ToString();
						rOOTTESTParamArrayResults.StartTime = xmlFile.ConfigInfo.StartTime;
					}
					list.AddRange(rOOTTESTParamResults.ParamArrayResults);
				}
			}
		}
		empty = string.Concat("Execute  ", Constants.STPROC_PARAMARRAYDATA, "  '", SerializeObject(list).Replace("'", "''"), " '");
		dsParamArrayDataRIDs = RunStoredProcAsQuery(empty, out WarningString2);
		WarningString += WarningString2;
		if (dsParamArrayDataRIDs == null)
		{
			badFile = true;
			WarningString += " Param Array data error ";
		}
	}

	private void AddParamResultRuntitle(ref ROOT xmlFile, ConversionType conversionType)
	{
		if (conversionType < ConversionType.Parametric)
		{
			return;
		}
		if (string.IsNullOrEmpty(xmlFile.ConfigInfo.RunTitle))
		{
			xmlFile.ConfigInfo.RunTitle = "ParamResult__ParamResult";
			if (xmlFile.ConfigInfo.Information == null)
			{
				xmlFile.ConfigInfo.Information = new ROOTConfigInfo[0];
			}
		}
		else
		{
			xmlFile.ConfigInfo.RunTitle = "ParamResult__ParamResult_ _" + xmlFile.ConfigInfo.RunTitle;
		}
		ROOTConfigInfo[] array = new ROOTConfigInfo[xmlFile.ConfigInfo.Information.Length + 1];
		ROOTConfigInfo rOOTConfigInfo = new ROOTConfigInfo();
		rOOTConfigInfo.Key = "ParamResult";
		rOOTConfigInfo.Value = "ParamResult";
		xmlFile.ConfigInfo.Information.CopyTo(array, 0);
		array[xmlFile.ConfigInfo.Information.Length] = rOOTConfigInfo;
		xmlFile.ConfigInfo.Information = array;
	}

	private void InsertParamData(System.Data.DataSet dsNodeDataIRDs, out System.Data.DataSet dsParamDataRIDs, out string WarningString, out bool badFile)
	{
		int num = 0;
		string WarningString2 = string.Empty;
		string empty = string.Empty;
		WarningString = string.Empty;
		badFile = false;
		DataTable dataTable = dsNodeDataIRDs.Tables[0];
		DataRow[] array = dataTable.Select("", " nodedatarid asc");
		string empty2 = string.Empty;
		dsParamDataRIDs = null;
		bool flag = false;
		bool flag2 = true;
		bool flag3 = true;
		int num2 = 0;
		int num3 = 0;
		int[] array2 = new int[2];
		while (!flag && num3 <= num2)
		{
			paramRID.ClearNewValues();
			paramResultOptionsRID.ClearNewValues();
			ROOTTEST[] tEST = xmlFile.TEST;
			foreach (ROOTTEST rOOTTEST in tEST)
			{
				if (rOOTTEST.ParamResults == null)
				{
					continue;
				}
				ROOTTESTParamResults[] paramResults = rOOTTEST.ParamResults;
				foreach (ROOTTESTParamResults rOOTTESTParamResults in paramResults)
				{
					string iDFromLookup = paramRID.GetIDFromLookup(rOOTTEST.NodeRID, rOOTTESTParamResults.N, rOOTTESTParamResults.LL, rOOTTESTParamResults.UL);
					if (iDFromLookup != string.Empty)
					{
						rOOTTESTParamResults.ParamRID = iDFromLookup;
					}
					else
					{
						flag2 = false;
						paramRID.AddToNewLookUpList(rOOTTEST.NodeRID, rOOTTESTParamResults.N, rOOTTESTParamResults.LL, rOOTTESTParamResults.UL);
					}
					double result = -9999.0;
					double result2 = -9999.0;
					double result3 = -9999.0;
					string text = Constants.UNDEFINED;
					try
					{
						if (!string.IsNullOrEmpty(rOOTTESTParamResults.LL))
						{
							string lL = rOOTTESTParamResults.LL;
							double.TryParse(lL, out result);
						}
					}
					catch
					{
					}
					try
					{
						if (!string.IsNullOrEmpty(rOOTTESTParamResults.UL))
						{
							string uL = rOOTTESTParamResults.UL;
							double.TryParse(uL, out result2);
						}
					}
					catch
					{
					}
					try
					{
						if (!string.IsNullOrEmpty(rOOTTESTParamResults.V))
						{
							string v = rOOTTESTParamResults.V;
							double.TryParse(v, out result3);
						}
					}
					catch
					{
					}
					string text2 = "";
					try
					{
						if (!string.IsNullOrEmpty(rOOTTESTParamResults.CHAR_V))
						{
							text2 = rOOTTESTParamResults.CHAR_V;
						}
					}
					catch
					{
					}
					if (result == -9999.0 && result2 == -9999.0 && text2.Length == 0)
					{
						text = Constants.UNDEFINED;
					}
					else if (text2.Trim().Length > 0)
					{
						text = Constants.PASSED;
					}
					else if (result3 >= result && result3 <= result2)
					{
						text = Constants.PASSED;
					}
					else if (result3 <= result2 && result == -9999.0)
					{
						text = Constants.PASSED;
					}
					else if (result3 >= result && result2 == -9999.0)
					{
						text = Constants.PASSED;
					}
					else if (result3 < result && result != -9999.0)
					{
						text = Constants.FAILEDLOW;
					}
					else if (result3 > result2 && result2 != -9999.0)
					{
						text = Constants.FAILEDHIGH;
					}
					string iDFromLookup2 = paramResultOptionsRID.GetIDFromLookup(text);
					if (iDFromLookup2 != string.Empty)
					{
						rOOTTESTParamResults.ParamResultOptionRID = iDFromLookup2;
						continue;
					}
					flag3 = false;
					paramResultOptionsRID.AddToNewLookUpList(text);
				}
			}
			flag = flag2 && flag3;
			if (flag)
			{
				continue;
			}
			if (!flag2)
			{
				if (array2[0] < paramRID.NewValueCount())
				{
					array2[0] = paramRID.NewValueCount();
				}
				System.Data.DataSet dataSet = InsertNewLookupValues(paramRID.GetNewValues(), Constants.STPROC_INSERTPARAMRID, out WarningString2);
				WarningString += WarningString2;
				if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
				{
					paramRID.PopulateValues(dataSet);
				}
				else
				{
					paramRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETPARAMRID} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
				}
				WarningString += WarningString2;
			}
			if (!flag3)
			{
				if (array2[1] < paramResultOptionsRID.NewValueCount())
				{
					array2[1] = paramResultOptionsRID.NewValueCount();
				}
				System.Data.DataSet dataSet = InsertNewLookupValues(paramResultOptionsRID.GetNewValues(), Constants.STPROC_INSERTPARAMRESULTOPTIONS, out WarningString2);
				WarningString += WarningString2;
				if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
				{
					paramResultOptionsRID.PopulateValues(dataSet);
				}
				else
				{
					paramResultOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETPARAMRESULTOPTIONS, out WarningString2));
				}
				WarningString += WarningString2;
			}
			flag3 = true;
			flag2 = true;
			num2 = Sum(array2);
			num3++;
		}
		if (!IgnoreLookupTables && num3 > num2)
		{
			WarningString = WarningString + "Warning: not all paramlookup information was inserted properly" + Environment.NewLine;
			if (paramRID.NewValueCount() > 0)
			{
				WarningString = WarningString + "New parameters which failed insertion are" + Environment.NewLine;
				WarningString += paramRID.GetNewValues();
			}
			if (paramResultOptionsRID.NewValueCount() > 0)
			{
				WarningString = WarningString + "New paramresults which failed insertion are" + Environment.NewLine;
				WarningString += paramResultOptionsRID.GetNewValues();
			}
		}
		flag = false;
		bool flag4 = true;
		num3 = 0;
		num2 = 0;
		array2 = new int[1];
		List<ROOTTESTParamResults> list = new List<ROOTTESTParamResults>();
		string empty3 = string.Empty;
		while (!flag && num3 <= num2)
		{
			list.Clear();
			num = 0;
			paramDetailsRID.ClearNewValues();
			ROOTTEST[] tEST = xmlFile.TEST;
			foreach (ROOTTEST rOOTTEST in tEST)
			{
				if (rOOTTEST.ParamResults != null)
				{
					ROOTTESTParamResults[] paramResults = rOOTTEST.ParamResults;
					foreach (ROOTTESTParamResults rOOTTESTParamResults in paramResults)
					{
						if (ProcessParamAttributes)
						{
							if (rOOTTEST.LOOPVALUES != null)
							{
								rOOTTESTParamResults.ParamAttributesRID = paramAttributesRID.GetIDFromLookup(rOOTTEST.TNAME, rOOTTESTParamResults.N, Regex.Replace(rOOTTEST.LOOPVALUES.LV.V, "(_ _|)RetryCount__\\d(_ _|)", string.Empty));
							}
							else
							{
								rOOTTESTParamResults.ParamAttributesRID = paramAttributesRID.GetIDFromLookup(rOOTTEST.TNAME, rOOTTESTParamResults.N, string.Empty);
							}
						}
						empty2 = paramDetailsRID.GetIDFromLookup(rOOTTEST.NodeDetailsRID, rOOTTESTParamResults.ParamRID, rOOTTESTParamResults.ParamAttributesRID);
						if (empty2 != string.Empty)
						{
							rOOTTESTParamResults.ParamDetailsRID = empty2;
						}
						else
						{
							flag4 = false;
							paramDetailsRID.AddToNewLookUpList(rOOTTEST.NodeDetailsRID, rOOTTESTParamResults.ParamRID, rOOTTESTParamResults.ParamAttributesRID);
						}
						rOOTTESTParamResults.NodeDataRID = array[num][0].ToString();
						rOOTTESTParamResults.StartTime = xmlFile.ConfigInfo.StartTime;
					}
					list.AddRange(rOOTTEST.ParamResults);
				}
				num++;
			}
			flag = flag4;
			if (flag)
			{
				continue;
			}
			if (!flag4)
			{
				if (array2[0] < paramDetailsRID.NewValueCount())
				{
					array2[0] = paramDetailsRID.NewValueCount();
				}
				System.Data.DataSet dataSet = InsertNewLookupValues(paramDetailsRID.GetNewValues(), Constants.STPROC_INSERTPARAMDETAILS, out WarningString2);
				WarningString += WarningString2;
				if (!IgnoreLookupTables)
				{
					if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
					{
						paramDetailsRID.PopulateValues(dataSet);
					}
					else
					{
						paramDetailsRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETPARAMDETAILS} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
					}
				}
				WarningString += WarningString2;
			}
			flag4 = true;
			num2 = Sum(array2);
			num3++;
		}
		if (!IgnoreLookupTables && num3 > num2)
		{
			WarningString = WarningString + "Warning: not all paramDetails information was inserted properly" + Environment.NewLine;
			if (paramDetailsRID.NewValueCount() > 0)
			{
				WarningString = WarningString + "New paramDetails which failed insertion are" + Environment.NewLine;
				WarningString += paramDetailsRID.GetNewValues();
			}
		}
		dsNodeDataIRDs.Clear();
		dataTable.Clear();
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder = SerializeObject(list);
		empty = string.Concat("Execute  ", Constants.STPROC_PARAMDATA, "  '", stringBuilder.Replace("'", "''"), " '");
		dsParamDataRIDs = RunStoredProcAsQuery(empty, out WarningString2);
		stringBuilder.Length = 0;
		empty = string.Empty;
		WarningString += WarningString2;
		if (dsParamDataRIDs == null)
		{
			badFile = true;
			WarningString += "Param data error ";
		}
	}

	private void InsertTestData(out System.Data.DataSet dsNodeDataIRDs, out string WarningString, out bool badFile)
	{
		WarningString = string.Empty;
		badFile = false;
		string WarningString2 = string.Empty;
		dsNodeDataIRDs = null;
		string empty = string.Empty;
		string empty2 = string.Empty;
		string empty3 = string.Empty;
		bool flag = false;
		try
		{
			int[] array = new int[5];
			int num = 0;
			int num2 = 0;
			flag = false;
			bool flag2 = true;
			bool flag3 = true;
			bool flag4 = true;
			bool flag5 = true;
			bool flag6 = true;
			while (!flag && num <= num2)
			{
				nodeRID.ClearNewValues();
				scenarioCombinedOptionsRID.ClearNewValues();
				scenarioSplitOptionsRID.ClearNewValues();
				resultOptionsRID.ClearNewValues();
				errorCodeOptionsRID.ClearNewValues();
				ROOTTEST[] tEST = xmlFile.TEST;
				foreach (ROOTTEST rOOTTEST in tEST)
				{
					empty2 = nodeRID.GetIDFromLookup(rOOTTEST.TNAME);
					if (empty2 != string.Empty)
					{
						rOOTTEST.NodeRID = empty2;
					}
					else
					{
						flag2 = false;
						nodeRID.AddToNewLookUpList(rOOTTEST.TNAME);
					}
					if (rOOTTEST.LOOPVALUES != null)
					{
						string iDFromLookup = scenarioCombinedOptionsRID.GetIDFromLookup(rOOTTEST.LOOPVALUES.LV.V);
						if (iDFromLookup != string.Empty)
						{
							rOOTTEST.ScenarioCombinedOptionsRID = iDFromLookup;
						}
						else
						{
							flag3 = false;
							scenarioCombinedOptionsRID.AddToNewLookUpList(rOOTTEST.LOOPVALUES.LV.V);
						}
					}
					if (rOOTTEST.Inputs != null)
					{
						ROOTTESTInput[] inputs = rOOTTEST.Inputs;
						foreach (ROOTTESTInput rOOTTESTInput in inputs)
						{
							string iDFromLookup2 = scenarioSplitOptionsRID.GetIDFromLookup(rOOTTESTInput.Key, rOOTTESTInput.Value);
							if (iDFromLookup2 != string.Empty)
							{
								rOOTTESTInput.ScenarioSplitOptionsRID = iDFromLookup2;
								continue;
							}
							flag4 = false;
							scenarioSplitOptionsRID.AddToNewLookUpList(rOOTTESTInput.Key, rOOTTESTInput.Value);
						}
					}
					string iDFromLookup3 = resultOptionsRID.GetIDFromLookup(rOOTTEST.RES);
					if (iDFromLookup3 != string.Empty)
					{
						rOOTTEST.ResultOptionsRID = iDFromLookup3;
					}
					else
					{
						flag5 = false;
						resultOptionsRID.AddToNewLookUpList(rOOTTEST.RES);
					}
					if (!string.IsNullOrEmpty(rOOTTEST.ERROR_CODE))
					{
						string combinedRID = string.Empty;
						InsertSubErrorCodeCombinedOptions(string.Empty, out combinedRID, ref WarningString2);
						string iDFromLookup4 = errorCodeOptionsRID.GetIDFromLookup(rOOTTEST.ERROR_CODE, combinedRID);
						if (iDFromLookup4 != string.Empty)
						{
							rOOTTEST.ErrorCodeRID = iDFromLookup4;
							continue;
						}
						flag6 = false;
						errorCodeOptionsRID.AddToNewLookUpList(rOOTTEST.ERROR_CODE, combinedRID);
					}
				}
				flag = flag2 && flag3 && flag4 && flag5 && flag6;
				if (flag)
				{
					continue;
				}
				if (!flag2)
				{
					if (array[0] < nodeRID.NewValueCount())
					{
						array[0] = nodeRID.NewValueCount();
					}
					System.Data.DataSet dataSet = InsertNewLookupValues(nodeRID.GetNewValues(), Constants.STPROC_INSERTNODE, out WarningString2);
					WarningString += WarningString2;
					if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
					{
						nodeRID.PopulateValues(dataSet);
					}
					else
					{
						nodeRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETNODERID} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
					}
					WarningString += WarningString2;
				}
				if (!flag3)
				{
					if (array[1] < scenarioCombinedOptionsRID.NewValueCount())
					{
						array[1] = scenarioCombinedOptionsRID.NewValueCount();
					}
					System.Data.DataSet dataSet = InsertNewLookupValues(scenarioCombinedOptionsRID.GetNewValues(), Constants.STPROC_INSERTSCENARIOCOMBINEDOPTIONS, out WarningString2);
					WarningString += WarningString2;
					if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
					{
						scenarioCombinedOptionsRID.PopulateValues(dataSet);
					}
					else
					{
						scenarioCombinedOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETSCENARIOCOMBINEDOPTIONS, out WarningString2));
					}
					WarningString += WarningString2;
				}
				if (!flag4)
				{
					if (array[2] < scenarioSplitOptionsRID.NewValueCount())
					{
						array[2] = scenarioSplitOptionsRID.NewValueCount();
					}
					System.Data.DataSet dataSet = InsertNewLookupValues(scenarioSplitOptionsRID.GetNewValues(), Constants.STPROC_INSERTSCENARIOSPLITOPTIONS, out WarningString2);
					WarningString += WarningString2;
					if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
					{
						scenarioSplitOptionsRID.PopulateValues(dataSet);
					}
					else
					{
						scenarioSplitOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETSCENARIOSPLITOPTIONS, out WarningString2));
					}
					WarningString += WarningString2;
				}
				if (!flag5)
				{
					if (array[3] < resultOptionsRID.NewValueCount())
					{
						array[3] = resultOptionsRID.NewValueCount();
					}
					System.Data.DataSet dataSet = InsertNewLookupValues(resultOptionsRID.GetNewValues(), Constants.STPROC_INSERTRESULTOPTIONS, out WarningString2);
					WarningString += WarningString2;
					if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
					{
						resultOptionsRID.PopulateValues(dataSet);
					}
					else
					{
						resultOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETRESULTOPTIONSRID, out WarningString2));
					}
					WarningString += WarningString2;
				}
				if (!flag6)
				{
					if (array[4] < errorCodeOptionsRID.NewValueCount())
					{
						array[4] = errorCodeOptionsRID.NewValueCount();
					}
					System.Data.DataSet dataSet = InsertNewLookupValues(errorCodeOptionsRID.GetNewValues(), Constants.STPROC_INSERTERRORCODEOPTIONS, out WarningString2);
					WarningString += WarningString2;
					if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
					{
						errorCodeOptionsRID.PopulateValues(dataSet);
					}
					else
					{
						errorCodeOptionsRID.PopulateValues(GetLookupValues(Constants.STPROC_GETERRORCODE, out WarningString2));
					}
					WarningString += WarningString2;
				}
				num2 = Sum(array);
				num++;
				flag2 = true;
				flag3 = true;
				flag4 = true;
				flag5 = true;
				flag6 = true;
			}
			if (num > num2)
			{
				WarningString = WarningString + "Warning: not all testnode lookup information was inserted properly" + Environment.NewLine;
				if (nodeRID.NewValueCount() > 0)
				{
					WarningString = WarningString + "New tests which failed insertion are" + Environment.NewLine;
					WarningString += nodeRID.GetNewValues();
				}
				if (scenarioCombinedOptionsRID.NewValueCount() > 0)
				{
					WarningString = WarningString + "New ScenarioCombinedOptions which failed insertion are" + Environment.NewLine;
					WarningString += scenarioCombinedOptionsRID.GetNewValues();
				}
				if (scenarioSplitOptionsRID.NewValueCount() > 0)
				{
					WarningString = WarningString + "New ScenarioSplitOptions which failed insertion are" + Environment.NewLine;
					WarningString += scenarioSplitOptionsRID.GetNewValues();
				}
				if (resultOptionsRID.NewValueCount() > 0)
				{
					WarningString = WarningString + "New Results which failed insertion are" + Environment.NewLine;
					WarningString += resultOptionsRID.GetNewValues();
				}
				if (errorCodeOptionsRID.NewValueCount() > 0)
				{
					WarningString = WarningString + "New errorcodes which failed insertion are" + Environment.NewLine;
					WarningString += errorCodeOptionsRID.GetNewValues();
				}
			}
			flag = false;
			bool flag7 = true;
			bool flag8 = true;
			num2 = 0;
			num = 0;
			array = new int[2];
			while (!flag && num <= num2)
			{
				NodeDetailsRID.ClearNewValues();
				scenarioSplitConditionsRID.ClearNewValues();
				ROOTTEST[] tEST = xmlFile.TEST;
				foreach (ROOTTEST rOOTTEST in tEST)
				{
					empty = nodeDetailsRID.GetIDFromLookup(rOOTTEST.NodeRID, rOOTTEST.ScenarioCombinedOptionsRID);
					if (empty != string.Empty)
					{
						rOOTTEST.NodeDetailsRID = empty;
					}
					else
					{
						flag7 = false;
						nodeDetailsRID.AddToNewLookUpList(rOOTTEST.NodeRID, rOOTTEST.ScenarioCombinedOptionsRID);
					}
					if (!string.IsNullOrEmpty(rOOTTEST.NodeDetailsRID) && rOOTTEST.LOOPVALUES != null && rOOTTEST.Inputs != null)
					{
						ROOTTESTInput[] inputs = rOOTTEST.Inputs;
						foreach (ROOTTESTInput rOOTTESTInput in inputs)
						{
							scenarioSplitConditionsRID.AddToNewLookUpList(rOOTTEST.NodeDetailsRID, rOOTTESTInput.ScenarioSplitOptionsRID);
						}
					}
					rOOTTEST.StartTime = xmlFile.ConfigInfo.StartTime;
				}
				InsertNewLookupValues(scenarioSplitConditionsRID.GetNewValues(), Constants.STPROC_SCENARIOSPLITCONDITIONS, out WarningString2);
				flag = flag7 && flag8;
				if (flag)
				{
					continue;
				}
				if (!flag7)
				{
					if (array[0] < nodeDetailsRID.NewValueCount())
					{
						array[0] = nodeDetailsRID.NewValueCount();
					}
					System.Data.DataSet dataSet = InsertNewLookupValues(nodeDetailsRID.GetNewValues(), Constants.STPROC_INSERTNODEDETAILS, out WarningString2);
					WarningString += WarningString2;
					if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
					{
						nodeDetailsRID.PopulateValues(dataSet);
					}
					else
					{
						nodeDetailsRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETNODEDETAILS} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
					}
					WarningString += WarningString2;
				}
				if (!flag8)
				{
					if (array[1] < scenarioSplitConditionsRID.NewValueCount())
					{
						array[1] = scenarioSplitConditionsRID.NewValueCount();
					}
					System.Data.DataSet dataSet = InsertNewLookupValues(scenarioSplitConditionsRID.GetNewValues(), Constants.STPROC_SCENARIOSPLITCONDITIONS, out WarningString2);
					WarningString += WarningString2;
					if (dataSet != null && dataSet.Tables[0].Rows.Count > 0)
					{
						scenarioSplitConditionsRID.PopulateValues(dataSet);
					}
					else
					{
						scenarioSplitConditionsRID.PopulateValues(GetLookupValues($"{Constants.STPROC_GETSCENARIOSPLITCONDITIONS} {xmlFile.ConfigInfo.TreeID}", out WarningString2));
					}
					WarningString += WarningString2;
				}
				num2 = Sum(array);
				num++;
				flag7 = true;
				flag8 = true;
			}
			if (num > num2)
			{
				WarningString = WarningString + "Warning: not all nodeDetails or scenarioSplitOptions information was inserted properly" + Environment.NewLine;
				if (nodeDetailsRID.NewValueCount() > 0)
				{
					WarningString = WarningString + "New nodedetails which failed insertion are" + Environment.NewLine;
					WarningString += nodeDetailsRID.GetNewValues();
				}
				if (scenarioSplitConditionsRID.NewValueCount() > 0)
				{
					WarningString = WarningString + "New ScenarioSpliConditions which failed insertion are" + Environment.NewLine;
					WarningString += scenarioSplitConditionsRID.GetNewValues();
				}
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder = SerializeObject(xmlFile.TEST);
			empty3 = string.Concat("Execute  ", Constants.STPROC_NODEDATA, "  '", stringBuilder.Replace("'", "''"), "', ", xmlFile.ConfigInfo.SessionDataRID);
			dsNodeDataIRDs = RunStoredProcAsQuery(empty3, out WarningString2);
			stringBuilder.Length = 0;
			empty3 = string.Empty;
			WarningString += WarningString2;
			if (dsNodeDataIRDs == null)
			{
				badFile = true;
			}
		}
		catch (Exception ex)
		{
			WarningString = WarningString + "\n Error inserting Test Data" + ex.ToString();
			badFile = true;
		}
	}
}
