c# System.ObjectDisposedException: 'Cannot access a disposed object. Object name: 'SQLiteConnection'.'

mion shion 241 Reputation points
2022-10-19T12:41:49.39+00:00

good afternoon,

i been working on some code for a while now and its a bulid of a game for bo3 mod tools ( they are released so is open )

but i having issue i trying to get the validate db to work for the life of me i cant i get the error,

System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'SQLiteConnection'.'

managed to get everything else working its a console app with flags,

and the db class is as follows,

using System;  
using System.Collections.Generic;  
using System.Data;  
using System.Data.SQLite;  
using System.Diagnostics;  
using System.IO;  
using System.Text;  
using gdtDB.Properties;  
  
namespace gdtDB  
{  
	// Token: 0x02000008 RID: 8  
	internal class db  
	{  
		// Token: 0x06000041 RID: 65 RVA: 0x0000237C File Offset: 0x0000057C  
		public static bool OpenDB(db.OpenDBOpt opt)  
		{  
			for (;;)  
			{  
				SQLiteErrorCode sqliteErrorCode = SQLiteErrorCode.Ok;  
				try  
				{  
					Stopwatch stopwatch = new Stopwatch();  
					stopwatch.Start();  
					bool result = db.OpenDBUnsafe(opt);  
					stopwatch.Stop();  
					msgLog.Verbose("OpenDB took: {0:0.000} sec", new object[]  
					{  
						stopwatch.Elapsed.TotalSeconds  
					});  
					return result;  
				}  
				catch (SQLiteException ex)  
				{  
					sqliteErrorCode = ex.ResultCode;  
					if (sqliteErrorCode != SQLiteErrorCode.Locked && sqliteErrorCode != SQLiteErrorCode.Busy && sqliteErrorCode != SQLiteErrorCode.Corrupt)  
					{  
						msgLog.Error(string.Format("ERROR: Can't open DB (SQLiteException={0}): {1}", sqliteErrorCode.ToString(), ex.Message.Replace(Environment.NewLine, ": ")));  
					}  
				}  
				catch (Exception ex2)  
				{  
					sqliteErrorCode = SQLiteErrorCode.Unknown;  
					msgLog.Error(string.Format("ERROR: Can't open DB: {0}", ex2.Message.Replace(Environment.NewLine, ": ")));  
				}  
				db.Conn.Close();  
				db.Conn.Dispose();  
				db.Conn = null;  
				if (sqliteErrorCode == SQLiteErrorCode.Corrupt)  
				{  
					msgLog.Status("Database is Corrupt! Deleting and Rebuilding...");  
					try  
					{  
						File.Delete(db.Filename);  
					}  
					catch (Exception ex3)  
					{  
						msgLog.Error(string.Format("ERROR: Failed to delete corrupt DB: {0}", ex3.Message.Replace(Environment.NewLine, ": ")));  
						return false;  
					}  
					opt = db.OpenDBOpt.Rebuild;  
				}  
				else  
				{  
					if (sqliteErrorCode != SQLiteErrorCode.Locked && sqliteErrorCode != SQLiteErrorCode.Busy)  
					{  
						break;  
					}  
					msgLog.Status("Database is busy! Retrying...");  
				}  
			}  
			return false;  
		}  
  
