/// <summary>
        /// Releases memory and restores the GameConnectHandler to its default state.
        /// </summary>
        internal static void Reset()
        {
            ReleaseMappedMemory();
            rawData = null;
            gameConnectionWorker = null;

            gameIsAlive           = false;
            lastSequenceNumber    = 0;
            GameConnected         = false;
            GameConnectionPending = false;
            Telemetry             = null;

            if (logDatabase != null)
            {
                logDatabase.Dispose();
                logDatabase = null;
            }

            MainWindow window = (MainWindow)Application.Current.MainWindow;

            if (window != null)
            {
                window.gameConnectionToggle.Content   = "Connect";
                window.gameConnectionToggle.IsEnabled = true;
                window.gameConnectedStoplight.Fill    = (Brush)Application.Current.Resources["redStoplight"];
                window.SequenceNumberLabel.Content    = "0 (Not Connected)";
            }
        }
Example #2
0
        public void DeleteDataFiles()
        {
            if (_db != null)
            {
                _streams = null;
                _db.Dispose();
            }

            // data file
            if (File.Exists(_options.ConnectionString))
            {
                File.Delete(_options.ConnectionString);
            }

            // log file
            var logFileName = Path.Combine
                              (
                Path.GetDirectoryName(_options.ConnectionString),
                Path.ChangeExtension
                (
                    Path.GetFileNameWithoutExtension(_options.ConnectionString) + "-log",
                    Path.GetExtension(_options.ConnectionString)
                )
                              );

            if (File.Exists(logFileName))
            {
                File.Delete(logFileName);
            }
        }
Example #3
0
        public Task <byte[]> BackupDatabase()
        {
            // Find database file to make backup
            if (!File.Exists(DatabaseFileName))
            {
                return(null);
            }

            try
            {
                // Commit all changes and dispose database instance to free database file lock
                _liteDatabase.Checkpoint();
                _liteDatabase.Dispose();

                // Return database content
                return(Task.FromResult(File.ReadAllBytes(DatabaseFileName)));
            }
            catch (Exception ex)
            {
                return(null);
            }
            finally
            {
                InitLiteDb();
            }
        }
Example #4
0
 public void EndDBAccess()
 {
     _logger.Log("closing db....");
     if (!IsDBOpen)
     {
         throw new InvalidOperationException("theres currently no db opened");
     }
     _db.Dispose();
     _db = null;
 }
 public List <Movie> GetMovies()
 {
     try
     {
         return(new List <Movie>(this.collection.FindAll()));
     }
     finally
     {
         db.Dispose();
     }
 }
        public override void Shutdown()
        {
            base.Shutdown();

            if (_dbRunningValues != null)
            {
                _dbRunningValues.Checkpoint();
                _dbRunningValues.Dispose();
                _dbRunningValues = null;
            }
        }
Example #7
0
        private void Application_Exit(object sender, ExitEventArgs e)
        {
            Config.Save();

            m_database.Shrink();
            m_database.Dispose();
        }
Example #8
0
        // Api stuff commeneted out as it's not needed currently

        /*public static T GetAPIResponse<T>(string targetEndpoint)
         * {
         *  try
         *  {
         *      using (var webClient = new WebClient())
         *      {
         *          string jsonString = webClient.DownloadString("https://localhost:3080/api/" + targetEndpoint);
         *          JsonWrapper jsonObject = JsonConvert.DeserializeObject<JsonWrapper>(jsonString);
         *          T result = JsonConvert.DeserializeObject<T>(jsonObject.Result.ToString());
         *          return result;
         *      }
         *  }
         *
         *  catch
         *  {
         *      return default(T);
         *  }
         * }
         *
         * public static Dictionary<Base, decimal> GetSellPoint(string endpoint, string item)
         * {
         *  List<Market> markets = GetAPIResponse<List<Market>>(endpoint);
         *  Dictionary<string, decimal> baseList = new Dictionary<string, decimal>();
         *  foreach (var i in markets)
         *  {
         *      if (i.Good.ContainsKey(item))
         *          baseList.Add(i.Base, i.Good.FirstOrDefault(x => x.Key == item).Value);
         *  }
         *
         *  Dictionary<Base, decimal> bases = new Dictionary<Base, decimal>();
         *  foreach (var s in baseList)
         *  {
         *      Base b = GetAPIResponse<Base>("base/" + s.Key);
         *      bases[b] = s.Value;
         *  }
         *
         *  return bases;
         * }*/

        public static List <T> GetDatabaseCollection <T>(string collectionName, ref Errors error)
        {
            if (!CheckDatabase())
            {
                error = Errors.DatabaseNotFound;
                return(default(List <T>));
            }

            using (var db = new LiteDatabase(GetDatabase()))
            {
                var collection = db.GetCollection <T>(collectionName);
                if (collection.Count() == 0)
                {
                    error = Errors.InvalidDatabaseStructure;
                    return(default(List <T>));
                }

                var list = new List <T>();
                foreach (var i in collection.FindAll())
                {
                    list.Add(i);
                }
                db.Dispose();
                error = Errors.Null;
                return(list);
            }
        }
