コード例 #1
0
        public int Upsert <T>(List <T> Data)
        {
            string CollectionName = typeof(T).Name;
            int    _ret           = -1;

            _ret = _repo.Upsert <T>(Data, CollectionName);
            return(_ret);
        }
コード例 #2
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var allTimeUpdate = new List <decimal>();

            while (!stoppingToken.IsCancellationRequested)
            {
                var stopWatch        = new Stopwatch();
                var singleTimeUpdate = new List <decimal>();
                using (_repository)
                {
                    var requiredGames = _repository.Query <RequiredGame>().ToList();
                    Console.WriteLine($"[{DateTime.Now:O}] Будет обновлено {requiredGames.Count} игр.");
                    foreach (var requiredGame in requiredGames)
                    {
                        stopWatch.Restart();
                        var game = _repository.Query <Game>()
                                   .Include(g => g.Cards)
                                   .Where(g => g.SteamAppId == requiredGame.SteamAppId)
                                   .FirstOrDefault();
                        if (game is null)
                        {
                            game = await _gameInfoLoader.GetInfo(requiredGame.SteamAppId);
                        }
                        else
                        {
                            game = await _gameInfoLoader.UpdateInfo(game);
                        }

                        game.Cards.ForEach(card => _repository.Upsert(card));
                        _repository.Upsert(game);
                        stopWatch.Stop();
                        singleTimeUpdate.Add((decimal)stopWatch.Elapsed.TotalMilliseconds);
                        Console.WriteLine($"Игра {game.Name} обновлена за {stopWatch.Elapsed:g}.");
                    }
                }

                if (singleTimeUpdate.Count > 0)
                {
                    var singleAvgUpdateTime = (double)singleTimeUpdate.Average();
                    Console.WriteLine(
                        $"Среднее время обновления игр за последний заход составило {TimeSpan.FromMilliseconds(singleAvgUpdateTime):g}.");

                    allTimeUpdate.AddRange(singleTimeUpdate);
                    var avgUpdateTime = (double)allTimeUpdate.Average();
                    Console.WriteLine(
                        $"Общее среднее время обновления игр составляет {TimeSpan.FromMilliseconds(avgUpdateTime):g}.");
                }
                else
                {
                    Console.WriteLine("В списке нет игр на обновление.");
                }

                await Task.Delay(TimeSpan.FromMinutes(_serviceOptions.UpdateDelay), stoppingToken);
            }
        }
コード例 #3
0
 public bool Upsert(T item)
 {
     using (var db = new LiteRepository(ConnectionString))
     {
         return(db.Upsert(item));
     }
 }
コード例 #4
0
 public bool SaveProfile(InferenceProfile item)
 {
     using (var repository = new LiteRepository(_connectionStringProvider.ConnectionString))
     {
         return(repository.Upsert(item));
     }
 }
コード例 #5
0
        /// <summary>Commit changes made to the collection.</summary>
        async Task ICollectionRef <T> .Commit()
        {
            try
            {
                using LiteRepository _liteRepo = new LiteRepository(RefConfig.Location);
                if (ToSave.Any() || ToModify.Any())
                {
                    IList <T> _combinedList = ToSave.Concat(ToModify).ToList();
                    _liteRepo.Upsert <T>(_combinedList, RefConfig.Collection);
                }
                if (ToRemove.Any())
                {
                    BsonValue[] _bsonValues = ToRemove.Select(_id => new BsonValue(_id)).ToArray();
                    _liteRepo.DeleteMany <T>(Query.In("_id", _bsonValues), RefConfig.Collection);
                }

                await Task.Run(() =>
                {
                    ToSave.Clear();
                    ToModify.Clear();
                    ToRemove.Clear();
                });
            }
            catch (Exception ex)
            { throw ex; }
        }
コード例 #6
0
ファイル: Repository.cs プロジェクト: Warafux/StardewMods
 /// <summary>
 /// Insert or Update a document based on _id key. Returns true if insert entity or false if update entity
 /// </summary>
 public bool Upsert <T>(T entity, string collectionName = null)
 {
     using (var db = new LiteRepository(_configService.ConnectionString))
     {
         return(db.Upsert <T>(entity, collectionName));
     }
 }
