Example #1
0
        public void CreateDB()
        {
            Directory.CreateDirectory(DirectoryConstants.DatabaseDirectory);

            using (var db = new LiteDatabase(DirectoryConstants.DatabaseString))
            {
                if (db.CollectionExists(m_CreaturesCollectionName))
                {
                    db.DropCollection(m_CreaturesCollectionName);
                }
                if (db.CollectionExists(m_SavedCreaturesCollectionName))
                {
                    db.DropCollection(m_SavedCreaturesCollectionName);
                }

                var collection = db.GetCollection <Creature>(m_CreaturesCollectionName);
                CreateCreatures(collection);

                // Setup indexes
                // May not need if not querying to filter
                // These caused a 3GB spike in memory usage
                //collection.EnsureIndex(x => x.Rank);
                //collection.EnsureIndex(x => x.Abilities);
            }
        }
Example #2
0
 //Use this with caution!
 //Kind of only suitable on reboot of the server
 public static void clearActiveUsers()
 {
     if (theDB.CollectionExists(AlbotDBDatatypes.ACTIVEUSERCOLECTION))
     {
         theDB.DropCollection(AlbotDBDatatypes.ACTIVEUSERCOLECTION);
     }
 }
Example #3
0
 public void Delete(string catelog)
 {
     if (!cacheDb.CollectionExists(catelog))
     {
         return;
     }
     cacheDb.DropCollection(catelog);
 }
Example #4
0
        public static T GetFirst <T>(string collectionName) where T : new()
        {
            if (!db.CollectionExists(collectionName))
            {
                return(default(T));
            }

            LiteCollection <T> collection = db.GetCollection <T>(collectionName);

            return(collection.FindOne(Query.All()));
        }
Example #5
0
        public void DropCollection_Test()
        {
            using (var db = new LiteDatabase(DB.Path()))
            {
                Assert.IsFalse(db.CollectionExists("customerCollection"));
                var collection = db.GetCollection <Customer>("customerCollection");

                collection.Insert(new Customer());
                Assert.IsTrue(db.CollectionExists("customerCollection"));

                db.DropCollection("customerCollection");
                Assert.IsFalse(db.CollectionExists("customerCollection"));
            }
        }
        public void DropCollection_Test()
        {
            using (var db = new LiteDatabase(new MemoryStream()))
            {
                Assert.IsFalse(db.CollectionExists("customerCollection"));
                var collection = db.GetCollection<Customer>("customerCollection");

                collection.Insert(new Customer());
                Assert.IsTrue(db.CollectionExists("customerCollection"));

                db.DropCollection("customerCollection");
                Assert.IsFalse(db.CollectionExists("customerCollection"));
            }
        }
        public static void Initialize()
        {
            using (var db = new LiteDatabase(DatabaseFilePath))
            {
                var customersExist = db.CollectionExists("Customer");
                if (!customersExist)
                {
                    db.GetCollection <Customer>().Insert(InitCustomers);
                }
                else
                {
                    var customers = db.GetCollection <Customer>();
                    foreach (var cust in InitCustomers)
                    {
                        var dbCustomer = customers.FindById(cust.Id);
                        if (dbCustomer != null)
                        {
                            customers.Update(dbCustomer);
                        }
                        else
                        {
                            customers.Insert(cust);
                        }
                    }
                }

                var ordersExists = db.CollectionExists("Order");
                if (!ordersExists)
                {
                    db.GetCollection <Order>().Insert(InitOrders);
                }
                else
                {
                    var orders = db.GetCollection <Order>();
                    foreach (var order in InitOrders)
                    {
                        var dbOrder = orders.FindById(order.Id);
                        if (dbOrder != null)
                        {
                            orders.Update(dbOrder);
                        }
                        else
                        {
                            orders.Insert(order);
                        }
                    }
                }
            }
        }