Example #9
0
 public void Shutdown()
 {
     Database.Dispose();
     LODsDatabase.Dispose();
     EntsDatabase.Dispose();
     TopsDatabase.Dispose();
 }
Example #10
0
        internal static void Init()
        {
            var dbPath = Path.Combine(Environment.CurrentDirectory, "DreadBot.db");

            if (!System.IO.File.Exists(dbPath))
            {
                Console.WriteLine("Database at path \"" + dbPath + "\" not found, starting a new instance");
                newInstance = true;
            }
            db = new LiteDatabase(@"DreadBot.db");

            DreadBotCol = db.GetCollection <BotConfig>("dreadbot");

            if (newInstance)
            {
                Configs.Welcome();
                DreadBotCol.Insert(Configs.RunningConfig);
            }
            else
            {
                try { Configs.RunningConfig = DreadBotCol.FindAll().First <BotConfig>(); }
                catch {
                    db.Dispose();
                    System.IO.File.Delete(dbPath);
                    db          = new LiteDatabase(@"DreadBot.db");
                    DreadBotCol = db.GetCollection <BotConfig>("dreadbot");
                    newInstance = true;
                    Configs.Welcome();
                    DreadBotCol.Insert(Configs.RunningConfig);
                }
            }
            Configs.RunningConfig.LastLaunch = Utilities.EpochTime();
            SaveConfig();
        }
Example #11
0
        public static void Close()
        {
            DB.Commit();

            DB.Dispose();
            IsOpened = false;
        }
Example #12
0
        protected override void EndProcessing()
        {
            resolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(Path);

            if (File.Exists(resolvedPath))
            {
                WriteWarning(string.Format("A LiteDB Database already exists at Path:\t['{0}']", resolvedPath));
            }
            else
            {
                ConnectionString connbuilder = new ConnectionString();
                connbuilder.Filename = resolvedPath;
                if (Credential != null)
                {
                    connbuilder.Password = Credential.GetNetworkCredential().Password;
                }

                LiteDatabase db = new LiteDatabase(connbuilder);
                db.Dispose();
                //verify that the database was created
                if (File.Exists(resolvedPath))
                {
                    WriteVerbose(string.Format("Sucessfully created a LiteDB Database at Path:\t['{0}']", resolvedPath));
                }
                else
                {
                    throw new Exception(string.Format("Could not create LiteDb database at Path:\t['{0}']", resolvedPath));
                }
            }
        }
Example #13
0
 public static bool RefreshLiveLdbBodyModelProductStatistics(string _Type)
 {
     try
     {
         //LogManager.SetCommonLog("RefreshLdbProductStatistics_ starting..." );
         // generate new statistic
         List <BodyModelProductStatistics> lstNewPS = StatisticsActs.GetLiveBodyModelProdStatistics(_Type);
         if ((lstNewPS != null) && (lstNewPS.Count != 0))
         {
             // get instanse of ldb
             LiteDatabase db = new LiteDatabase(ldbConfig.ldbConnectionString);
             // get old ldb ps lst
             LiteCollection <BodyModelProductStatistics> dbPS = db.GetCollection <BodyModelProductStatistics>("BodyModelProductStatistics");
             // delete old lst
             dbPS.Delete(Query.EQ("DateIntervalType", _Type));
             // insetr new lst
             dbPS.Insert(lstNewPS);
             //LogManager.SetCommonLog("RefreshLdbProductStatistics_ insert successfully" + lstNewPS.Count);
             db.Dispose();
             return(true);
         }
         return(false);
     }
     catch (Exception ex)
     {
         //DBHelper.LogFile(ex);
         LogManager.SetCommonLog("RefreshLdbBodyModelProductStatistics_" + ex.Message.ToString());
         return(false);
     }
 }