		// Token: 0x06000042 RID: 66 RVA: 0x000024F8 File Offset: 0x000006F8  
		public static bool OpenDBUnsafe(db.OpenDBOpt opt)  
		{  
			if (opt == db.OpenDBOpt.Undefined)  
			{  
				return false;  
			}  
			db.openedStatus = opt;  
			if (db.IsOpen)  
			{  
				msgLog.Error("Cannot open another database until the prior one is closed.");  
				db.openedStatus = db.OpenDBOpt.Undefined;  
				return false;  
			}  
			string filename = db.Filename;  
			db.Conn = new SQLiteConnection("data source=" + filename);  
			db.Conn.Open();  
			if (db.Conn.State != ConnectionState.Open)  
			{  
				msgLog.Error("Failed to open a database connection.");  
				db.Conn = null;  
				return false;  
			}  
			db.Conn.Update += db.UpdateEventHandler;  
			db.Cmd = db.Conn.CreateCommand();  
			db.Cmd.CommandText = "PRAGMA synchronous = OFF; PRAGMA page_size = 32768; PRAGMA journal_mode=wal;";  
			db.Cmd.ExecuteNonQuery();  
			db.Trans = db.Conn.BeginTransaction();  
			db.Cmd_GetGDF = new SQLiteCommand("SELECT PK_id FROM _gdf WHERE name=@name;", db.Conn);  
			db.Cmd_GetGDF.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_GetGDT = new SQLiteCommand("SELECT PK_id FROM _gdt WHERE name=@name;", db.Conn);  
			db.Cmd_GetGDT.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_GetGDT_name = new SQLiteCommand("SELECT name FROM _gdt;", db.Conn);  
			db.Cmd_GetGDT_time = new SQLiteCommand("SELECT PK_id,timestamp FROM _gdt WHERE name=@name;", db.Conn);  
			db.Cmd_GetGDT_time.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_GetEntityId = new SQLiteCommand("SELECT _entity.PK_id FROM _entity WHERE _entity.name=@name AND _entity.FK_gdt=@FK_gdt;", db.Conn);  
			db.Cmd_GetEntityId.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_GetEntityId.Parameters.Add(new SQLiteParameter("@FK_gdt"));  
			db.Cmd_GetEntityParent = new SQLiteCommand("SELECT PK_id,FK_parent_id FROM _entity WHERE name=@name AND FK_gdf=@FK_gdf;", db.Conn);  
			db.Cmd_GetEntityParent.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_GetEntityParent.Parameters.Add(new SQLiteParameter("@FK_gdf"));  
			db.Cmd_GetEntityName = new SQLiteCommand("SELECT _entity.name FROM _entity WHERE _entity.PK_id=@PK_id;", db.Conn);  
			db.Cmd_GetEntityName.Parameters.Add(new SQLiteParameter("@PK_id"));  
			db.Cmd_GetIdEntityGDF = new SQLiteCommand("SELECT _gdf.name,_entity.name FROM _entity INNER JOIN _gdf ON _entity.FK_gdf = _gdf.PK_id WHERE _entity.PK_id=@PK_id;", db.Conn);  
			db.Cmd_GetIdEntityGDF.Parameters.Add(new SQLiteParameter("@PK_id"));  
			db.Cmd_GetNamedEntityGDF = new SQLiteCommand("SELECT _gdf.name,_entity.PK_id FROM _entity INNER JOIN _gdf ON _entity.FK_gdf = _gdf.PK_id WHERE _entity.name=@name;", db.Conn);  
			db.Cmd_GetNamedEntityGDF.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_GetGDFsGDTs = new SQLiteCommand("SELECT _entity.FK_gdt FROM _entity WHERE _entity.FK_gdf = @FK_gdf", db.Conn);  
			db.Cmd_GetGDFsGDTs.Parameters.Add(new SQLiteParameter("@FK_gdf"));  
			db.Cmd_GetEntityGDT = new SQLiteCommand("SELECT _gdt.PK_id,_gdt.name,_gdt.bOpenForEdit FROM _entity INNER JOIN _gdt ON _entity.FK_gdt = _gdt.PK_id WHERE _entity.name=@name;", db.Conn);  
			db.Cmd_GetEntityGDT.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_GetEntityIDsGDT = new SQLiteCommand("SELECT _entity.name,_entity.PK_id FROM _entity WHERE _entity.FK_gdt=@FK_gdt;", db.Conn);  
			db.Cmd_GetEntityIDsGDT.Parameters.Add(new SQLiteParameter("@FK_gdt"));  
			db.Cmd_GetEntityForSave = new SQLiteCommand("SELECT _entity.PK_id as entityID, _entity.FK_parent_id as parentID, _entity.name as entityName, _gdf.name as gdfName\r\n                  FROM _entity,_gdf ON _entity.FK_gdf = _gdf.PK_id\r\n                  WHERE FK_gdt=@FK_gdt ORDER BY _entity.iGdtSeqNum;", db.Conn);  
			db.Cmd_GetEntityForSave.Parameters.Add(new SQLiteParameter("@FK_gdt"));  
			db.Cmd_CreateGDT = new SQLiteCommand("INSERT INTO _gdt (name,timestamp) VALUES (@name, @timestamp);SELECT last_insert_rowid();", db.Conn);  
			db.Cmd_CreateGDT.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_CreateGDT.Parameters.Add(new SQLiteParameter("@timestamp"));  
			db.Cmd_CreateEntity = new SQLiteCommand("INSERT INTO _entity (name,iGdtSeqNum,FK_parent_id,FK_gdf,FK_gdt,_gdt_linenum) VALUES (@name,@iGdtSeqNum,@FK_parent_id,@FK_gdf,@FK_gdt,@_gdt_linenum);SELECT last_insert_rowid();", db.Conn);  
			db.Cmd_CreateEntity.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_CreateEntity.Parameters.Add(new SQLiteParameter("@iGdtSeqNum"));  
			db.Cmd_CreateEntity.Parameters.Add(new SQLiteParameter("@FK_parent_id"));  
			db.Cmd_CreateEntity.Parameters.Add(new SQLiteParameter("@FK_gdf"));  
			db.Cmd_CreateEntity.Parameters.Add(new SQLiteParameter("@FK_gdt"));  
			db.Cmd_CreateEntity.Parameters.Add(new SQLiteParameter("@_gdt_linenum"));  
			db.Cmd_UpdateGDT = new SQLiteCommand("UPDATE _gdt SET timestamp=@timestamp WHERE PK_id=@PK_id;", db.Conn);  
			db.Cmd_UpdateGDT.Parameters.Add(new SQLiteParameter("@timestamp"));  
			db.Cmd_UpdateGDT.Parameters.Add(new SQLiteParameter("@PK_id"));  
			db.Cmd_UpdateEntity = new SQLiteCommand("UPDATE _entity SET iGdtSeqNum=@iGdtSeqNum, FK_parent_id=@FK_parent_id, FK_gdf=@FK_gdf, FK_gdt=@FK_gdt, _gdt_linenum=@_gdt_linenum WHERE PK_id=@PK_id;", db.Conn);  
			db.Cmd_UpdateEntity.Parameters.Add(new SQLiteParameter("@iGdtSeqNum"));  
			db.Cmd_UpdateEntity.Parameters.Add(new SQLiteParameter("@FK_parent_id"));  
			db.Cmd_UpdateEntity.Parameters.Add(new SQLiteParameter("@FK_gdf"));  
			db.Cmd_UpdateEntity.Parameters.Add(new SQLiteParameter("@FK_gdt"));  
			db.Cmd_UpdateEntity.Parameters.Add(new SQLiteParameter("@PK_id"));  
			db.Cmd_UpdateEntity.Parameters.Add(new SQLiteParameter("@_gdt_linenum"));  
			db.Cmd_MarkExportEntityByName = new SQLiteCommand("UPDATE _entity SET bExport=1 WHERE name=@name AND FK_gdf=@FK_gdf;", db.Conn);  
			db.Cmd_MarkExportEntityByName.Parameters.Add(new SQLiteParameter("@name"));  
			db.Cmd_MarkExportEntityByName.Parameters.Add(new SQLiteParameter("@FK_gdf"));  
			db.Cmd_GetEntityForExport = new SQLiteCommand("SELECT _entity.PK_id as entityID, _entity.FK_parent_id as parentID, _entity.name as entityName, _gdf.name as gdfName\r\n                  FROM _entity,_gdf ON _entity.FK_gdf = _gdf.PK_id\r\n                  WHERE FK_gdt=@FK_gdt AND _entity.bExport>0 ORDER BY _entity.iGdtSeqNum;", db.Conn);  
			db.Cmd_GetEntityForExport.Parameters.Add(new SQLiteParameter("@FK_gdt"));  
			db.Cmd_GetXAnimForExportByID = new SQLiteCommand("SELECT\r\n                    model,filename,previewModel,previewAttachModel\r\n                  FROM xanim\r\n                  WHERE PK_id=@id;", db.Conn);  
			db.Cmd_GetXAnimForExportByID.Parameters.Add(new SQLiteParameter("@id"));  
			db.Cmd_GetXModelForExportByID = new SQLiteCommand("SELECT\r\n                    filename,mediumLod,lowLod,lowestLod,lod4File,lod5File,lod6File,lod7File,BulletCollisionFile,\r\n                    skinOverride,\r\n                    submodel0_Name,submodel1_Name,submodel2_Name,submodel3_Name,submodel4_Name,submodel5_Name,submodel6_Name,submodel7_Name,submodel8_Name,\r\n                    submodel9_Name,submodel10_Name,submodel11_Name,submodel12_Name,submodel13_Name,submodel14_Name,submodel15_Name\r\n                  FROM xmodel\r\n                  WHERE PK_id=@id;", db.Conn);  
			db.Cmd_GetXModelForExportByID.Parameters.Add(new SQLiteParameter("@id"));  
			db.Cmd_GetMaterialForExportByID = new SQLiteCommand("SELECT\r\n                    alphaMap,alphaRevealMap,camoDetailMap,camoMaskMap,colorMap,colorMap00,colorMap01,colorMap02,colorMap03,colorMap04,colorMap05,colorMap06,colorMap07,colorMap08,\r\n                    colorMap09,colorMap10,colorMap11,colorMap12,colorMap13,colorMap14,colorMap15,cosinePowerMap,detailMap,flickerLookupMap,heatmap,normalMap,occMap,specColorMap,\r\n                    specDetailMap,specReflectionMap,sw_codetexture_00,sw_codetexture_01,sw_codetexture_02,sw_codetexture_03,sw_codetexture_04,sw_codetexture_05,sw_codetexture_06,\r\n                    sw_codetexture_07,sw_codetexture_08,sw_codetexture_09,sw_codetexture_10,sw_codetexture_11,sw_codetexture_12,sw_codetexture_13,sw_codetexture_14,sw_codetexture_15,\r\n                    transColorMap,transGlossMap,transNormalMap,transRevealMap,transSpecMap\r\n                  FROM material\r\n                  WHERE PK_id=@id;", db.Conn);  
			db.Cmd_GetMaterialForExportByID.Parameters.Add(new SQLiteParameter("@id"));  
			if (db.openedStatus == db.OpenDBOpt.NonUpdate)  
			{  
				return true;  
			}  
			bool flag = true;  
			int num = 0;  
			if (db.openedStatus == db.OpenDBOpt.Rebuild)  
			{  
				flag = false;  
			}  
			else  
			{  
				db.Cmd.CommandText = "PRAGMA user_version;";  
				try  
				{  
					SQLiteDataReader sqliteDataReader = db.Cmd.ExecuteReader();  
					if (sqliteDataReader.HasRows)  
					{  
						sqliteDataReader.Read();  
						num = sqliteDataReader.GetInt32(0);  
					}  
					sqliteDataReader.Close();  
				}  
				catch (SQLiteException)  
				{  
					flag = false;  
				}  
				if (num != db.currentVersion)  
				{  
					flag = false;  
				}  
			}  
			if (!flag)  
			{  
				db.openedStatus = db.OpenDBOpt.Rebuild;  
				msgLog.Verbose("Rebuilding database");  
			}  
			else if (db.openedStatus == db.OpenDBOpt.Update)  
			{  
				StringBuilder stringBuilder = null;  
				db.Cmd.CommandText = "SELECT name,md5,PK_id FROM _gdf;";  
				SQLiteDataReader sqliteDataReader;  
				try  
				{  
					sqliteDataReader = db.Cmd.ExecuteReader();  
				}  
				catch  
				{  
					db.openedStatus = db.OpenDBOpt.Rebuild;  
					sqliteDataReader = null;  
				}  
				if (db.openedStatus == db.OpenDBOpt.Update && sqliteDataReader.HasRows)  
				{  
					while (sqliteDataReader.Read())  
					{  
						string @string = sqliteDataReader.GetString(0);  
						if (gdf.collection.ContainsKey(@string))  
						{  
							gdf.collection[@string].isInDb = true;  
							if (gdf.collection[@string].md5 != sqliteDataReader.GetString(1))  
							{  
								db.openedStatus = db.OpenDBOpt.Rebuild;  
								break;  
							}  
						}  
						else  
						{  
							if (Settings.Default.DeleteMissingGdf)  
							{  
								if (stringBuilder == null)  
								{  
									stringBuilder = new StringBuilder();  
								}  
								stringBuilder.Append(string.Format("DELETE from _gdf WHERE PK_id={0}; DELETE from _entity WHERE FK_gdf={0}; DROP TABLE IF EXISTS '{1}';", sqliteDataReader.GetInt32(2), @string));  
								break;  
							}  
							break;  
						}  
					}  
					sqliteDataReader.Close();  
				}  
				if (stringBuilder != null)  
				{  
					db.Cmd.CommandText = stringBuilder.ToString();  
					db.Cmd.ExecuteNonQuery();  
				}  
			}  
			if (db.openedStatus == db.OpenDBOpt.Update)  
			{  
				foreach (gdf gdf in gdf.collection.Values)  
				{  
					if (!gdf.isInDb)  
					{  
						db.openedStatus = db.OpenDBOpt.Rebuild;  
						break;  
					}  
				}  
				if (db.openedStatus == db.OpenDBOpt.Update)  
				{  
					return true;  
				}  
			}  
			bool flag2 = false;  
			if (!flag)  
			{  
				flag2 = true;  
			}  
			else  
			{  
				db.Cmd.CommandText = "SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name IN ('_entity','_gdf','_gdt','_meta');";  
				if (Convert.ToInt64(db.Cmd.ExecuteScalar()) != 4L)  
				{  
					flag2 = true;  
				}  
			}  
			if (flag2)  
			{  
				db.Cmd.CommandText = string.Format("DROP TABLE IF EXISTS _gdf;", new object[0]);  
				db.Cmd.ExecuteNonQuery();  
				db.Cmd.CommandText = "CREATE TABLE _gdf (\r\n                    PK_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n                    name TEXT NOT NULL,\r\n                    md5 TEXT );\r\n                  CREATE UNIQUE INDEX IX_gdfName      ON _gdf(name);";  
				db.Cmd.ExecuteNonQuery();  
				db.Cmd.CommandText = string.Format("DROP TABLE IF EXISTS _meta;", new object[0]);  
				db.Cmd.ExecuteNonQuery();  
				db.Cmd.CommandText = "CREATE TABLE _meta (\r\n                            _name TEXT NOT NULL,\r\n                            _key TEXT NOT NULL,\r\n                            _type TEXT NOT NULL,\r\n                            _default TEXT NOT NULL,\r\n                            _min NUMERIC NOT NULL,\r\n                            _max NUMERIC NOT NULL,\r\n                            _enums TEXT NOT NULL,\r\n                            _index INTEGER NOT NULL\r\n                         );\r\n                         CREATE UNIQUE INDEX IX_metaNameKey ON _meta(_name, _key);";  
				db.Cmd.ExecuteNonQuery();  
				db.Cmd.CommandText = string.Format("DROP TABLE IF EXISTS _gdt;", new object[0]);  
				db.Cmd.ExecuteNonQuery();  
				db.Cmd.CommandText = "CREATE TABLE _gdt (\r\n                    PK_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n                    name TEXT NOT NULL,\r\n                    bOpenForEdit INT DEFAULT 0,\r\n                    timestamp INTEGER DEFAULT 0 );\r\n                  CREATE UNIQUE INDEX IX_gdtName ON _gdt(name);";  
				db.Cmd.ExecuteNonQuery();  
				db.Cmd.CommandText = string.Format("DROP TABLE IF EXISTS _entity;", new object[0]);  
				db.Cmd.ExecuteNonQuery();  
				db.Cmd.CommandText = "CREATE TABLE _entity (\r\n                    PK_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n                    name TEXT NOT NULL,\r\n                    iGdtSeqNum INT DEFAULT 0,\r\n                    FK_parent_id INTEGER REFERENCES _entity(PK_id),\r\n                    FK_gdf INTEGER NOT NULL REFERENCES _gdf(PK_id),\r\n                    FK_gdt INTEGER NOT NULL REFERENCES _gdt(PK_id),\r\n                    _gdt_linenum INT DEFAULT 0,\r\n                    bExport INT DEFAULT 0);\r\n                 CREATE        INDEX IX_entityName   ON _entity(name,fk_gdf);\r\n                 CREATE        INDEX IX_entityParent ON _entity(FK_parent_id);\r\n                 CREATE        INDEX IX_entityGdf ON _entity(FK_gdf);\r\n                 CREATE        INDEX IX_entityGdt ON _entity(FK_gdt);";  
				db.Cmd.ExecuteNonQuery();  
			}  
			SQLiteCommand sqliteCommand = new SQLiteCommand(db.Conn);  
			sqliteCommand.CommandText = string.Format("INSERT INTO _meta (_name,_type,_key,_min,_max,_default,_enums,_index) VALUES (@_name,@_type,@_key,@_min,@_max,@_default,@_enums,@_index)", new object[0]);  
			sqliteCommand.Parameters.Add(new SQLiteParameter("@_name"));  
			sqliteCommand.Parameters.Add(new SQLiteParameter("@_type"));  
			sqliteCommand.Parameters.Add(new SQLiteParameter("@_key"));  
			sqliteCommand.Parameters.Add(new SQLiteParameter("@_min"));  
			sqliteCommand.Parameters.Add(new SQLiteParameter("@_max"));  
			sqliteCommand.Parameters.Add(new SQLiteParameter("@_default"));  
			sqliteCommand.Parameters.Add(new SQLiteParameter("@_enums"));  
			sqliteCommand.Parameters.Add(new SQLiteParameter("@_index"));  
			foreach (KeyValuePair<string, gdf> keyValuePair in gdf.collection)  
			{  
				bool flag3 = false;  
				bool flag4 = false;  
				long num2 = -1L;  
				db.Cmd.CommandText = string.Format("SELECT md5, PK_id FROM _gdf where name='{0}';", keyValuePair.Key);  
				SQLiteDataReader sqliteDataReader = db.Cmd.ExecuteReader();  
				if (sqliteDataReader.HasRows)  
				{  
					sqliteDataReader.Read();  
					flag4 = (sqliteDataReader.GetString(0) != keyValuePair.Value.md5);  
					num2 = sqliteDataReader.GetInt64(1);  
				}  
				else  
				{  
					flag3 = true;  
				}  
				sqliteDataReader.Close();  
				if (flag4 || flag3 || !flag)  
				{  
					msgLog.Verbose("Rebuilding table {0}", new object[]  
					{  
						keyValuePair.Key  
					});  
					if (flag3)  
					{  
						db.Cmd.CommandText = string.Format("INSERT INTO _gdf (name,md5) VALUES ('{0}','{1}')", keyValuePair.Key, keyValuePair.Value.md5);  
						db.Cmd.ExecuteNonQuery();  
					}  
					else if (flag4)  
					{  
						db.Cmd_GetGDFsGDTs.Parameters["@FK_gdf"].Value = num2;  
						sqliteDataReader = db.Cmd_GetGDFsGDTs.ExecuteReader();  
						while (sqliteDataReader.Read())  
						{  
							gdt.modifiedGDts.Add(sqliteDataReader.GetInt64(0));  
						}  
						sqliteDataReader.Close();  
						db.Cmd.CommandText = string.Format("DELETE FROM _entity WHERE FK_gdf = {0}", num2);  
						db.Cmd.ExecuteNonQuery();  
						db.Cmd.CommandText = string.Format("UPDATE _gdf SET md5='{0}' WHERE name='{1}'", keyValuePair.Value.md5, keyValuePair.Key);  
						db.Cmd.ExecuteNonQuery();  
					}  
					if (flag3 || flag4)  
					{  
						db.Cmd.CommandText = string.Format("DELETE FROM _meta WHERE _name = '{0}'", keyValuePair.Key);  
						db.Cmd.ExecuteNonQuery();  
						foreach (KeyValuePair<string, gdfVariable> keyValuePair2 in keyValuePair.Value.vars)  
						{  
							string value = "";  
							string value2 = "";  
							string text = "";  
							string value3 = "";  
							string value4 = "string";  
							IgdfType typeInfo = keyValuePair2.Value.typeInfo;  
							gdfFloat gdfFloat = typeInfo as gdfFloat;  
							gdfEnum gdfEnum = typeInfo as gdfEnum;  
							gdfInt gdfInt = typeInfo as gdfInt;  
							gdfColor gdfColor = typeInfo as gdfColor;  
							gdfString gdfString = typeInfo as gdfString;  
							text = keyValuePair2.Value.typeInfo.DatumDefault.s;  
							if (gdfFloat != null)  
							{  
								value4 = "float";  
								value = gdfFloat.minValue.d.ToString();  
								value2 = gdfFloat.maxValue.d.ToString();  
								if (!text.Contains("."))  
								{  
									text += ".0";  
								}  
							}  
							else if (gdfInt != null)  
							{  
								value4 = "int";  
								value = gdfInt.minValue.i.ToString();  
								value2 = gdfInt.maxValue.i.ToString();  
							}  
							else if (gdfString != null)  
							{  
								value4 = "string";  
							}  
							else if (gdfColor != null)  
							{  
								value4 = "color";  
							}  
							else if (gdfEnum != null)  
							{  
								StringBuilder stringBuilder2 = new StringBuilder(4096);  
								bool flag5 = true;  
								value4 = "enum";  
								foreach (List<string> list in gdfEnum.enumList)  
								{  
									if (flag5)  
									{  
										flag5 = false;  
									}  
									else  
									{  
										stringBuilder2.Append('|');  
									}  
									string text2 = list[0];  
									stringBuilder2.Append(list[0]);  
								}  
								value3 = stringBuilder2.ToString();  
							}  
							sqliteCommand.Parameters["@_name"].Value = keyValuePair.Key;  
							sqliteCommand.Parameters["@_type"].Value = value4;  
							sqliteCommand.Parameters["@_key"].Value = keyValuePair2.Key;  
							sqliteCommand.Parameters["@_min"].Value = value;  
							sqliteCommand.Parameters["@_max"].Value = value2;  
							sqliteCommand.Parameters["@_default"].Value = text;  
							sqliteCommand.Parameters["@_enums"].Value = value3;  
							sqliteCommand.Parameters["@_index"].Value = keyValuePair2.Value.sortedIndex;  
							sqliteCommand.ExecuteNonQuery();  
						}  
					}  
					db.Cmd.CommandText = string.Format("DROP TABLE IF EXISTS '{0}';", keyValuePair.Key);  
					db.Cmd.ExecuteNonQuery();  
					StringBuilder stringBuilder3 = new StringBuilder(string.Format("CREATE TABLE {0} (PK_id INTEGER NOT NULL PRIMARY KEY, _precalc_md5 TEXT NOT NULL, _name TEXT NOT NULL, _derived_bits BLOB", keyValuePair.Key));  
					List<string> list2 = new List<string>();  
					foreach (gdfVariable gdfVariable in keyValuePair.Value.vars.Values)  
					{  
						list2.Add(gdfVariable.identifier);  
					}  
					list2.Sort();  
					foreach (string key in list2)  
					{  
						gdfVariable gdfVariable2 = keyValuePair.Value.vars[key];  
						string sqlcolumnDef = gdfVariable2.SQLColumnDef;  
						if (sqlcolumnDef != null)  
						{  
							stringBuilder3.Append(',');  
							stringBuilder3.Append(sqlcolumnDef);  
						}  
					}  
					stringBuilder3.Append(");");  
					stringBuilder3.Append(string.Format("CREATE INDEX IX_{0}_NameMd5 ON {0} (_name,_precalc_md5);", keyValuePair.Key));  
					db.Cmd.CommandText = stringBuilder3.ToString();  
					db.Cmd.ExecuteNonQuery();  
				}  
			}  
			if (!flag)  
			{  
				db.Cmd.CommandText = "PRAGMA user_version=" + db.currentVersion + ";";  
				db.Cmd.ExecuteNonQuery();  
			}  
			return true;  
		}  
  