コード例 #7
0
 public async Task Commit()
 {
     try
     {
         // For some odd reasons, current LiteDB version does not support transaction
         using (LiteRepository _liteRepo = new LiteRepository(LiteDBLocation))
         {
             if (ToSave.Any() || ToModify.Any())
             {
                 IList <T> _combinedList = ToSave.Concat(ToModify).ToList();
                 _liteRepo.Upsert <T>(_combinedList, CollectionName);
             }
             if (ToRemove.Any())
             {
                 _liteRepo.Delete <T>(Query.Where("_id", id => ToRemove.Contains(id)), CollectionName);
             }
         }
         await Task.Run(() =>
         {
             ToSave.Clear();
             ToModify.Clear();
             ToRemove.Clear();
         });
     }
     catch (Exception ex)
     { throw ex; }
 }
コード例 #8
0
        public void Apply(LiteRepository repository)
        {
            List <ProfileEntity> profiles = repository.Query <ProfileEntity>().ToList();

            foreach (ProfileEntity profileEntity in profiles)
            {
                foreach (FolderEntity profileEntityFolder in profileEntity.Folders)
                {
                    profileEntityFolder.Enabled = true;
                    foreach (LayerEffectEntity layerEffectEntity in profileEntityFolder.LayerEffects)
                    {
                        layerEffectEntity.Enabled = true;
                    }
                }

                foreach (LayerEntity profileEntityLayer in profileEntity.Layers)
                {
                    profileEntityLayer.Enabled = true;
                    foreach (LayerEffectEntity layerEffectEntity in profileEntityLayer.LayerEffects)
                    {
                        layerEffectEntity.Enabled = true;
                    }
                }

                repository.Upsert(profileEntity);
            }
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: v-kabanov/PIM
        static void TestLitedb()
        {
            var mapper = new BsonMapper();

            mapper.Entity <Note>()
            .Ignore(n => n.Name)
            .Ignore(n => n.IsTransient);
            //.Id(n => n.Id)
            //.Ignore(n => n.Id);

            //https://github.com/mbdavid/LiteDB/wiki/Connection-String
            var connectionString = "Filename=..\\MyLitedb.dat; Password=posvord; Initial Size=5MB; Upgrade=true";

            string id;

            using (var repo = new LiteRepository(connectionString, mapper))
            {
                var note = Note.Create("Blah blah");
                note.Id = ObjectId.NewObjectId().ToString();

                repo.Upsert(note);
                //var bsonDocument = adapter.ToBson(note);
                //repo.Database.Engine.Upsert(nameof(Note), bsonDocument);
                id = note.Id;
            }

            using (var repo = new LiteRepository(connectionString, mapper))
            {
                //var bson = repo.Engine.FindById(nameof(Note), id);
                //var note = adapter.Read(bson);
                var note = repo.SingleById <Note>(id);

                Console.WriteLine($"{note.Name} - {note.CreateTime} - {note.LastUpdateTime}");
            }
        }
コード例 #10
0
ファイル: ShowRepository.cs プロジェクト: michelealda/tvapi
 public void Insert(Show item)
 {
     using (var db = new LiteRepository(ConnectionString))
     {
         db.Upsert(item);
     }
 }
コード例 #11
0
 public bool SaveSettings(Settings item)
 {
     using (var repository = new LiteRepository(_connectionStringProvider.ConnectionString))
     {
         return(repository.Upsert(item));
     }
 }
コード例 #12
0
ファイル: Repository.cs プロジェクト: Warafux/StardewMods
 /// <summary>
 /// Insert or Update all documents based on _id key. Returns entity count that was inserted
 /// </summary>
 public int Upsert <T>(IEnumerable <T> entities, string collectionName = null)
 {
     using (var db = new LiteRepository(_configService.ConnectionString))
     {
         return(db.Upsert <T>(entities, collectionName));
     }
 }
コード例 #13
0
 public void Upsert(QueryRecordDocument record)
 {
     using (var db = new LiteRepository(ConnectionName))
     {
         db.Upsert(record);
         ConfigCache.Clear();
     }
 }
コード例 #14
0
ファイル: StateManager.cs プロジェクト: asimonf/RetroLite
        public void ScanForGames()
        {
            var systems = Directory.GetDirectories(Path.Combine(Environment.CurrentDirectory, "roms"));

            Logger.Debug("Found paths {systems}", systems);

            var systemCollection = _db.Database.GetCollection <Entity.System>();

            Parallel.ForEach(systems, (systemPath) =>
            {
                var systemName = Path.GetFileNameWithoutExtension(systemPath);

                Console.WriteLine("System " + systemPath);

                var system = systemCollection.FindById(systemName);

                if (null == system)
                {
                    Logger.Warn($"No core loaded for system '{system}'");
                    return;
                }

                var gameFiles = Directory.EnumerateFiles(systemPath);

                Parallel.ForEach(gameFiles, (gameFile) =>
                {
                    var extension = Path.GetExtension(gameFile)?.Replace(".", "");

                    if (null == extension || !system.ValidExtensions.Contains(extension))
                    {
                        Logger.Debug($"Skipping file '{gameFile}'");
                        return;
                    }

                    _db.Upsert(new Game()
                    {
                        Id     = Path.GetFileNameWithoutExtension(gameFile),
                        Name   = Path.GetFileNameWithoutExtension(gameFile),
                        Path   = gameFile,
                        System = systemName
                    });
                });
            });
        }
コード例 #15
0
        public Result <int> Upsert(IEnumerable <T> entities, string collectionName = null)
        {
            var result = new Result <int>();

            try
            {
                result.ResultObject = _liteRepository.Upsert(entities, collectionName);
            }
            catch (Exception ex)
            {
                result.ResultCode         = (int)ResultStatusCode.InternalServerError;
                result.ResultMessage      = "Hata Oluştu => " + ex;
                result.ResultInnerMessage = "Hata Oluştu => " + ex.InnerException;

                result.ResultStatus = false;
            }

            return(result);
        }
コード例 #16
0
        /// <summary>
        /// Updates all interface settings from the provided object properties that are not null.
        /// </summary>
        public static void UpdateInterfaceSettings(PartialInterfaceSettings options)
        {
            foreach (var prop in options.GetType().GetProperties())
            {
                if (!(prop.GetValue(options) is string value))
                {
                    continue;
                }

                typeof(InternalOptions).GetProperty(prop.Name).SetValue(InternalOptions, value);
                logger.Debug(new LogSetOption
                {
                    Name  = prop.Name,
                    Value = value
                }.ToJson());
            }

            Repo.Upsert(InternalOptions);
        }
コード例 #17
0
        public Task SetPrefix(IGuild guild, string prefix)
        {
            var _guild = new DiscordServer()
            {
                Id     = guild.Id,
                Prefix = prefix
            };

            _repository.Upsert(_guild);
            return(Task.FromResult(0));
        }
コード例 #18
0
 /// <summary>
 /// true if insert
 /// false if update
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 public bool Save(T entity)
 {
     lock (Keylock)
     {
         using (var repo = new LiteRepository(new LiteDatabase(GetPath())))
         {
             var result = repo.Upsert <T>(entity);
             return(result);
         }
     }
 }
コード例 #19
0
ファイル: LiteDbTests.cs プロジェクト: maxbl4/RaceLogic
        public void Should_generate_long_id()
        {
            using var repo = new LiteRepository(dbFile).WithUtcDate();
            var entity = new EntityLong {
                Data = "123"
            };

            repo.Upsert(entity);
            var e = repo.Query <EntityLong>().Where(x => x.Id == entity.Id).First();

            e.Data.Should().Be("123");
            e.Id.Should().NotBe(0);
        }
コード例 #20
0
        public void Should_serialize_and_deserialize_to_litedb()
        {
            using var repo = new LiteRepository(dbFileName).WithUtcDate();
            var cls = new Class {
                Id = Id <Class> .NewId(), Name = "Class1"
            };
            var rider = new Rider {
                Id = Id <Rider> .NewId(), Name = "Rider1", ClassId = cls.Id
            };

            repo.Insert(cls);
            repo.Upsert(rider);
            repo.Upsert(rider);
            repo.Query <Rider>().Count().Should().Be(1);

            var persistedRider = repo.Query <Rider>().Where(x => x.Id == rider.Id).First();

            persistedRider.Name.Should().Be("Rider1");
            var persistedClass = repo.Query <Class>().Where(x => x.Id == persistedRider.ClassId).First();

            persistedClass.Name.Should().Be("Class1");
        }
コード例 #21
0
        public async Task SetPrefix(string name)
        {
            var all = _repository.Query <DiscordGuild>().ToList();

            var guild = new DiscordGuild()
            {
                Id     = Context.Guild.Id,
                Prefix = name
            };

            var result = _repository.Upsert(guild);

            await ReplyAsync($"Prefix changed succesfully.");
        }
コード例 #22
0
        protected void Save <TState>(TState aggregateState, Guid id)
            where TState : struct
        {
            using (var db = new LiteRepository(_connectionString, _mapper))
            {
                var stateWrapped = new StateWrapper <TState>
                {
                    Id    = id,
                    State = aggregateState
                };

                db.Upsert(stateWrapped, _collectionName);
            }
        }
コード例 #23
0
        //irasome duomenis i LitleDB
        private void InsertIntoLitleDB()
        {
            if (connectionString == "")
            {
                return;
            }

            using (var db = new LiteRepository(connectionString))
            {
                foreach (Elementas el in elementai)
                {
                    db.Upsert(el);
                }
            }
        }
コード例 #24
0
ファイル: Custom_Mapper_Tests.cs プロジェクト: gunpal5/LiteDB
        public void ShouldInsertIntoDatabaseAndRecover()
        {
            var items = CreateCollection();

            using (var repository = new LiteRepository(new MemoryStream(), _mapper))
            {
                var result = repository.Upsert <ItemCollection>(items);
                Assert.IsTrue(result);
                Assert.AreNotEqual(Guid.Empty, items.Id);
                var lst = repository.SingleById <ItemCollection>(items.Id);
                Assert.AreEqual("MyCollection", lst.MyItemCollectionName);
                Assert.AreEqual(lst.Count, 1);
                Assert.IsInstanceOfType(lst[0], typeof(Item));
                Assert.AreEqual(lst[0].MyItemName, "MyItem");
            }
        }
コード例 #25
0
        public void SavePlaylist(Playlist playlist)
        {
            if (playlist is null)
            {
                throw new ArgumentNullException(nameof(playlist));
            }

            using var db = new LiteRepository(cxstring);
            if (playlist.Tunes.Count > 0)
            {
                db.Upsert(playlist);
            }
            else
            {
                db.Delete <Playlist>(playlist.ID);
            }
        }
コード例 #26
0
        static Database()
        {
            Repo            = new LiteRepository("config.db");
            DB              = Repo.Database;
            InternalOptions = Repo.FirstOrDefault <InternalOptions>();

            if (InternalOptions == null)
            {
                InternalOptions = new InternalOptions();
                return;
            }

            // check if InternalOptions are valid
            InternalOptions.MaxModifications = Math.Max(InternalOptions.MaxModifications, 0);
            InternalOptions.Duration         = Math.Max(InternalOptions.Duration, MIN_DURATION);

            Repo.Upsert(InternalOptions);
        }
コード例 #27
0
        public bool Insert(T entity)
        {
            try
            {
                using (var db = new LiteRepository(conStr))
                {
                    // simple access to Insert/Update/Upsert/Delete
                    var result = db.Upsert(entity);

                    //if( result.AsString == entity. )
                    return(result);
                }
            }
            catch
            {
                return(false);
            }
        }
コード例 #28
0
 public void Save(ModuleSettingsEntity moduleSettingsEntity)
 {
     _repository.Upsert(moduleSettingsEntity);
 }
コード例 #29
0
 public bool Upsert <T>(T ins)
 {
     return(_repository.Upsert(ins));
 }
コード例 #30
0
 public void Save(ProfileEntity profileEntity)
 {
     _repository.Upsert(profileEntity);
 }