Example #14
0
        public static bool RefreshLdbQCHStatistics()
        {
            try
            {
                //LogManager.SetCommonLog("RefreshLdbQCStatistics starting... just today="+ JustTodayStatistics);
                // generate new statistic
                List <QCHStatistics> lstNewPS = StatisticsActs.GetHQCStatistics();
                if (lstNewPS != null)
                {
                    // get instanse of ldb
                    LiteDatabase db = new LiteDatabase(ldbConfig.ldbQCStatisticsConnectionString);

                    // get old ldb ps lst
                    LiteCollection <QCHStatistics> dbPS = db.GetCollection <QCHStatistics>("QCHStatistics");
                    // delete old lst
                    dbPS.Delete(Query.All());
                    // insetr new lst
                    dbPS.Insert(lstNewPS);
                    //LogManager.SetCommonLog("RefreshLdbQCStatistics insert successfully" + lstNewPS.Count);
                    db.Dispose();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LogManager.SetCommonLog("RefreshLdbQCHStatistics_err:" + ex.Message.ToString());
                return(false);
            }
        }
Example #15
0
        public string GetMessageEvent(CommandSource source)
        {
            var message = string.Empty;

            var name = source.Message.Split(" ");

            if (name[1] == "winner")
            {
                var winner = DrawWinner();

                message = $"Il vincitore del giveaway è: {winner}";
                return(message);
            }

            var giveaway = new Giveaway();

            giveaway.Name = name[1];

            var settings = new EngineSettings {
                Filename = "giveaway.db"
            };
            var db      = new LiteEngine(settings);
            var _liteDb = new LiteDatabase(db);

            _liteDb.GetCollection <Giveaway>().Insert(giveaway);
            _liteDb.Checkpoint();

            _liteDb.Dispose();

            message = $"{source.User} hai creato il giveaway: {name[1]}";

            return(message);
        }
Example #16
0
    //加载模型
    public void LoadModels(string url, string password, string sceneName)
    {
        string secUrl = string.Empty;

        url    = url.Replace("\\", "/");
        secUrl = url.Insert(url.LastIndexOf("/") + 1, "vesal");
        vesal_log.vesal_write_log("开始获取加密文件:" + DateTime.Now.TimeOfDay.ToString());
        ConnectionString connect1 = new ConnectionString();

        connect1.Filename  = secUrl;
        connect1.LimitSize = 10000000000;
        connect1.Password  = password;
        connect1.Journal   = false;
        connect1.Mode      = LiteDB.FileMode.ReadOnly;
        byte[] streams1, streams2;
        using (var db = new LiteDatabase(connect1))
        {
            var stream = db.FileStorage.OpenRead(sceneName + ".assetbundle");
            streams1 = StreamToBytes(stream);
            stream.Dispose();
        }
        vesal_log.vesal_write_log("开始获取未加密文件:" + DateTime.Now.TimeOfDay.ToString());
        ConnectionString connect2 = new ConnectionString();

        connect2.Filename  = url;
        connect2.LimitSize = 10000000000;
        connect2.Journal   = false;
        connect2.Mode      = LiteDB.FileMode.ReadOnly;
        using (var db = new LiteDatabase(connect2))
        {
            var stream = db.FileStorage.OpenRead(sceneName + ".assetbundle");
            streams2 = StreamToBytes(stream);
            stream.Dispose();
            //流组合
            byte[] streams = new byte[streams1.Length + streams2.Length];
            streams1.CopyTo(streams, 0);
            streams2.CopyTo(streams, streams1.Length);
            //加载ab
            AssetBundle curBundleObj = AssetBundle.LoadFromMemory(streams);
            CurrentObj = (GameObject)curBundleObj.LoadAsset(sceneName, typeof(GameObject));
            Debug.Log("animationGameObject = Instantiate(CurrentObj)");
            animationGameObject = Instantiate(CurrentObj);
            //获取动画
            anim = animationGameObject.GetComponent <Animation>()[abObjName];
            anim.normalizedTime = 0;
            Vector3 tmpV = animationGameObject.transform.rotation.eulerAngles;
            animationGameObject.transform.rotation = Quaternion.Euler(tmpV.x, tmpV.y - 180f, tmpV.z);
            if (PPTGlobal.PPTEnv == PPTGlobal.PPTEnvironment.plugin)
            {
                animationGameObject.SetActive(true);
            }
            else
            {
                animationGameObject.SetActive(false);
            }
            vesal_log.vesal_write_log("模型加载完成:" + DateTime.Now.TimeOfDay.ToString());
            curBundleObj.Unload(false);
            db.Dispose();
        }
    }
Example #17
0
 protected virtual void _dispose(bool disposing)
 {
     if (disposing)
     {
         dbHandle.Dispose();
     }
 }
Example #18
0
 public void Dispose()
 {
     if (_db != null)
     {
         _db.Dispose();
     }
 }
Example #19
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         db?.Dispose();
     }
 }
