コード例 #1
3
 public TorrentImdbEntry GetById(Uri id)
 {
     using (var db = new LiteDatabase(PCinemaDbName))
     {
         var movie = db.GetCollection<TorrentImdbEntry>(TorrentImdbEntryCollectionName)
             .Find(x => x.TorrentLink == id)
             .FirstOrDefault(x => x.TorrentLink == id);
         return movie;
     }
 }
コード例 #2
2
ファイル: ListView.xaml.cs プロジェクト: burukinsd/USD
        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);
            }
        }
コード例 #3
0
ファイル: LiteDbDataStore.cs プロジェクト: and3k5/GmailStats
        public Task <T> GetAsync <T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }


            var tcs = new TaskCompletionSource <T>();

            try
            {
                using (var db = new LiteDB.LiteDatabase(dbPath))
                {
                    var collection = db.GetCollection <LiteDbDataStoreItem>(DataStoreCollectionName);

                    var idKey = GenerateStoredKey(key, typeof(T));

                    var item = collection.FindById(idKey);

                    tcs.SetResult(item == null ? default(T) : NewtonsoftJsonSerializer.Instance.Deserialize <T>(item.Data));
                }
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }

            return(tcs.Task);
        }
コード例 #4
0
ファイル: DbBase.cs プロジェクト: flycd/MyWeb
        public static LiteDatabase CreateDBContext()
        {
            //打开或者创建新的数据库

               var db = new LiteDatabase("App_Data/MyData.db");
               return db;
        }
コード例 #5
0
ファイル: Reception.cs プロジェクト: aymanprocessor/Medical
        private void search(string by, string what)
        {
            try
            {
                reception_Frm = new Reception_frm(this);

                using (var db = new LiteDB.LiteDatabase(@"database.db"))
                {
                    var coll = db.GetCollection <Reserve>("Reserves");
                    coll.EnsureIndex(x => x.name);
                    coll.EnsureIndex(x => x.reserveDate);

                    var row = coll.Find(Query.StartsWith(by, what)).Select(x => new
                    {
                        Code       = x.ID,
                        Name       = x.name,
                        Mobile     = x.mobile,
                        Job        = x.job,
                        Department = x.dept,
                        Date       = x.reserveDate.ToString("d/MM/yyyy")
                    });
                    MessageBox.Show("github");
                    dgReception.DataSource = row.ToList();
                }
            }
            catch (Exception)
            {
            }
        }
コード例 #6
0
        public void change_password()
        {
            var author = new Author()
            {
                Email = "*****@*****.**",
                HashedPassword = Hasher.GetMd5Hash("mzblog")
            };
            using (var _db = new LiteDatabase(_dbConfig.DbPath))
            {
                var authorCol = _db.GetCollection<Author>(DBTableNames.Authors);
                authorCol.Insert(author);

                new ChangePasswordCommandInvoker(_dbConfig)
                    .Execute(new ChangePasswordCommand()
                    {
                        AuthorId = author.Id,
                        OldPassword = "******",
                        NewPassword = "******",
                        NewPasswordConfirm = "pswtest"
                    })
                    .Success.Should().BeTrue();

                authorCol.FindById(author.Id).HashedPassword.Should().BeEquivalentTo(Hasher.GetMd5Hash("pswtest"));
            }
        }
コード例 #7
0
ファイル: IndexOrderTest.cs プロジェクト: ktaranov/LiteDB
        public void Index_Order()
        {
            using (var db = new LiteDatabase(new MemoryStream()))
            {
                var col = db.GetCollection<BsonDocument>("order");

                col.Insert(new BsonDocument().Add("text", "D"));
                col.Insert(new BsonDocument().Add("text", "A"));
                col.Insert(new BsonDocument().Add("text", "E"));
                col.Insert(new BsonDocument().Add("text", "C"));
                col.Insert(new BsonDocument().Add("text", "B"));

                col.EnsureIndex("text");

                var asc = string.Join("",
                    col.Find(Query.All("text", Query.Ascending))
                    .Select(x => x["text"].AsString)
                    .ToArray());

                var desc = string.Join("",
                    col.Find(Query.All("text", Query.Descending))
                    .Select(x => x["text"].AsString)
                    .ToArray());

                Assert.AreEqual(asc, "ABCDE");
                Assert.AreEqual(desc, "EDCBA");
            }
        }