Example #8
0
        /// <summary>
        /// Create a new Storage wrappper using LiteDB
        /// </summary>
        /// <param name="path">Filename of database file (doesn't need to exist)</param>
        public LiteDBStorage(string path)
        {
            BsonMapper.Global.RegisterAutoId <string>
            (
                isEmpty: (value) => value == null || value.Trim() == "",
                newId: (db, col) => _keyGen.GetAndAdd(1).ToString()
            );

            _db = new LiteDatabase(path);
            if (_db.CollectionExists(COLLECTION_NAME))
            {
                TotalItems = _db.GetCollection <StorageRecord>(COLLECTION_NAME).Count();
            }
            else
            {
                TotalItems = 0;
            }

            var highestId = _db.GetCollection <StorageRecord>(COLLECTION_NAME).FindAll()
                            .OrderByDescending(i => { return(BigInteger.Parse(i.Id)); })
                            .Take(1)
                            .ToList <StorageRecord>();

            if (highestId.Count == 1)
            {
                _keyGen = new IdGenerator(BigInteger.Parse(highestId[0].Id));
            }
            else
            {
                _keyGen = new IdGenerator(BigInteger.Zero);
            }
        }
Example #9
0
 private void DropTable()
 {
     if (_database.CollectionExists(Helper.TABLE_NAME))
     {
         _database.DropCollection(Helper.TABLE_NAME);
     }
 }
Example #10
0
        public void FindLocker_Test()
        {
            Assert.AreEqual(col.Count(), 0);

            // insert data
            Task.Factory.StartNew(InsertData).Wait();

            // test inserted data :: Info = 1
            var data = col.FindOne(o => o.Key == "Test1");

            Assert.IsNotNull(data);
            Assert.AreEqual(1, data.Info);

            // update data :: Info = 77
            Task.Factory.StartNew(UpdateData).Wait();

            // find updated data
            data = col.FindOne(o => o.Key == "Test1");
            Assert.IsNotNull(data);
            Assert.AreEqual(77, data.Info);

            // drop collection
            db.DropCollection("col1");
            Assert.AreEqual(db.CollectionExists("col1"), false);
        }
Example #11
0
        public CounterpartyDbContext(string path)
        {
            Database = new LiteDatabase(path);
            var col = Database.GetCollection <Counterparty>();

            if (!Database.CollectionExists(typeof(Counterparty).Name))
            {
                col.Insert(new Counterparty()
                {
                    Name             = "ПАО СБЕРБАНК",
                    FullName         = "ПУБЛИЧНОЕ АКЦИОНЕРНОЕ ОБЩЕСТВО \"СБЕРБАНК РОССИИ\"",
                    INN              = 7707083893,
                    KPP              = 540602001,
                    CounterpartyType = CounterpartyTypeEnum.LEGAL
                });

                col.Insert(new Counterparty()
                {
                    Name             = "БАЙКАЛЬСКИЙ БАНК ПАО СБЕРБАНК",
                    FullName         = "БАЙКАЛЬСКИЙ БАНК ПАО СБЕРБАНК",
                    INN              = 7707083893,
                    KPP              = 380843001,
                    CounterpartyType = CounterpartyTypeEnum.LEGAL
                });

                col.Insert(new Counterparty()
                {
                    Name             = "ИП Чех Илья Викторович",
                    FullName         = "Индивидуальный предприниматель Чех Илья Викторович",
                    INN              = 784806113663,
                    CounterpartyType = CounterpartyTypeEnum.INDIVIDUAL
                });
            }
        }