Example #20
0
        private void Disconnect()
        {
            btnConnect.Text = "Connect";

            this.UIState(false);

            foreach (var tab in tabSql.TabPages.Cast <TabPage>().Where(x => x.Name != "+").ToArray())
            {
                var task = tab.Tag as TaskData;
                task.ThreadRunning = false;
                task.WaitHandle.Set();
            }

            // clear all tabs and controls
            tabSql.TabPages.Clear();

            txtSql.Clear();
            grdResult.Clear();
            txtResult.Clear();
            txtParameters.Clear();

            tvwDatabase.Nodes.Clear();
            tvwDatabase.Focus();


            _db?.Dispose();
            _db = null;
        }
 public void TareDown()
 {
     _client.Dispose();
     _server.Dispose();
     _memoryStream.Dispose();
     _db.Dispose();
 }
Example #22
0
 public void Dispose()
 {
     if (!nodb)
     {
         db.Dispose();
     }
 }
Example #23
0
        private void ReportThread()
        {
            this.Timer.Start();

            var output = new StringBuilder();

            while (this.Timer.Elapsed < this.Duration && _running)
            {
                Thread.Sleep(Math.Min(1000, (int)this.Duration.Subtract(this.Timer.Elapsed).TotalMilliseconds));

                this.ReportPrint(output);

                Console.Clear();
                Console.WriteLine(output.ToString());
            }

            this.StopRunning();

            this.Timer.Stop();

            _db.Dispose();

            this.ReportPrint(output);
            this.ReportSummary(output);

            Console.Clear();
            Console.WriteLine(output.ToString());

            File.AppendAllText(_file.Output, output.ToString());
        }
Example #24
0
 public void Dispose()
 {
     if (_database != null)
     {
         _database.Dispose();
     }
 }
Example #25
0
        private static void Upgrade()
        {
            database.Dispose();
            dbMemoryStream.Seek(0, SeekOrigin.Begin);
            using (var tempFile = File.Create("upgrade.db"))
            {
                dbMemoryStream.CopyTo(tempFile);
            }

            var tempDb = new LiteDatabase("filename=upgrade.db;upgrade=true");

            tempDb.Dispose();

            using (var upgradedDb = File.Open("upgrade.db", System.IO.FileMode.Open))
            {
                using (FileStream outFile = File.Open(Resources.DB_NAME, System.IO.FileMode.OpenOrCreate))
                {
                    using (GZipStream gZipStream = new GZipStream(outFile, CompressionMode.Compress))
                    {
                        upgradedDb.CopyTo(gZipStream);
                    }
                }
            }

            File.Delete("upgrade.db");
            File.Delete("upgrade-bkp.db");
            Open();
        }
Example #26
0
        public override void Run(Span<string> args)
        {
            var dbFolder = Path.GetDirectoryName(DbPath) ?? throw new InvalidOperationException("Unable to determine data folder path");
            var backupDataFile = Path.Combine(dbFolder, $"data-{DateTime.Now:yyyyMMdd-HHmmss}.litedb");
            File.Copy(DbPath, backupDataFile);

            using var originalDb = new LiteDatabase(new ConnectionString
            {
                Filename = DbPath,
                Upgrade = true,
            });
            var upgradeDbPath = $"{DbPath}.new";
            if (File.Exists(upgradeDbPath))
                File.Delete(upgradeDbPath);
            using var newdb = new LiteDatabase(new ConnectionString
            {
                Filename = upgradeDbPath,
            });

            var storage = new Storage(newdb);
            storage.Import(originalDb);
            originalDb.Dispose();
            newdb.Dispose();
            File.Delete(DbPath);
            File.Move(upgradeDbPath, DbPath);
        }