		// Token: 0x06000043 RID: 67 RVA: 0x000035F0 File Offset: 0x000017F0  
		private static void UpdateEventHandler(object sender, UpdateEventArgs e)  
		{  
			db.updateCount++;  
		}  
  
		// Token: 0x06000044 RID: 68 RVA: 0x00003600 File Offset: 0x00001800  
		public static void ValidateDB()  
		{  
			db.Cmd.CommandText = "\r\nSELECT \r\n  _gdt.name            AS gdt_file, \r\n  _entity._gdt_linenum AS gdt_line, \r\n  _gdf.name            AS asset_type, \r\n  _entity.name         AS asset_name\r\nFROM (\r\n  SELECT \r\n    _entity.name, \r\n    _entity.fk_gdf \r\n  FROM _entity \r\n  GROUP BY _entity.name,_entity.fk_gdf \r\n  HAVING COUNT(_entity.name)>1 \r\n) AS _duplicates \r\nJOIN _entity ON ( _duplicates.fk_gdf = _entity.fk_gdf AND _duplicates.name = _entity.name )\r\nJOIN _gdf    ON ( _entity.fk_gdf = _gdf.pk_id )\r\nJOIN _gdt    ON ( _entity.fk_gdt = _gdt.pk_id )\r\nORDER BY asset_type, asset_name, gdt_file, gdt_line\r\n";  
			HashSet<string> hashSet = new HashSet<string>();  
			SQLiteDataReader sqliteDataReader = db.Cmd.ExecuteReader();  
			while (sqliteDataReader.Read())  
			{  
				msgLog.Error(string.Format("ERROR: Duplicate '{2}' asset '{3}' found in {0}:{1}", new object[]  
				{  
					Path.Combine(Program.TA_GAME_PATH, sqliteDataReader.GetString(0)),  
					sqliteDataReader.GetValue(1),  
					sqliteDataReader.GetValue(2),  
					sqliteDataReader.GetValue(3)  
				}));  
				hashSet.Add(sqliteDataReader.GetString(0));  
			}  
			sqliteDataReader.Close();  
			if (hashSet.Count > 0)  
			{  
				StringBuilder stringBuilder = new StringBuilder();  
				bool flag = false;  
				stringBuilder.Append(string.Format("UPDATE _gdt SET timestamp = {0} WHERE _gdt.name IN (", DateTime.FromFileTime(0L).ToBinary()));  
				foreach (string value in hashSet)  
				{  
					if (flag)  
					{  
						stringBuilder.Append(',');  
					}  
					flag = true;  
					stringBuilder.Append('"');  
					stringBuilder.Append(value);  
					stringBuilder.Append('"');  
				}  
				stringBuilder.Append(')');  
				db.Cmd.CommandText = stringBuilder.ToString();  
				int num = db.Cmd.ExecuteNonQuery();  
				if (num != hashSet.Count)  
				{  
					msgLog.Error(string.Format("ERROR: Invalidated only {0} out of {1} .gdts", num, hashSet.Count));  
				}  
			}  
		}  
  
