Exemple #1
0
        public SiteInfo Retrieve()
        {
            SiteInfo item = crawled.Find(p => true, 0, 1).FirstOrDefault();

            _print.Show("remaining:" + crawled.Count());
            return(item);
        }
 /// <inheritdoc/>
 public void Initiate()
 {
     Plex.Objects.Logger.Log("World generator is now reading ISP table...");
     _isps = _db.Database.GetCollection <InternetServiceProvider>("worldIsps");
     _isps.EnsureIndex(x => x.Id);
     Plex.Objects.Logger.Log($"{_isps.Count()} found.");
     if (_backend.IsMultiplayer)
     {
         if (_isps.Count() != _ispNames.Length)
         {
             Plex.Objects.Logger.Log("ISP database out of sync with server's internal namebank. Updating...");
             foreach (var ispName in _ispNames)
             {
                 Plex.Objects.Logger.Log($"Looking for \"{ispName.ToUpper()}\"...");
                 var existing = _isps.FindOne(x => x.Name == ispName);
                 if (existing == null)
                 {
                     Plex.Objects.Logger.Log("Not found. Creating new ISP...");
                     existing = new InternetServiceProvider
                     {
                         Id   = Guid.NewGuid().ToString(),
                         Name = ispName
                     };
                     _isps.Insert(existing);
                 }
             }
         }
     }
 }
 public int Count(Expression <Func <TEntity, bool> > where = null)
 {
     try
     {
         if (where != null)
         {
             return(collection.Count(where));
         }
         return(collection.Count());
     }
     catch { return(0); }
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     using (LiteDatabase database = new LiteDatabase(LiteDbService.dbFilePath))
     {
         LiteCollection <NewsType> collection = database.GetCollection <NewsType>("NewsType");
         if (collection.Count() == 0)
         {
             NewsType document = new NewsType
             {
                 Id   = 1,
                 Name = "培训信息"
             };
             collection.Insert(document);
             document = new NewsType
             {
                 Id   = 2,
                 Name = "资讯信息"
             };
             collection.Insert(document);
         }
         else
         {
             collection.FindAll();
         }
     }
 }
Exemple #5
0
        public async void AddNova_Categoria(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNome.Text) == true)
            {
                await DisplayAlert("Atenção!", "Valor inválido", "Cancelar");

                return;
            }

            if (Categorias.Exists(X => X.Nome == txtNome.Text))
            {
                await DisplayAlert("Atenção!", "Já existe uma categoria com este nome registrado: " + txtNome.Text, "Cancelar");

                return;
            }

            int       idCategoria = Categorias.Count() == 0 ? 1 : (int)(Categorias.Max(x => x.CategoriaId) + 1);
            Categoria categoria   = new Categoria
            {
                CategoriaId = idCategoria,
                Nome        = txtNome.Text,
            };

            Categorias.Insert(categoria);
            await Navigation.PopAsync();
        }
Exemple #6
0
        public async void AddNova_Noticia(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtTitulo.Text) == true)
            {
                await DisplayAlert("Atenção!", "Valor inválido", "Cancelar");

                return;
            }

            if (Noticias.Exists(X => X.Titulo == txtTitulo.Text))
            {
                await DisplayAlert("Atenção!", "Já existe uma notícia com este título registrado: " + txtTitulo.Text, "Cancelar");

                return;
            }

            int     idNoticia = Noticias.Count() == 0 ? 1 : (int)(Noticias.Max(x => x.NoticiaId) + 1);
            Noticia noticia   = new Noticia
            {
                NoticiaId = idNoticia,
                categoria = categoriaSelect,
                Titulo    = txtTitulo.Text,
                Descricao = edtDescricao.Text,
                DtNoticia = lblDtNoticia.Text,
            };

            Noticias.Insert(noticia);
            await Navigation.PopAsync();
        }
Exemple #7
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);
        }
Exemple #8
0
        public async Task <BookingResponse> IsAvailable(Booking booking)
        {
            BookingResponse bookingResponse = null;

            try
            {
                #region Code to create sample data

                SampleData.Delete(d => d.NoOfPax >= 0);

                if (SampleData.Count() == 0)
                {
                    SampleData.InsertBulk(CreateBookingData());
                }

                var all = SampleData.FindAll();

                #endregion

                var result = SampleData.Find(b => b.StartDate == booking.StartDate && b.EndDate == booking.EndDate &&
                                             b.NoOfPax >= int.Parse(booking.NoOfPax));

                bookingResponse = new BookingResponse {
                    IsAvailable = result.Count() == 0?false:true
                };
            }
            catch (Exception)
            {
                //yell / shout //catch // log
            }
            return(await Task.FromResult(bookingResponse));
        }