コード例 #8
0
ファイル: DataService.cs プロジェクト: mprattinger/Inventur
        public Task<int> SaveDataAsync(InventurItem item, bool isNew = false)
        {
            return Task.Factory.StartNew(() =>
            {
                item.ChangedAt = DateTime.Now;
                item.Exported = false;
                using (var db = new LiteDatabase(dbName))
                {
                    var col = db.GetCollection<InventurItem>(tabName);
                    if (isNew)
                    {
                        //Zuerst prüfen ob es bereits einen Eintrag gibt

                        var existing = col.Find(x => x.EANCode == item.EANCode && x.Exported == false).FirstOrDefault();
                        if (existing != null)
                        {
                            existing.Amount += item.Amount;
                            existing.ChangedAt = item.ChangedAt;
                            col.Update(existing);
                        }
                        else
                        {
                            item.CreatedAt = DateTime.Now;
                            var res = col.Insert(item);
                        }
                    }
                    else
                    {
                        col.Update(item);
                    }
                    return 1;
                }
            });
        }
コード例 #9
0
        /// <summary>
        /// Wraps a database operation in a try/catch block
        /// </summary>
        /// <typeparam name="U">The type of result expected from the function</typeparam>
        /// <param name="path">The database path and filename</param>
        /// <param name="f">The operation to invoke</param>
        /// <returns>A CallResult with the result of the operation</returns>