		// Token: 0x06000045 RID: 69 RVA: 0x0000378C File Offset: 0x0000198C  
		public static void CloseDB()  
		{  
			db.ValidateDB();  
			db.Trans = null;  
			if (db.IsOpen)  
			{  
				db.Conn.Close();  
			}  
			db.Conn = null;  
			if (db.updateCount > 0)  
			{  
				File.SetLastWriteTimeUtc(db.Filename, DateTime.UtcNow);  
			}  
		}  
  
		// Token: 0x06000046 RID: 70 RVA: 0x000037C7 File Offset: 0x000019C7  
		public static void CommitTransaction()  
		{  
			if (db.Trans != null && db.IsOpen)  
			{  
				db.Trans.Commit();  
			}  
		}  
  
		// Token: 0x06000047 RID: 71 RVA: 0x000037E4 File Offset: 0x000019E4  
		public static void CreateTriggers()  
		{  
			foreach (gdf gdf in gdf.collection.Values)  
			{  
				gdf.BuildTriggersSQL(db.Conn);  
			}  
		}  
  
		// Token: 0x06000048 RID: 72 RVA: 0x00003840 File Offset: 0x00001A40  
		public static void DropTriggers()  
		{  
			StringBuilder stringBuilder = new StringBuilder();  
			db.Cmd.CommandText = "SELECT name FROM sqlite_master WHERE type = 'trigger';";  
			SQLiteDataReader sqliteDataReader = db.Cmd.ExecuteReader();  
			if (sqliteDataReader.HasRows)  
			{  
				while (sqliteDataReader.Read())  
				{  
					stringBuilder.AppendFormat("DROP TRIGGER {0};", sqliteDataReader.GetString(0));  
				}  
			}  
			sqliteDataReader.Close();  
			db.Cmd.CommandText = stringBuilder.ToString();  
			db.Cmd.ExecuteNonQuery();  
		}  
  