Exemple #9
0
 public static List <BodyModelProductStatistics> GetLiveLdbBodyModelProductStatistics(string _Type)
 {
     try
     {
         //LogManager.SetCommonLog("GetLdbProductStatistics_request start");
         List <BodyModelProductStatistics> lstPS = new List <BodyModelProductStatistics>();
         // generate new statistic
         //List<ProductStatistics> lstNewPS = StatisticsActs.GetYearProdStatistics();
         // get instanse of ldb
         LiteDatabase db = new LiteDatabase(ldbConfig.ldbConnectionString);
         // get old ldb ps lst
         LiteCollection <BodyModelProductStatistics> dbPS = db.GetCollection <BodyModelProductStatistics>("BodyModelProductStatistics");
         // Get old lst
         if (dbPS.Count() != 0)
         {
             foreach (var item in dbPS.Find(Query.EQ("DateIntervalType", _Type)))
             {
                 lstPS.Add(item);
             }
         }
         // insetr new lst
         //LogManager.SetCommonLog("GetLdbProductStatistics_result="+ dbPS.Count());
         return(lstPS);
     }
     catch (Exception ex)
     {
         LogManager.SetCommonLog("GetLdbBodyModelProductStatistics_" + ex.Message.ToString());
         return(null);
     }
 }
Exemple #10
0
 public static ldbUpdStatus GetLdbUpdateStatus()
 {
     try
     {
         LiteDatabase db;
         db = new LiteDatabase(ldbConfig.ldbUpdateStatusConnectionString);
         // get old ldb ps lst
         LiteCollection <ldbUpdStatus> result = db.GetCollection <ldbUpdStatus>("ldbUpdStatus");
         if ((result != null) && (result.Count() != 0))
         {
             ldbUpdStatus First = new ldbUpdStatus();
             foreach (var item in result.FindAll())
             {
                 return(item);
             }
             ldbUpdStatus lus = new ldbUpdStatus();
             lus.Id = "1";
             return(lus);
         }
         else
         {
             ldbUpdStatus lus = new ldbUpdStatus();
             lus.Id = "1";
             return(lus);
         }
         //db.Dispose();
     }
     catch (Exception ex)
     {
         LogManager.SetCommonLog("GetLdbUpdateStatus:" + ex.Message.ToString());
         return(null);
     }
 }
Exemple #11
0
        public Aliases()
        {
            _db   = new LiteDatabase("sys.db");
            Items = _db.GetCollection <AliasDBItem>("aliases");
            // Items.EnsureIndex(field => field.Domain);

            if (Items.Count() == 0)
            {
                add("bloknot-taganrog.ru", "Блокнот.Таганрог");
                add("bloknot-rostov.ru", "Блокнот.Ростов-на-Дону");
                add("bloknot-novocherkassk.ru", "Блокнот.Новочеркасск");
                add("bloknot-volgograd.ru", "Блокнот.Волгоград");
                add("bloknot-volgodonsk.ru", "Блокнот.Волгодонск");
                add("bloknot-krasnodar.ru", "Блокнот.Краснодар");
                add("bloknot-novorossiysk.ru", "Блокнот.Новороссийск");
                add("bloknot-stavropol.ru", "Блокнот.Ставрополь");
                add("bloknot-shakhty.ru", "Блокнот.Шахты");
                add("161.ru", "161.ru");
                add("big-rostov.ru", "Большой Ростов");
                add("crime0.com", "CrimeRussia.com");
                add("donday.ru", "DonDay.ru");
                add("donnews.ru", "DonNews.ru");
                add("k0m2375.livejournal.com", "k0m2375.Хорошилов");
                add("kavkaz-uzel.eu", "Кавказский Узел");
                add("newsdelo.com", "Деловое Сообщество");
                add("1rnd.ru", "1Rnd.ru");
                add("privet-rostov.ru", "Привет Ростов");
                add("rostovgazeta.ru", "Ростов.Газета");
                add("ruffnews.ru", "Ёрш");
                add("vdnews.org", "VDNews.org");
            }
        }