Example #12
0
        private void Import_OnClick(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "Файлы БД программы (USD.db)|USD.db|Все файлы БД (*.db)|*.db|Все файлы (*.*)|*.*"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                using (var db = new LiteDatabase(DirectoryHelper.GetDataDirectory() + Settings.Default.LiteDbFileName))
                {
                    using (var db1 = new LiteDatabase(openFileDialog.FileName))
                    {
                        if (!db1.CollectionExists("screenings"))
                        {
                            MessageBox.Show(
                                "Не подходящая база данных. Используйте базу данных, только от этой программы.", "УЗД",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }

                        var origCol = db.GetCollection("screenings");
                        var newCol  = db1.GetCollection("screenings");
                        foreach (var source in newCol.FindAll().ToList())
                        {
                            source["Id"] = null;
                            origCol.Insert(source);
                        }
                    }
                }
                (DataContext as ListViewModel.ListViewModel)?.LoadData();
                MessageBox.Show("Данные успешно импортированны", "УЗД", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
Example #13
0
 public static bool Exists <T>()
 {
     using (var db = new LiteDatabase($"{DatabaseHelper.DatabasePath}/Database.db"))
     {
         return(db.CollectionExists(typeof(T).Name));
     }
 }
Example #14
0
        private bool FindModuleModel(string moduleName, string filePath, out ModuleModel model)
        {
            model = null;

            // We don't cache results here. Module resolution service decides when to call in here
            // and it is responsible of overall management of the loaded Python modules.
            for (var retries = 50; retries > 0; --retries)
            {
                try {
                    // TODO: make combined db rather than per module?
                    var dbPath = FindDatabaseFile(moduleName, filePath);
                    if (string.IsNullOrEmpty(dbPath))
                    {
                        return(false);
                    }

                    using (var db = new LiteDatabase(dbPath)) {
                        if (!db.CollectionExists("modules"))
                        {
                            return(false);
                        }

                        var modules = db.GetCollection <ModuleModel>("modules");
                        model = modules.Find(m => m.Name == moduleName).FirstOrDefault();
                        return(model != null);
                    }
                } catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException)
                {
                    Thread.Sleep(10);
                }
            }
            return(false);
        }
Example #15
0
        public void loadDB(string connStr)
        {
            this.connStr = connStr;
            using (var db = new LiteDatabase(connStr))
            {
                // TODO Если юзер пытается загрузить пустую или испорченную бд
                try
                {
                    if (db.CollectionExists("users"))
                    {
                        MainWindow.db_users = getAllUsers();

                        // Сохраним путь к бд в конфиг, чтобы в следующий раз само открылось
                        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings["db_destination"].Value = connStr;
                        config.Save(ConfigurationSaveMode.Modified);
                        ConfigurationManager.RefreshSection("appSettings");

                        corrupted = false;
                    }
                }
                catch (LiteException)
                {
                    Console.WriteLine(this.ToString() + ": Испорченная база данных");
                    MessageBox.Show("Невозможно загрузить базу данных!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    corrupted = true;
                }
            }
        }
    private IEnumerable <SampleResponse> getDailySample(DateTime Date, LiteDatabase db)
    {
        var collectionName = Date.ToString("yyyyMMdd");

        if (db.CollectionExists(collectionName))
        {
            return(db.GetCollection <SampleResponse>(collectionName).FindAll());
        }

        var response = new List <SampleResponse>();

        var    url  = "https://api.neur.io/v1/samples?sensorId={0}&start={1}&end={2}&granularity=hours&perPage=500";
        String resp =
            (Task.Run(async()
                      => await GetURL(String.Format(url, sensor, Date.ToUniversalTime().ToString("o"), Date.AddDays(1).ToUniversalTime().ToString("o")), null)))
            .Result;

        response.AddRange(JsonConvert.DeserializeObject <SampleResponse[]>(resp));
        if (Date.AddDays(1) < DateTime.Now)
        {
            var collection = db.GetCollection <SampleResponse>(collectionName);
            collection.InsertBulk(response);
        }
        return(response);
    }
Example #17
0
 // Bootstrap the DB
 public static void InitializeDatabase()
 {
     // Insert some service records if they don't exist yet
     if (!DB.CollectionExists("services"))
     {
         var serviceSeeds = Regex.Split(Properties.Resources.SeedServices, "\r\n|\r|\n");
         foreach (string line in serviceSeeds)
         {
             var data = line.Split(',');
             if (data.Length == 2)
             {
                 Service.Collection.Insert(new Service
                 {
                     Name = data[0],
                     Fee  = float.Parse(data[1])
                 });
             }
         }
     }
     // Set up mappings between models here. This ensures that
     // relationships between objects come out of the database intact.
     BsonMapper.Global.Entity <Consultation>()
     .DbRef(x => x.ServiceRecord, "services")
     .DbRef(x => x.MemberRecord, "members")
     .DbRef(x => x.ProviderRecord, "providers");
 }
Example #18
0
 public void CheckIDoID()
 {
     if (!_db.CollectionExists(_STR_INDEX_OF_INDEX))
     {
         UpdateIndexIndex();
     }
 }
Example #19
0
 public static bool Exists <T>()
 {
     using (var db = new LiteDatabase(@"./Datenbank/Datenbank.db"))
     {
         return(db.CollectionExists(typeof(T).Name));
     }
 }
Example #20
0
 /// <summary>
 /// Check database for an existing document
 /// </summary>
 /// <param name="colName">Collection name</param>
 /// <returns></returns>
 private bool CheckIfCollectionExists(string colName)
 {
     using (var db = new LiteDatabase(dbPath))
     {
         return(db.CollectionExists(colName));
     }
 }
Example #21
0
 /// <summary>
 /// Add an example notable to an unitialized database.
 /// /// </summary>
 public void AddInitialExampleNotable()
 {
     if (!db.CollectionExists(nameof(notableCollection)))
     {
         notableCollection.Insert(new Notable(DateTime.Now, "Example Notable Title", "Example Notable Text"));
     }
 }
 public static void DropTableIfExists(this LiteDatabase db, string collectionName)
 {
     if (db.CollectionExists(collectionName))
     {
         db.DropCollection(collectionName);
     }
 }
Example #23
0
        private static void InitializeData()
        {
            try
            {
                using (var db = new LiteDatabase(DATABASE))
                {
                    if (db.CollectionExists(COLLECTION))
                    {
                        db.DropCollection(COLLECTION);
                    }

                    var sites = db.GetCollection <Site>(COLLECTION);

                    sites.Insert(new Site()
                    {
                        Id = 1, Name = "Geeks.ms"
                    });
                    sites.Insert(new Site()
                    {
                        Id = 2, Name = "Microsoft"
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #24
0
        public void Initialise()
        {
            if (hasRun)
            {
                return;
            }
            using (var db = new LiteDatabase(DatabaseDir))
            {
                if (!db.CollectionExists("guilds"))
                {
                    _logMethod.Invoke(new LogMessage(LogSeverity.Error, LogSource, "Guild collection does not exist"));
                    return;
                }

                var guilds = db.GetCollection <GuildObject>("guilds");
                foreach (var guild in _client.Guilds)
                {
                    var dbGuild = guilds.FindOne(x => x.GuildId == guild.Id);
                    _currentTags.Add(guild.Id, dbGuild.Tags);
                    _approvedUsers.Add(guild.Id, dbGuild.ApprovedUsers);
                }
            }

            _logMethod.Invoke(new LogMessage(LogSeverity.Info, LogSource, "Database has been loaded"));
            hasRun = true;
        }
Example #25
0
 /// <summary>
 /// Check if the collection of Class name exists.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public static bool Exists <T>()
 {
     using (var db = new LiteDatabase(ServerSettings.DatabaseLocation + ServerSettings.DatabaseFile))
     {
         return(db.CollectionExists(typeof(T).Name));
     }
 }
Example #26
0
 public void Erase()
 {
     if (Database.CollectionExists(CollectionName))
     {
         Database.DropCollection(CollectionName);
     }
 }
Example #27
0
 /// <summary>
 ///	Load the location-weather code pairs into the database for retrieval.
 /// /// </summary>
 /// <returns></returns>
 public async Task InitializaDatabaseWithWeatherCodesIfAbsentAsync()
 {
     if (!db.CollectionExists(nameof(defaultCollection)))
     {
         var asm   = typeof(Library).GetTypeInfo().Assembly;
         var tasks = asm.GetManifestResourceNames().ToList().Select(z => {
             return(Task.Run(() => {
                 using (Stream rs = asm.GetManifestResourceStream(z)) {
                     using (var sr = new StreamReader(rs)) {
                         var jo = LiteDB.JsonSerializer.Deserialize(sr);
                         weatherCodes = BsonMapper.Global.ToDocument(jo);
                         name = z.Split(".").Reverse().Skip(1).Take(1).First();
                         var doc = new BsonDocument()
                         {
                             [(nameof(name))] = name, [(nameof(weatherCodes))] = weatherCodes
                         };
                         defaultCollection.Insert(doc);
                     }
                 }
             }));
         });
         await Task.WhenAll(tasks);
     }
     return;
 }
Example #28
0
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            int port = 8989;

            //Try and load the port from settings
            using (var db = new LiteDatabase("DataStorage.db"))
            {
                if (db.CollectionExists("Settings"))
                {
                    if (db.GetCollection <Setting>("Settings").Exists(x => x.Key == "System.AdminPort"))
                    {
                        port = db.GetCollection <Setting>("Settings").Find(x => x.Key == "System.AdminPort").First().AsInt();
                    }
                }
            }

            port = GetAvailablePort(port);
            string ListenURL = $"http://+:{port}";

            Console.WriteLine("Starting with URL " + ListenURL);

            return(Host.CreateDefaultBuilder(args)
                   .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseUrls(ListenURL);
                webBuilder.UseStartup <Startup>();
            }));
        }
Example #29
0
 /// <summary>
 /// Return the state value
 /// </summary>
 /// <returns>State value</returns>
 /// <param name="collectionName">Key to identify the state</param>
 public override object GetValue(string collectionName)
 {
     if (!Database.CollectionExists(collectionName))
     {
         return(null);
     }
     return(Database.GetCollection <object>(collectionName).FindAll().First());
 }
Example #30
0
        public void ImportAll()
        {
            try
            {
                using (var db = new LiteDatabase(Path.Combine(ResourcesPath, "dataDb.db")))
                {
                    if (db.CollectionExists("data"))
                    {
                        return;
                    }

                    var allRecords = File.ReadAllLines(Path.Combine(ResourcesPath, "ml.txt"));

                    var allData = new List <Data>();

                    foreach (var record in allRecords)
                    {
                        var columns = record.Split(' ');
                        var id      = columns[0].Substring(0, columns[0].Length - 1);
                        var date    = DateTime.ParseExact(columns[1], "dd.MM.yyyy", CultureInfo.InvariantCulture);
                        var prev    = allData.LastOrDefault();

                        if (prev != null && prev.Added.Day == date.Day)
                        {
                            date += TimeSpan.FromHours(21); // Second draw of the day.
                        }
                        else
                        {
                            date += TimeSpan.FromHours(14);
                        }

                        var values = columns[2].Split(',').Select(int.Parse).OrderByDescending(b => b).ToArray();
                        var pairs  = _permutationProvider.GetPermutations(values, 2)
                                     .Select(p => p.ToArray()[0] + ", " + p.ToArray()[1]).ToArray();

                        var data = new Data
                        {
                            Id       = int.Parse(id),
                            Added    = date,
                            Values   = values,
                            Pairs    = pairs,
                            IsCustom = false
                        };

                        allData.Add(data);
                    }
                    var a = allData.Where(d => d.Pairs.Contains("2, 6")).ToList();
                    var dataCollection = db.GetCollection <Data>("data");
                    dataCollection.InsertBulk(allData);

                    dataCollection.EnsureIndex(col => col.Added);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }
Example #31
0
        private static void DbMigration()
        {
            using (var db = new LiteDatabase(DirectoryHelper.GetDataDirectory() + Settings.Default.LiteDbFileName))
            {
                if (!db.CollectionExists("screenings"))
                {
                    return;
                }

                var col = db.GetCollection("screenings");
                IEnumerable <BsonDocument> items = col.FindAll().ToList();
                foreach (var item in items)
                {
                    var isNeedUpdate = false;
                    var formations   = item["FocalFormations"].AsArray;
                    foreach (var form in formations)
                    {
                        var size = form.AsDocument["Size"];
                        if (!size.IsString)
                        {
                            form.AsDocument.Set("Size", size.AsString);
                            isNeedUpdate = true;
                        }
                        if (size.IsNull)
                        {
                            form.AsDocument.Set("Size", string.Empty);
                            isNeedUpdate = true;
                        }

                        var cdk = form.AsDocument["CDK"];
                        if (cdk.AsString == "Avascular")
                        {
                            form.AsDocument.Set("CDK", "None");
                            isNeedUpdate = true;
                        }
                    }

                    var cysts = item["Cysts"].AsArray;
                    if (cysts != null)
                    {
                        foreach (var cyst in cysts)
                        {
                            var cdk = cyst.AsDocument["CDK"];
                            if (cdk.AsString == "Avascular")
                            {
                                cyst.AsDocument.Set("CDK", "None");
                                isNeedUpdate = true;
                            }
                        }
                    }

                    if (isNeedUpdate)
                    {
                        col.Update(item);
                    }
                }
            }
        }