		// Token: 0x1700001E RID: 30  
		// (get) Token: 0x06000049 RID: 73 RVA: 0x000038B3 File Offset: 0x00001AB3  
		public static bool IsOpen  
		{  
			get  
			{  
				return db.Conn != null;  
			}  
		}  
  
		// Token: 0x1700001F RID: 31  
		// (get) Token: 0x0600004A RID: 74 RVA: 0x000038C0 File Offset: 0x00001AC0  
		public static string Filename  
		{  
			get  
			{  
				return Path.Combine(Program.TA_TOOLS_PATH, "gdtDB\\gdt.db");  
			}  
		}  
  
		// Token: 0x0400000D RID: 13  
		public static int currentVersion = 42;  
  
		// Token: 0x0400000E RID: 14  
		public static int updateCount = 0;  
  
		// Token: 0x0400000F RID: 15  
		public static SQLiteConnection Conn = null;  
  
		// Token: 0x04000010 RID: 16  
		public static SQLiteCommand Cmd = null;  
  
		// Token: 0x04000011 RID: 17  
		public static SQLiteCommand Cmd_GetGDF = null;  
  
		// Token: 0x04000012 RID: 18  
		public static SQLiteCommand Cmd_GetGDT = null;  
  
		// Token: 0x04000013 RID: 19  
		public static SQLiteCommand Cmd_GetGDT_name = null;  
  