Exemple #12
0
        public IDatabaseManager Initialize()
        {
            // relational mappings
            _mapper.Entity <VpdbGame>()
            .Id(g => g.Id, false)
            .DbRef(g => g.Backglass, VpdbFiles)
            .DbRef(g => g.Logo, VpdbFiles);
            _mapper.Entity <VpdbRelease>()
            .Id(r => r.Id, false)
            .DbRef(r => r.Game, VpdbGames);
            _mapper.Entity <VpdbTableFile>()
            .DbRef(f => f.Reference, VpdbFiles)
            .DbRef(f => f.PlayfieldImage, VpdbFiles)
            .DbRef(f => f.PlayfieldVideo, VpdbFiles);
            _mapper.Entity <VpdbAuthor>()
            .DbRef(r => r.User, VpdbUsers);
            _mapper.Entity <VpdbFile>()
            .Id(f => f.Id, false);

            // db & collections
            _db       = new LiteDatabase(Path.Combine(_settingsManager.Settings.PinballXFolder, @"Databases\vpdb.db"));
            _jobs     = _db.GetCollection <Job>(Jobs);
            _messages = _db.GetCollection <Message>(Messages);
            _releases = _db.GetCollection <VpdbRelease>(VpdbReleases);
            _files    = _db.GetCollection <VpdbFile>(VpdbFiles);

            _logger.Info("Global database with {0} release(s) loaded.", _releases.Count());
            _initialized.OnNext(true);
            return(this);
        }
Exemple #13
0
        /// <summary>
        /// Create the instance of an <see cref="IndexOutput"/> and the required <see cref="FileContent"/> and <see cref="FileMetaData"/> objects
        /// </summary>
        /// <param name="name">The name of the indexing file </param>
        /// <returns>The object of <see cref="IndexOutput"/></returns>
        public override IndexOutput CreateOutput(string name)
        {
            LiteDbIndexOutput runningOutput;

            if (_runningOutputs.TryRemove(name, out runningOutput))
            {
                runningOutput.Dispose();
            }


            if (0 == _fileContenteCollection.Count(fc => fc.Name == name))
            {
                var fileContent = new FileContent {
                    Name = name
                };
                _fileContenteCollection.Insert(fileContent);
            }
            if (0 == _fileMetaDataCollection.Count(fm => fm.Name == name))
            {
                var fileMetaData = new FileMetaData {
                    Name = name, LastTouchedTimestamp = DateTime.UtcNow
                };
                _fileMetaDataCollection.Insert(fileMetaData);
            }
            GC.Collect();

            var result = new LiteDbIndexOutput(_db, name);

            _runningOutputs.TryAdd(name, result);

            return(result);
        }
Exemple #14
0
        public async Task <int> Count()
        {
            Task <int> task = Task.Run(() => _collection.Count());
            await      task;

            return(task.Result);
        }
Exemple #15
0
 public long GetBlockCount()
 {
     if (_blocks != null)
     {
         return(_blocks.Count());
     }
     return(0);
 }
Exemple #16
0
 /// <summary>
 /// Забирает обновления из базы
 /// </summary>
 private void UpdateAll()
 {
     LastStateFromDatabase    = _db.GetCollection <Call>("missed_calls");
     CurrentDbSize            = LastStateFromDatabase.Count();
     Last250CallsFromDatabase = LastStateFromDatabase.FindAll().OrderByDescending(x => x.Id).Take(250)
                                .ToList();
     CurrentDbSize = Last250CallsFromDatabase.Count;
 }
Exemple #17
0
 public DBService(string connstr)
 {
     _db         = new LiteDatabase(connstr);
     _entrys     = _db.GetCollection <Entry>(_STR_ENTRY_COLLECTION_NAME);
     _storage    = _db.FileStorage;
     _entryCount = _entrys.Count();
     _rand       = new Random();
 }
Exemple #18
0
 public int MatchCount()
 {
     using (LiteDatabase db = new LiteDatabase(DBConnectionString))
     {
         LiteCollection<MatchRecord> matchColl = db.GetCollection<MatchRecord>(MatchHeader);
         return matchColl.Count();
     }
 }
Exemple #19
0
 public int MatchCount(Expression<Func<MatchRecord, bool>> predicate)
 {
     using (LiteDatabase db = new LiteDatabase(DBConnectionString))
     {
         LiteCollection<MatchRecord> matchColl = db.GetCollection<MatchRecord>(MatchHeader);
         return matchColl.Count(predicate);
     }
 }