Example #27
0
 public virtual void Dispose()
 {
     if (db != null)
     {
         db.Dispose();
     }
 }
 public void Dispose()
 {
     _cache.Clear();
     _liteDatabase?.Dispose();
     _liteDatabase = null;
     GC.SuppressFinalize(this);
 }
Example #29
0
 public static void Close()
 {
     if (db != null)
     {
         db.Dispose();
     }
 }
Example #30
0
        public void Test_Transaction_ReleaseWhenFailToStart()
        {
            var blockingStream = new BlockingStream();
            var db             = new LiteDatabase(blockingStream)
            {
                Timeout = TimeSpan.FromSeconds(1)
            };
            Thread lockerThread = null;

            try
            {
                lockerThread = new Thread(() =>
                {
                    db.GetCollection <Person>().Insert(new Person());
                    blockingStream.ShouldBlock = true;
                    db.Checkpoint();
                    db.Dispose();
                });
                lockerThread.Start();
                blockingStream.Blocked.WaitOne(1000).Should().BeTrue();
                Assert.Throws <LiteException>(() => db.GetCollection <Person>().Insert(new Person())).Message.Should().Contain("timeout");
                Assert.Throws <LiteException>(() => db.GetCollection <Person>().Insert(new Person())).Message.Should().Contain("timeout");
            }
            finally
            {
                blockingStream.ShouldUnblock.Set();
                lockerThread?.Join();
            }
        }
Example #31
0
        public override void Execute(ref LiteDatabase db, StringScanner s, Display display, InputCommand input)
        {
            if (db == null) throw LiteException.NoDatabase();

            db.Dispose();

            db = null;
        }
Example #32
0
        public override void Execute(ref LiteDatabase db, StringScanner s, Display display, InputCommand input)
        {
            var filename = s.Scan(@".+");

            if (db != null)
            {
                db.Dispose();
            }

            db = new LiteDatabase(filename);
        }
        public void Concurrent_Test()
        {
            var dbname = DB.RandomFilename();
            var N = 300; // interate counter

            var a = new LiteDatabase(dbname);
            var b = new LiteDatabase(dbname);
            var c = new LiteDatabase(dbname);
            var d = new LiteDatabase(dbname);

            // task A -> insert N documents
            var ta = Task.Factory.StartNew(() =>
            {
                var col = a.GetCollection("col1");
                col.EnsureIndex("name");

                for (var i = 1; i <= N; i++)
                {
                    col.Insert(this.CreateDoc(i, "-insert-"));
                }
            });

            // task B -> update N documents
            var tb = Task.Factory.StartNew(() =>
            {
                var col = b.GetCollection("col1");
                var i = 1;

                while (i <= N)
                {
                    var doc = this.CreateDoc(i, "-update-");
                    doc["date"] = new DateTime(2015, 1, 1);
                    doc["desc"] = null;

                    var success = col.Update(doc);
                    if (success) i++;
                }
            });

            // tasK C -> delete N-1 documents (keep only _id = 1)
            var tc = Task.Factory.StartNew(() =>
            {
                var col = c.GetCollection("col1");
                var i = 2;

                while (i <= N)
                {
                    // delete document after update
                    if (col.Exists(Query.And(Query.EQ("_id", i), Query.EQ("name", "-update-"))))
                    {
                        var success = col.Delete(i);
                        if (success) i++;
                    }
                }
            });

            // task D -> upload 40 files + delete 20
            var td = Task.Factory.StartNew(() =>
            {
                for (var i = 1; i <= 40; i++)
                {
                    d.FileStorage.Upload("f" + i, this.CreateMemoryFile(20000));
                }
                for (var i = 1; i <= 20; i++)
                {
                    d.FileStorage.Delete("f" + i);
                }
            });

            // Now, test data
            Task.WaitAll(ta, tb, tc, td);

            a.Dispose();
            b.Dispose();
            c.Dispose();
            d.Dispose();

            using (var db = new LiteDatabase(dbname))
            {
                var col = db.GetCollection("col1");
                var doc = col.FindById(1);

                Assert.AreEqual("-update-", doc["name"].AsString);
                Assert.AreEqual(new DateTime(2015, 1, 1), doc["date"].AsDateTime);
                Assert.AreEqual(true, doc["desc"].IsNull);
                Assert.AreEqual(col.Count(), 1);

                Assert.AreEqual(1, col.Count());
                Assert.AreEqual(20, db.FileStorage.FindAll().Count());
            }
        }