#pragma warning disable CS1573
        public static CallResult <U> LiteDbAction <U>(string path, Func <LiteDatabase, U> f, [CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = 0)
#pragma warning restore CS1573
        {
            var result = new CallResult <U>();

            try
            {
                if (f == null)
                {
                    throw new ArgumentNullException("LiteDbAction: Parameter 'f' cannot be null");
                }
                using (var db = new LiteDB.LiteDatabase(path))
                {
                    result.Result  = f.Invoke(db);
                    result.Success = true;
                }
            }
            catch (LiteException e)
            {
                result.Exception = e;
                Log.e(new Exception(string.Format("LiteException: ErrorCode={0}, Message={1}", e.ErrorCode, e.Message), e));
            }
            catch (Exception e)
            {
                result.Exception = e;
                Log.e(new Exception(string.Format("Caller:{0}, Line:{1}, File:{2}", callerMemberName, callerLineNumber, callerFilePath), e));
            }
            return(result);
        }
コード例 #10
0
ファイル: NoteController.cs プロジェクト: jicking/NoteKeeper
        public bool Delete(int id)
        {
            //var results = col.Find(x => x.Name.StartsWith("Jo"));
            try
            {
                using (var db = new LiteDatabase(liteDBPath))
                {
                    // Get a collection (or create, if not exits)
                    var col = db.GetCollection<Note>("notes");
                    var note = col.FindOne(x => x.Id == id);

                    if (note == null)
                        return false;

                    if (col.Delete(x => x.Id == id) <= 0)
                        return false;

                    return true;
                }
            }
            catch (Exception)
            {

                //throw;
                return false;
            }
        }
コード例 #11
0
        /// <summary>
        /// Retrieve byte data from the database
        /// </summary>
        /// <param name="path">The database path and filename</param>
        /// <param name="id">The unique id used to identify the data</param>
        /// <returns>The data if found, otherwise null</returns>
        public static CallResult <byte[]> Download(this string path, string id)
        {
            var result = new CallResult <byte[]>();

            try
            {
                using (var db = new LiteDB.LiteDatabase(path))
                {
                    var li = db.FileStorage.FindById(id);
                    using (var ms = new System.IO.MemoryStream())
                    {
                        ms.Seek(0, System.IO.SeekOrigin.Begin);
                        li.CopyTo(ms);
                        result.Result  = ms.ToArray();
                        result.Success = true;
                    }
                }
            }
            catch (Exception e)
            {
                result.Exception = e;
                Log.e(e);
            }
            return(result);
        }
コード例 #12
0
 public ControllerFactory(string dbpath =null)
 {
     if (String.IsNullOrEmpty(dbpath) == false)
         this.db = DbContextFactory.CreateLiteDBContext(dbpath);
     else
         this.db = DbContextFactory.CreateLiteDBContext();
 }
コード例 #13
0
        // Parameter has no matching param tag in the XML comment (but other parameters do)
        /// <summary>
        /// Wraps a database operation in a try/catch block
        /// </summary>
        /// <typeparam name="T">The Type which determines the database collection name</typeparam>
        /// <typeparam name="U">The type of result expected from the operation</typeparam>
        /// <param name="path">The database path and filename</param>
        /// <param name="f">The operation to invoke</param>
        /// <returns>A CallResult with the result of the operation</returns>
#pragma warning disable CS1573
        public static CallResult <U> LiteDbAction <T, U>(string path, Func <LiteDatabase, LiteCollection <T>, U> f, [CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = 0) where T : new()
#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
        {
            //return LiteDbAction<T, U>(path, database =>
            //{
            //    return f.Invoke(database, GetCollection<T>(database));
            //}, callerMemberName, callerFilePath, callerLineNumber);
            var result = new CallResult <U>();

            try
            {
                if (f == null)
                {
                    throw new ArgumentNullException("LiteDbAction: Parameter 'f' cannot be null");
                }
                using (var db = new LiteDB.LiteDatabase(path))
                {
                    var collection = GetCollection <T>(db);
                    result.Result  = f.Invoke(db, collection);
                    result.Success = true;
                }
            }
            catch (LiteException e)
            {
                result.Exception = e;
                Log.e(new Exception(string.Format("LiteException: ErrorCode={0}, Message={1}", e.ErrorCode, e.Message), e));
            }
            catch (Exception e)
            {
                result.Exception = e;
                Log.e(new Exception(string.Format("Caller:{0}, Line:{1}, File:{2}", callerMemberName, callerLineNumber, callerFilePath), e));
            }
            return(result);
        }
コード例 #14
0
        public void FileStorage_InsertDelete()
        {
            // create a dump file
            File.WriteAllText("Core.dll", "FileCoreContent");

            using (var db = new LiteDatabase(DB.Path()))
            {
                db.FileStorage.Upload("Core.dll", "Core.dll");

                var exists = db.FileStorage.Exists("Core.dll");

                Assert.Equal(true, exists);

                var deleted = db.FileStorage.Delete("Core.dll");

                Assert.Equal(true, deleted);

                var deleted2 = db.FileStorage.Delete("Core.dll");

                Assert.Equal(false, deleted2);


            }

            File.Delete("Core.dll");
        }
コード例 #15
0
        public void FileStorage_Concurrency()
        {
            using (var db = new LiteDatabase(fdb))
            {
            }

            var t1 = new Thread(new ThreadStart(TaskInsert));
            var t2 = new Thread(new ThreadStart(TaskInsert));
            var t3 = new Thread(new ThreadStart(TaskInsert));
            var t4 = new Thread(new ThreadStart(TaskInsert));
            var t5 = new Thread(new ThreadStart(TaskInsert));
            var t6 = new Thread(new ThreadStart(TaskInsert));

            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();
            t5.Start();
            t6.Start();

            t1.Join();
            t2.Join();
            t3.Join();
            t4.Join();
            t5.Join();
            t6.Join();

        }
コード例 #16
0
ファイル: LiteDbCache.cs プロジェクト: JeremyOne/CryptLink
 public override void Initialize()
 {
     DataBase = new LiteDatabase(ConnectionString);
     LCol     = DataBase.GetCollection <CacheItem>(CollectionName);
     LCol.EnsureIndex(c => c.Key);
     //CurrentCollectionCount = LCol.Count();
 }
コード例 #17
0
ファイル: IncludeTest.cs プロジェクト: andrewhart098/LiteDB
        public void Include_Test()
        {
            using (var db = new LiteDatabase(DB.Path()))
            {
                var customers = db.GetCollection<Customer>("customers");
                var orders = db.GetCollection<Order>("orders");

                var customer = new Customer
                {
                    Name = "John Doe"
                };

                // insert and set customer.Id
                customers.Insert(customer);

                var order = new Order
                {
                    Customer = new DbRef<Customer>(customers, customer.Id)
                };

                orders.Insert(order);

                var query = orders
                    .Include((x) => x.Customer.Fetch(db))
                    .FindAll()
                    .Select(x => new { CustomerName = x.Customer.Item.Name })
                    .FirstOrDefault();

                Assert.Equal(customer.Name, query.CustomerName);

            }
        }
コード例 #18
0
        public async Task Sync()
        {
            var github = new GitHubClient(new ProductHeaderValue("Jackett"));
            var releases = await github.Release.GetAll("zone117x", "Jackett");

            if (releases.Count > 0)
            {
                using (var db = new LiteDatabase(GetDBPath()))
                {
                    var releaseCollection = db.GetCollection<Release>("Releases");
                    releaseCollection.Drop();
                    releaseCollection.EnsureIndex(x => x.When);

                    foreach (var release in releases)
                    {
                        releaseCollection.Insert(new Release()
                        {
                            When = release.PublishedAt.Value.DateTime,
                            Description = release.Body,
                            Title = release.Name,
                            Url = release.HtmlUrl,
                            Version = release.TagName
                        });
                    }
                }
            }
        }
コード例 #19
0
 public static List<Release> GetReleases()
 {
     using (var db = new LiteDatabase(GetDBPath()))
     {
         var releaseCollection = db.GetCollection<Release>("Releases");
         return releaseCollection.FindAll().OrderByDescending(x => x.When).ToList();
     }
 }
コード例 #20
0
 protected virtual LiteDB.LiteDatabase GetDatabase(bool refersh = false)
 {
     if (this.db == null || refersh)
     {
         this.db = new LiteDB.LiteDatabase(connectionString);
     }
     return(this.db);
 }
コード例 #21
0
 public static LiteDatabase OpenOrCreateDefault()
 {
     if (_dbInstance == null)
     {
         _dbInstance = new LiteDatabase("betago_srv.lidb");
     }
     return _dbInstance;
 }
コード例 #22
0
 private LiteStorage GetLiteFileStorage()
 {
     using (var db = new LiteDB.LiteDatabase(_connectionString))
     {
         var q = db.FileStorage;
         return(q);
     }
 }
コード例 #23
0
 // TODO: Clear out data after it has gone stale
 // TODO: Allow for multiple matches to be stored simultaneously
 public static CricinfoMatchDetails GetLastStore()
 {
     using (var db = new LiteDatabase(@"C:\Temp\Cricket.db"))
     {
         var col = db.GetCollection<CricinfoMatchDetails>("score");
         return col.FindAll().OrderByDescending(x => x.RetrievedDate).FirstOrDefault();
     }
 }
コード例 #24
0
ファイル: Form1.cs プロジェクト: kissstudio/LiteDBMgr
 private void button2_Click(object sender, EventArgs e)
 {
     LiteDatabase db = new LiteDatabase(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app.bin"));
     var x = db.GetCollection<Histories>(nameof(Histories));
     x.Delete(Query.All());
     comboBox1.Items.Clear();
     this.buttonLoad.Enabled = false;
 }
コード例 #25
0
 public IEnumerable<TorrentMovie> GetAll()
 {
     using (var db = new LiteDatabase(PCinemaDbName))
     {
         var movies = db.GetCollection<TorrentMovie>(TorrentMovieCollectionName).Find(Query.GTE("LastUpdated", DateTime.Now.AddDays(-1)));
         return movies.ToList();
     }
 }
コード例 #26
0
ファイル: DataBase.cs プロジェクト: xJon/TARSbot
 public static bool RemoveUniqueUser(ulong id)
 {
     using (var db = new LiteDatabase(ConstData.path))
     {
         var uniqueUsers = db.GetCollection<UniqueUser>("uniqueUsers");
         uniqueUsers.Delete(Query.EQ("userID", id));
         return true;
     }
 }
コード例 #27
0
 public bool Delete(int laneId)
 {
     using (var database = new LiteDB.LiteDatabase(ConnectionString))
     {
         var lanes  = database.GetCollection <LaneDocument>();
         var result = lanes.Delete(laneId);
         return(result);
     }
 }
コード例 #28
0
        private LiteCollection <T> GetLiteCollection <T>()
        {
            using (var db = new LiteDB.LiteDatabase(_connectionString))
            {
                var q = db.GetCollection <T>(_tableName);

                return(q);
            }
        }
コード例 #29
0
ファイル: DataBase.cs プロジェクト: xJon/TARSbot
 public static string GetServerPrefix(ulong serverID)
 {
     using (var db = new LiteDatabase(ConstData.path))
     {
         var servers = db.GetCollection<ServerSetting>("servers");
         var customServerSetting = servers.FindOne(Query.EQ("serverID", serverID));
         return (customServerSetting != null && customServerSetting.customPrefix != null) ? customServerSetting.customPrefix : "TARS";
     }
 }
コード例 #30
0
 public LoggingMiddleware(RequestDelegate next, LiteDB.LiteDatabase db)
 {
     _db = db;
     if (next == null)
     {
         throw new ArgumentNullException(nameof(next));
     }
     _next = next;
 }
コード例 #31
0
ファイル: DataBase.cs プロジェクト: xJon/TARSbot
 public static bool IsUniqueUser(ulong id)
 {
     using (var db = new LiteDatabase(ConstData.path))
     {
         var uniqueUsers = db.GetCollection<UniqueUser>("uniqueUsers");
         var resultUser = uniqueUsers.FindOne(Query.EQ("userID", id));
         return resultUser != null ? true : false;
     }
 }
コード例 #32
0
ファイル: LiteDbDataStore.cs プロジェクト: and3k5/GmailStats
        public Task ClearAsync()
        {
            using (var db = new LiteDB.LiteDatabase(dbPath))
                if (db.CollectionExists(DataStoreCollectionName))
                {
                    db.DropCollection(DataStoreCollectionName);
                }

            return(CompletedTask);
        }
コード例 #33
0
ファイル: DataBase.cs プロジェクト: xJon/TARSbot
 public static bool AddUniqueUser(string name, ulong id)
 {
     using (var db = new LiteDatabase(ConstData.path))
     {
         var uniqueUsers = db.GetCollection<UniqueUser>("uniqueUsers");
         var uniqueUser = new UniqueUser { userName = name, userID = id };
         uniqueUsers.Insert(uniqueUser);
         return true;
     }
 }
コード例 #34
0
 public ImdbData GetById(int id)
 {
     using (var db = new LiteDatabase(PCinemaDbName))
     {
         var movie = db.GetCollection<ImdbData>(ImdbMovieCollectionName)
             .Find(x => x.Id == id && x.LastUpdated >= DateTime.Now.AddDays(-7))
             .FirstOrDefault();
         return movie;
     }
 }
コード例 #35
0
 public LiteDBBackedTest()
 {
     var dbDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
     _dbConfig = new Config { DbPath = Path.Combine(dbDir, "blog.db") };
     using (var _db = new LiteDatabase(_dbConfig.DbPath))
     {
         var authorCol = _db.GetCollection<Author>(DBTableNames.Authors);
         authorCol.EnsureIndex<string>(x => x.Id);
     }
 }
コード例 #36
0
        //private readonly Lazy<IDictionariesRepository> _dictionariesRepository;

        protected BaseDocumentDatabase(string dbPath)
        {
            if (String.IsNullOrWhiteSpace(dbPath))
                throw new ArgumentException("Argument is null or whitespace", nameof(dbPath));

            _dbPath = dbPath;
            _db = new LiteDatabase(_dbPath);

            //_dictionariesRepository = new Lazy<IDictionariesRepository>(() => new LiteDictionariesRepository(_db));
        }
コード例 #37
0
        public Archage_AH_DataCollector()
        {
            InitializeComponent();

            path = Directory.GetCurrentDirectory() + "\\ItemDB.db";
            DB = new LiteDatabase(@path);
            inventoryPath = Directory.GetCurrentDirectory() + "\\InventoryDB.db";
            InventoryDB = new LiteDatabase(@inventoryPath);

            conversionPath = Directory.GetCurrentDirectory() + "\\ConversionDB.db";
            ConversionDB = new LiteDatabase(@conversionPath);

            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
            RecipesPath = @Directory.GetCurrentDirectory() + "\\Recipe.json";
            if (File.Exists(RecipesPath))
            {
                string Recipes = System.IO.File.ReadAllText(RecipesPath);
                RecipeItemsTop = new List<RecipeItem>();
                RecipeItemsTop = JsonConvert.DeserializeObject<List<RecipeItem>>(Recipes);
            }
            else
            {
                RecipeItemsTop = new List<RecipeItem>();
            }
            AuctionPath = @Directory.GetCurrentDirectory() + "\\AuctionData.json";
            if (File.Exists(AuctionPath))
            {
                string Auctions = System.IO.File.ReadAllText(AuctionPath);
                AuctionItemsTop = JsonConvert.DeserializeObject<List<AuctionItem>>(Auctions);
            }
            else
            {
                AuctionItemsTop = new List<AuctionItem>();
            }
            InventoryPath = @Directory.GetCurrentDirectory() + "\\Inventory.json";
            if (File.Exists(InventoryPath))
            {
                string Inventory = System.IO.File.ReadAllText(InventoryPath);
                InventoryItemsTop = JsonConvert.DeserializeObject<List<InventoryItem>>(Inventory);
            }
            else
            {
                InventoryItemsTop = new List<InventoryItem>();
            }
            ConversionPath = @Directory.GetCurrentDirectory() + "\\Conversion.json";
            if (File.Exists(ConversionPath))
            {
                string Conversion = System.IO.File.ReadAllText(ConversionPath);
                ConversionItemsTop = JsonConvert.DeserializeObject<List<Conversion>>(Conversion);
            }
            else
            {
                ConversionItemsTop = new List<Conversion>();
            }
        }
コード例 #38
0
ファイル: DbRepo.cs プロジェクト: faush01/Emby.Kodi.SyncQueue
        public DbRepo(string dp, ILogger logger, IJsonSerializer json = null)
        {
            DataPath = dp;
            //LitePlatform.Initialize(new LitePlatformFullDotNet());            
            var data = Path.Combine(DataPath, dataName);
 
            _logger = logger;
            _json = json;

            if (File.Exists(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.ldb")))
            {
                File.Delete(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.ldb"));
            }
            if (File.Exists(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.2.ldb")))
            {
                File.Delete(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.2.ldb"));
            }
            if (File.Exists(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.3.ldb")))
            {
                File.Delete(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.3.ldb"));
            }
            if (File.Exists(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.31.ldb")))
            {
                File.Delete(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.31.ldb"));
            }

            if (!Directory.Exists(DataPath))
            {
                Directory.CreateDirectory(DataPath);
            }

            if (!File.Exists(data))
            {

            }
            if (DB == null) { DB = new LiteDatabase(data); }
            
            folders = DB.GetCollection<FolderRec>("Folders");
            items = DB.GetCollection<ItemRec>("Items");
            userinfos = DB.GetCollection<UserInfoRec>("UserInfos");

            folders.EnsureIndex(x => x.ItemId);
            folders.EnsureIndex(x => x.UserId);
            folders.EnsureIndex(x => x.LastModified);
            folders.EnsureIndex(x => x.Status);
            folders.EnsureIndex(x => x.MediaType);
            items.EnsureIndex(x => x.ItemId);
            items.EnsureIndex(x => x.LastModified);
            items.EnsureIndex(x => x.Status);
            items.EnsureIndex(x => x.MediaType);
            userinfos.EnsureIndex(x => x.ItemId);
            userinfos.EnsureIndex(x => x.UserId);
            userinfos.EnsureIndex(x => x.LastModified);
            userinfos.EnsureIndex(x => x.MediaType);
        }      
コード例 #39
0
ファイル: Program.cs プロジェクト: burukinsd/USD
        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);
                    }
                }
            }
        }
コード例 #40
0
ファイル: LiteFileInfo.cs プロジェクト: azraelrabbit/LiteDB
        internal LiteFileInfo(LiteDatabase db, BsonDocument doc)
        {
            _db = db;

            this.Id = doc["_id"].AsString;
            this.Filename = doc["filename"].AsString;
            this.MimeType = doc["mimeType"].AsString;
            this.Length = doc["length"].AsInt64;
            this.UploadDate = doc["uploadDate"].AsDateTime;
            this.Metadata = doc["metadata"].AsDocument;
        }
コード例 #41
0
        public static void StoreNew(CricinfoMatchDetails current)
        {
            using (var db = new LiteDatabase(@"C:\Temp\Cricket.db"))
            {
                // Get customer collection
                var col = db.GetCollection<CricinfoMatchDetails>("score");

                // Insert new customer document (Id will be auto-incremented)
                col.Insert(current);
            }
        }
コード例 #42
0
ファイル: BulkTest.cs プロジェクト: ktaranov/LiteDB
        public void Bulk_Test()
        {
            using (var db = new LiteDatabase(new MemoryStream()))
            {
                var col = db.GetCollection("b");

                col.Insert(GetDocs());

                Assert.AreEqual(220, col.Count());
            }
        }
コード例 #43
0
 public void Update(int targetId, string laneLabel, int projectId)
 {
     using (var database = new LiteDB.LiteDatabase(ConnectionString))
     {
         var lanes = database.GetCollection <LaneDocument>();
         lanes.Update(targetId, new LaneDocument()
         {
             Title = laneLabel, ProjectId = projectId
         });
     }
 }
コード例 #44
0
        public List <LaneDocument> GetAll(int projectId)
        {
            var laneDocuments = new List <LaneDocument>();

            using (var database = new LiteDB.LiteDatabase(ConnectionString))
            {
                var lanes = database.GetCollection <LaneDocument>();
                laneDocuments = lanes.Find(Query.EQ("ProjectId", projectId)).ToList();
            }

            return(laneDocuments);
        }
コード例 #45
0
        public List <ProjectDocument> GetAll()
        {
            List <ProjectDocument> results;

            using (var database = new LiteDB.LiteDatabase(ConnectionString))
            {
                var projects = database.GetCollection <ProjectDocument>();
                results = projects.FindAll().ToList();
            }

            return(results);
        }
コード例 #46
0
        public bool Delete(int cardId)
        {
            bool result;

            using (var database = new LiteDB.LiteDatabase(ConnectionString))
            {
                var cards = database.GetCollection <CardDocument>();
                cards.EnsureIndex("Id");
                result = cards.Delete(cardId);
            }

            return(result);
        }
コード例 #47
0
        public List <CardDocument> Get(int laneId)
        {
            var cardDocuments = new List <CardDocument>();

            using (var database = new LiteDB.LiteDatabase(ConnectionString))
            {
                var cards = database.GetCollection <CardDocument>();
                cards.EnsureIndex("ParentLaneId");
                cardDocuments = cards.Find(x => x.ParentLaneId == laneId).ToList();
            }

            return(cardDocuments);
        }
コード例 #48
0
        public ProjectDocument Get(int projectId)
        {
            ProjectDocument result;

            using (var database = new LiteDB.LiteDatabase(ConnectionString))
            {
                var projects = database.GetCollection <ProjectDocument>();
                projects.EnsureIndex("Id");
                result = projects.Find(x => x.Id == projectId).FirstOrDefault();
            }

            return(result);
        }
コード例 #49
0
ファイル: Customer.cs プロジェクト: marnezos/uomi
        // Returns a list of customers from the DB.
        // This is the main DB functionality

        public static IEnumerable <Customer> ToList(CustomerColumn orderBy, bool ascending, string filter = "")
        {
            //Open DB
            using (var db = new LiteDB.LiteDatabase(AppDomain.CurrentDomain.BaseDirectory + @"\uomi.db"))
            {
                // Retrieve 'customers' collection
                var col = db.GetCollection <Customer>("customers");

                // Declare a return variable
                IEnumerable <Customer> retCustomers;

                //Check if a filter was provided
                if (string.IsNullOrEmpty(filter))
                {
                    //No filter, fetch everything
                    retCustomers = col.FindAll();
                }
                else
                {
                    //Apply filter in name or address or phonenumber
                    retCustomers = col.Find(x => true).Where(x => CultureInfo.CurrentCulture.CompareInfo.IndexOf(x.Name, filter, CompareOptions.IgnoreCase) >= 0 ||
                                                             CultureInfo.CurrentCulture.CompareInfo.IndexOf(x.Address, filter, CompareOptions.IgnoreCase) >= 0 ||
                                                             CultureInfo.CurrentCulture.CompareInfo.IndexOf(x.Phonenumber, filter, CompareOptions.IgnoreCase) >= 0);
                }

                //Order the output
                switch (orderBy)
                {
                case CustomerColumn.Id:
                    retCustomers = ascending ? retCustomers.OrderBy(x => x.Id) : retCustomers.OrderByDescending(x => x.Id);
                    break;

                case CustomerColumn.Name:
                    retCustomers = ascending ? retCustomers.OrderBy(x => x.Name) : retCustomers.OrderByDescending(x => x.Name);
                    break;

                case CustomerColumn.Address:
                    retCustomers = ascending ? retCustomers.OrderBy(x => x.Address) : retCustomers.OrderByDescending(x => x.Address);
                    break;

                case CustomerColumn.Phonenumber:
                    retCustomers = ascending ? retCustomers.OrderBy(x => x.Phonenumber) : retCustomers.OrderByDescending(x => x.Phonenumber);
                    break;

                case CustomerColumn.Balance:
                    retCustomers = ascending ? retCustomers.OrderBy(x => x.Balance) : retCustomers.OrderByDescending(x => x.Balance);
                    break;
                }
                return(retCustomers);
            }
        }
コード例 #50
0
        /// <summary>
        /// Find and return the first item found matching the criteria
        /// </summary>
        /// <typeparam name="T">The Type which determines the database collection name</typeparam>
        /// <param name="path">The database path and filename</param>
        /// <param name="match">A matching function used to find matches</param>
        /// <returns>The first item found matching the criteria.  Null if no matches were found.</returns>
        public static CallResult <T> FindOne <T>(string path, System.Linq.Expressions.Expression <Func <T, bool> > match) where T : new()
        {
            using (var db = new LiteDB.LiteDatabase(path))
            {
                var collection = GetCollection <T>(db);
                var result     = collection.Find(match).FirstOrDefault();
                return(new CallResult <T>(result != null, result));
            }

            //return LiteDbAction<T, T>(path, (database, collection) =>
            //{
            //    return collection.FindOne(f => match.Invoke(f));
            //});
        }
コード例 #51
0
        public int Insert(string laneLabel, int projectId)
        {
            int id;

            using (var database = new LiteDB.LiteDatabase(ConnectionString))
            {
                var lanes = database.GetCollection <LaneDocument>();
                id = lanes.Insert(new LaneDocument()
                {
                    Title = laneLabel, ProjectId = projectId
                });
            }
            return(id);
        }
コード例 #52
0
        public int New(string projectName)
        {
            int result = 0;

            using (var database = new LiteDB.LiteDatabase(ConnectionString))
            {
                var projects = database.GetCollection <ProjectDocument>();
                result = projects.Insert(new ProjectDocument()
                {
                    Name = projectName
                });
            }

            return(result);
        }
コード例 #53
0
ファイル: Customer.cs プロジェクト: marnezos/uomi
 //Deletes customer instance from the database
 public bool DeleteFromDatabase()
 {
     try
     {
         using (var db = new LiteDB.LiteDatabase(AppDomain.CurrentDomain.BaseDirectory + @"\uomi.db"))
         {
             var col = db.GetCollection <Customer>("customers");
             col.Delete(this.Id);
         }
         return(true);
     }
     catch
     {
         return(false);
     }
 }
コード例 #54
0
ファイル: Reception.cs プロジェクト: aymanprocessor/Medical
        private void update()
        {
            reception_Frm = new Reception_frm(this);
            reception_Frm.clear();
            reception_Frm.btnOk.Text = "Update";
            using (var db = new LiteDB.LiteDatabase(@"database.db"))
            {
                var coll = db.GetCollection <Reserve>("Reserves");
                var row  = coll.FindById((int)dgReception.Rows[rowSelected].Cells[0].Value);

                reception_Frm.dtpReserveDate.Value = row.reserveDate;
                reception_Frm.tbName.Text          = row.name;
                reception_Frm.tbMobile.Text        = row.mobile;
                reception_Frm.cbJob.Text           = row.job;
                reception_Frm.cbDept.Text          = row.dept;
            }
            reception_Frm.Show();
        }
コード例 #55
0
ファイル: LiteDbDataStore.cs プロジェクト: and3k5/GmailStats
        public Task DeleteAsync <T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }

            using (var db = new LiteDB.LiteDatabase(dbPath))
            {
                var collection = db.GetCollection <LiteDbDataStoreItem>(DataStoreCollectionName);

                var idKey = GenerateStoredKey(key, typeof(T));

                collection.Delete(item => item.Id == idKey);
            }

            return(CompletedTask);
        }
コード例 #56
0
        public int Insert(int parentLaneId, string cardName, string cardDescription, int cardPoints,
                          CardTypes parsedCardType)
        {
            int id;

            using (var database = new LiteDB.LiteDatabase(ConnectionString))
            {
                var cards = database.GetCollection <CardDocument>();
                id = cards.Insert(new CardDocument()
                {
                    ParentLaneId    = parentLaneId,
                    CardName        = cardName,
                    CardDescription = cardDescription,
                    CardPoints      = cardPoints
                });
            }
            return(id);
        }
コード例 #57
0
        /// <summary>
        /// Deletes a Bitmap from the database
        /// </summary>
        /// <param name="path">The database path and filename</param>
        /// <param name="id">The unique id identifying the bitmap</param>
        public static CallResult DeleteBitmap(this string path, string id)
        {
            var result = new CallResult();

            try
            {
                using (var db = new LiteDB.LiteDatabase(path))// GetDatabase(path))
                {
                    db.FileStorage.Delete(id);
                    result.Success = true;
                }
            }
            catch (Exception e)
            {
                result.Exception = e;
                Log.e(e);
            }
            return(result);
        }
コード例 #58
0
        /// <summary>
        /// Store a file to the database
        /// </summary>
        /// <param name="path">The database path and filename</param>
        /// <param name="id">The unique id for the filename.  Can be the path and filename, or some other unique value.</param>
        /// <param name="filename">The path and name of the file to save</param>
        /// <returns>True if the data is saved, otherwise False</returns>
        public static CallResult Upload(this string path, string id, string filename)
        {
            var result = new CallResult();

            using (var db = new LiteDB.LiteDatabase(path))
            {
                try
                {
                    db.FileStorage.Upload(id, filename);
                    result.Success = true;
                }
                catch (Exception e)
                {
                    result.Exception = e;
                    Log.e(e);
                }
            }
            return(result);
        }
コード例 #59
0
ファイル: Reception.cs プロジェクト: aymanprocessor/Medical
        private void loadReserves()
        {
            var list = new List <Reserve>();

            using (var db = new LiteDB.LiteDatabase(@"database.db"))
            {
                var col    = db.GetCollection <Reserve>("Reserves");
                var result = col.FindAll().Select(x => new
                {
                    Code       = x.ID,
                    Name       = x.name,
                    Mobile     = x.mobile,
                    Job        = x.job,
                    Department = x.dept,
                    Date       = x.reserveDate.ToString("d/MM/yyyy")
                });

                dgReception.DataSource = result.ToList();
            }
        }
コード例 #60
0
        /// <summary>
        /// Retrieves a file from the database
        /// </summary>
        /// <param name="path">The database path and filename</param>
        /// <param name="id">The unique id used to identify the data</param>
        /// <param name="outputFilename">The path and filename to use when saving the file</param>
        /// <param name="overwrite">If true, any existing file will be overwritten</param>
        /// <returns>True if the file was retrieved and written to the file system.  Otherwise False.</returns>
        public static CallResult Download(this string path, string id, string outputFilename, bool overwrite = true)
        {
            var result = new CallResult();

            try
            {
                using (var db = new LiteDB.LiteDatabase(path))
                {
                    var li = db.FileStorage.FindById(id);
                    li.SaveAs(outputFilename, overwrite);
                    result.Success = true;
                }
            }
            catch (Exception e)
            {
                result.Exception = e;
                Log.e(e);
            }
            return(result);
        }