Exemple #20
0
        public override async Task LoadAsync()
        {
            Ocupado = true;
            try
            {
                LiteCollection <PokemonLTB> pokemonsDB = _dataBase.GetCollection <PokemonLTB>();

                if (pokemonsDB.Count() == 0)
                {
                    var pokemonsAPI = await _pokemonService.GetPokemonsAsync();

                    foreach (var pokemon in pokemonsAPI)
                    {
                        PokemonLTB pokeLTB = new PokemonLTB
                        {
                            Id     = pokemon.Id,
                            Name   = pokemon.Name.ToUpper(),
                            Height = pokemon.Height
                        };

                        pokemonsDB.Upsert(pokeLTB);

                        using (Stream stream = GetImageStreamFromUrl(pokemon.Sprites.FrontDefault.AbsoluteUri))
                        {
                            if (stream != null)
                            {
                                //Verfica se ja existe a imagem,se existir apaga
                                if (_dataBase.FileStorage.Exists(pokemon.Id.ToString()))
                                {
                                    _dataBase.FileStorage.Delete(pokemon.Id.ToString());
                                }
                                _dataBase.FileStorage.Upload(pokemon.Id.ToString(), pokemon.Name, stream);
                            }
                        }
                    }

                    pokemonsDB = _dataBase.GetCollection <PokemonLTB>();
                }



                Pokemons.Clear();

                foreach (var pokemon in pokemonsDB.FindAll())
                {
                    pokemon.Image = ImageSource.FromStream(() => _dataBase.FileStorage.FindById(pokemon.Id.ToString()).OpenRead());
                    Pokemons.Add(pokemon);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Erro", ex.Message);
            }
            finally
            {
                Ocupado = false;
            }
        }
        private void Initialize()
        {
            var meta = database.GetMetaData(AudioLogEntriesTable);

            if (meta.Version > CurrentHistoryVersion)
            {
                Log.Error("Database table \"{0}\" is higher than the current version. (table:{1}, app:{2}). " +
                          "Please download the latest TS3AudioBot to read the history.", AudioLogEntriesTable, meta.Version, CurrentHistoryVersion);
                return;
            }

            audioLogEntries = database.GetCollection <AudioLogEntry>(AudioLogEntriesTable);
            audioLogEntries.EnsureIndex(x => x.AudioResource.UniqueId, true);
            audioLogEntries.EnsureIndex(x => x.Timestamp);
            audioLogEntries.EnsureIndex(ResourceTitleQueryColumn,
                                        $"LOWER($.{nameof(AudioLogEntry.AudioResource)}.{nameof(AudioResource.ResourceTitle)})");
            RestoreFromFile();

            if (meta.Version == CurrentHistoryVersion)
            {
                return;
            }

            if (audioLogEntries.Count() == 0)
            {
                meta.Version = CurrentHistoryVersion;
                database.UpdateMetaData(meta);
                return;
            }

            // Content upgrade
            switch (meta.Version)
            {
            case 0:
                var all = audioLogEntries.FindAll().ToArray();
                foreach (var audioLogEntry in all)
                {
                    switch (audioLogEntry.AudioResource.AudioType)
                    {
                    case "MediaLink": audioLogEntry.AudioResource.AudioType = "media"; break;

                    case "Youtube": audioLogEntry.AudioResource.AudioType = "youtube"; break;

                    case "Soundcloud": audioLogEntry.AudioResource.AudioType = "soundcloud"; break;

                    case "Twitch": audioLogEntry.AudioResource.AudioType = "twitch"; break;
                    }
                }
                audioLogEntries.Update(all);
                meta.Version = 1;
                database.UpdateMetaData(meta);
                goto default;

            default:
                Log.Info("Database table \"{0}\" upgraded to {1}", AudioLogEntriesTable, meta.Version);
                break;
            }
        }
        internal EnrichmentDatabase()
        {
            Logger.LogInfo("Loading enrichment sessions from database...");
            _sessions        = Database.GetCollection <EnrichmentSession.SessionData>("EnrichmentSessions");
            _partialSessions = Database.GetCollection <PartialSession.PartialData>("EnrichmentPartial");

            Logger.LogInfo(_sessions.Count(Query.All()) + " enrichment sessions loaded.");
            Logger.LogInfo(_partialSessions.Count(Query.All()) + " partial session loaded.");
        }
        /// <inheritdoc/>
        public void Initiate()
        {
            _drivePath = Path.Combine(_backend.RootDirectory, "drives");
            if (!System.IO.Directory.Exists(_drivePath))
            {
                Plex.Objects.Logger.Log("Creating drive directory...");
                System.IO.Directory.CreateDirectory(_drivePath);
                Plex.Objects.Logger.Log("Done.");
            }
            Plex.Objects.Logger.Log("Loading and mounting entity drives...");
            this._drives = _database.Database.GetCollection <EntityMount>("entity_drives");
            _drives.EnsureIndex(x => x.Id);
            var noFSCount      = _drives.Delete(x => !File.Exists(Path.Combine(_drivePath, x.ImagePath)));
            var noEntityDrives = _drives.Find(x => _entityBackend.GetEntity(x.EntityId) == null);

            foreach (var drive in noEntityDrives)
            {
                Plex.Objects.Logger.Log($"Removing drive: //{drive.EntityId}/{drive.Mountpoint}. Entity not found.");
                File.Delete(Path.Combine(_drivePath, drive.ImagePath));
                _drives.Delete(x => x.Id == drive.Id);
            }
            Plex.Objects.Logger.Log($"{noFSCount} drives deleted from database due to missing PlexFAT images.");
            Plex.Objects.Logger.Log($"{noEntityDrives.Count()} drives deleted from database due to missing NPC or player entities.");
            Plex.Objects.Logger.Log($"{_drives.Count()} drives loaded from database. Mounting...");

            foreach (var drive in _drives.FindAll())
            {
                Plex.Objects.Logger.Log($"Mounting {drive.ImagePath} to //{drive.EntityId}/{drive.Mountpoint}...");
                var fat = new PlexFATDriveMount(new MountInformation
                {
                    DriveNumber   = drive.Mountpoint,
                    ImageFilePath = Path.Combine(_drivePath, drive.ImagePath),
                    Specification = DriveSpec.PlexFAT,
                    VolumeLabel   = drive.VolumeLabel
                }, drive.EntityId);
                fat.EnsureDriveExistence();
                _mounts.Add(fat);
            }
            Plex.Objects.Logger.Log("Done loading filesystems...");

            _entityBackend.EntitySpawned += (id, entity) =>
            {
                //Create a drive for the entity if they don't have one.
                if (CreateFS(id, 0, "Peacegate OS"))
                {
                    Plex.Objects.Logger.Log($"Created new 'Peacegate OS' drive at //{id}/0.");
                }
            };
            _backend.PlayerJoined += (id, player) =>
            {
                if (CreateFS(_entityBackend.GetPlayerEntityId(id), 0, "Peacegate OS"))
                {
                    Plex.Objects.Logger.Log($"Created new 'Peacegate OS' drive at //{id}/0.");
                }
            };
        }
        private void btnRetornaPorco_Clicked(object sender, EventArgs e)
        {
            LiteCollection <Porco> Porcos = _dataBase.GetCollection <Porco>();

            if (Porcos.Count() > 0)
            {
                var porco = Porcos.FindAll().FirstOrDefault();
                lbStatusPorco.Text = porco.VirouBacon ? "Bacon" : porco.Nome;
            }
        }
        public static bool DoesAccountExist(string username)
        {
            LiteCollection <Account> accs = Account_Database.GetCollection <Account>("Accounts");

            if (accs.Count() <= 0)
            {
                return(false);
            }
            return(accs.FindOne(Query.EQ("Username", username)) != default(Account));
        }
Exemple #26
0
        private void Get(object sender, System.EventArgs e)
        {
            Customers = _dataBase.GetCollection <Customer>();

            if (Customers.Count() > 0)
            {
                var customer = Customers.FindAll().FirstOrDefault(x => x.Name == EntryName.Text);
                DisplayAlert("id: " + customer?.Id, "Name: " + customer?.Name, "ok");
            }
        }
 /// <inheritdoc/>
 public void Initiate()
 {
     Plex.Objects.Logger.Log("Save manager is starting...");
     _saves = _db.Database.GetCollection <SaveFile>("usersaves");
     _saves.EnsureIndex(x => x.Id);
     _values = _db.Database.GetCollection <SaveValue>("usersavevalues");
     _values.EnsureIndex(x => x.Id);
     _snapshots = _db.Database.GetCollection <SaveSnapshot>("usersavesnapshots");
     _snapshots.EnsureIndex(x => x.Id);
     Plex.Objects.Logger.Log($"Done. {_saves.Count()} saves loaded. {_values.Count()} total values loaded.");
 }
        public void RetornaBot_Clicked(object sender, EventArgs e)
        {
            LiteCollection <Bot> Bots = _dataBase.GetCollection <Bot>();

            if (Bots.Count() > 0)
            {
                var bot = Bots.FindAll().FirstOrDefault();
                imgBot.Source    = ImageSource.FromStream(() => _dataBase.FileStorage.FindById(bot.BotId.ToString()).OpenRead());
                lbStatusBot.Text = "Bot Retornado";
            }
        }
        public async Task <IEnumerable <Mediafile> > GetTracks()
        {
            IEnumerable <Mediafile> collection = null;
            await Core.CoreMethods.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                Core.CoreMethods.LibVM.SongCount = tracks.Count();
                collection = tracks.Find(LiteDB.Query.All());
            });

            return(collection);
        }
Exemple #30
0
 public long GetLength()
 {
     try
     {
         return(liteCollection.Count());
     }
     catch (NullReferenceException ex)
     {
         return(0);
     }
 }