		// Token: 0x04000014 RID: 20  
		public static SQLiteCommand Cmd_GetGDT_time = null;  
  
		// Token: 0x04000015 RID: 21  
		public static SQLiteCommand Cmd_GetEntityId = null;  
  
		// Token: 0x04000016 RID: 22  
		public static SQLiteCommand Cmd_GetEntityParent = null;  
  
		// Token: 0x04000017 RID: 23  
		public static SQLiteCommand Cmd_GetEntityName = null;  
  
		// Token: 0x04000018 RID: 24  
		public static SQLiteCommand Cmd_GetIdEntityGDF = null;  
  
		// Token: 0x04000019 RID: 25  
		public static SQLiteCommand Cmd_GetNamedEntityGDF = null;  
  
		// Token: 0x0400001A RID: 26  
		public static SQLiteCommand Cmd_GetEntityGDT = null;  
  
		// Token: 0x0400001B RID: 27  
		public static SQLiteCommand Cmd_GetEntityIDsGDT = null;  
  
		// Token: 0x0400001C RID: 28  
		public static SQLiteCommand Cmd_GetEntityForSave = null;  
  
		// Token: 0x0400001D RID: 29  
		public static SQLiteCommand Cmd_CreateGDT = null;  
  
		// Token: 0x0400001E RID: 30  
		public static SQLiteCommand Cmd_CreateEntity = null;  
  
		// Token: 0x0400001F RID: 31  
		public static SQLiteCommand Cmd_UpdateGDT = null;  
  
		// Token: 0x04000020 RID: 32  
		public static SQLiteCommand Cmd_UpdateEntity = null;  
  
		// Token: 0x04000021 RID: 33  
		public static SQLiteCommand Cmd_GetGDFsGDTs = null;  
  
		// Token: 0x04000022 RID: 34  
		public static SQLiteCommand Cmd_MarkExportEntityByName = null;  
  
		// Token: 0x04000023 RID: 35  
		public static SQLiteCommand Cmd_GetEntityForExport = null;  
  
		// Token: 0x04000024 RID: 36  
		public static SQLiteCommand Cmd_GetXAnimForExportByID = null;  
  
		// Token: 0x04000025 RID: 37  
		public static SQLiteCommand Cmd_GetXModelForExportByID = null;  
  
		// Token: 0x04000026 RID: 38  
		public static SQLiteCommand Cmd_GetMaterialForExportByID = null;  
  
		// Token: 0x04000027 RID: 39  
		public static db.OpenDBOpt openedStatus = db.OpenDBOpt.Undefined;  
  
		// Token: 0x04000028 RID: 40  
		private static SQLiteTransaction Trans = null;  
  
		// Token: 0x02000009 RID: 9  
		public enum OpenDBOpt  
		{  
			// Token: 0x0400002A RID: 42  
			Rebuild,  
			// Token: 0x0400002B RID: 43  
			Update,  
			// Token: 0x0400002C RID: 44  
			NonUpdate,  
			// Token: 0x0400002D RID: 45  
			Undefined  
		}  
	}  
}  
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
11,610 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,481 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rajanikant Hawaldar 86 Reputation points
    2022-10-19T12:57:22.133+00:00

    In ValidateDB() before execute db.Cmd.ExecuteReader(); line of code, check if connection obj is null initial it and open connection


  2. Zhanglong Wu-MSFT 256 Reputation points Microsoft Vendor
    2022-10-26T06:23:28.007+00:00

    @mion shion ,

    As RajanikantHawaldar-9680 mentioned, please open connection before access database. like this:

    if(db.Conn ==null)  
    {  
    db.Conn = new SQLiteConnection("data source=" + filename);  
    db.Conn.Open();  
    SQLiteDataReader sqliteDataReader = db.Cmd.ExecuteReader();  
    }  
    

    Best regards,
    Zhanglong

    0 comments No comments