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;
     }
 }
Exemple #2
2
        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);
            }
        }
Exemple #3
0
        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);

            }
        }
Exemple #4
0
        public void handle <T>(string table, Action <ILiteCollection <T> > action)
            where T : class
        {
            var col = _database.GetCollection <T>(table);

            action(col);
        }
Exemple #5
0
        public void AutoId_Test()
        {
            using (var db = new LiteDatabase(DB.Path()))
            {
                var cs_int = db.GetCollection<EntityInt>("int");
                var cs_guid = db.GetCollection<EntityGuid>("guid");
                var cs_oid = db.GetCollection<EntityOid>("oid");

                // int32
                var cint_1 = new EntityInt { Name = "Using Int 1" };
                var cint_2 = new EntityInt { Name = "Using Int 2" };
                var cint_5 = new EntityInt { Id = 5, Name = "Using Int 5" }; // set Id, do not generate (jump 3 and 4)!
                var cint_6 = new EntityInt { Id = 0, Name = "Using Int 6" }; // for int, 0 is empty

                // guid
                var guid = Guid.NewGuid();

                var cguid_1 = new EntityGuid { Id = guid, Name = "Using Guid" };
                var cguid_2 = new EntityGuid { Name = "Using Guid" };

                // oid
                var oid = ObjectId.NewObjectId();

                var coid_1 = new EntityOid { Name = "ObjectId-1" };
                var coid_2 = new EntityOid { Id = oid, Name = "ObjectId-2" };

                cs_int.Insert(cint_1);
                cs_int.Insert(cint_2);
                cs_int.Insert(cint_5);
                cs_int.Insert(cint_6);

                cs_guid.Insert(cguid_1);
                cs_guid.Insert(cguid_2);

                cs_oid.Insert(coid_1);
                cs_oid.Insert(coid_2);

                // test for int
                Assert.AreEqual(cint_1.Id, 1);
                Assert.AreEqual(cint_2.Id, 2);
                Assert.AreEqual(cint_5.Id, 5);
                Assert.AreEqual(cint_6.Id, 6);

                // test for guid
                Assert.AreEqual(cguid_1.Id, guid);
                Assert.AreNotEqual(cguid_2.Id, Guid.Empty);
                Assert.AreNotEqual(cguid_1.Id, cguid_2.Id);

                // test for oid
                Assert.AreNotEqual(coid_1, ObjectId.Empty);
                Assert.AreEqual(coid_2.Id, oid);

            }
        }
        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"));
            }
        }
Exemple #7
0
        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");
            }
        }
Exemple #8
0
        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;
                }
            });
        }
Exemple #9
0
        public async Task Invoke(HttpContext httpContext)
        {
            var sw = Stopwatch.StartNew();

            try
            {
                await _next(httpContext);

                sw.Stop();
            }
            catch (Exception)
            {
                sw.Stop();
            }
            finally
            {
                var item = new RequestLogItem();
                item.RequestMethod = httpContext.Request.Method;
                item.RequestPath   = httpContext.Request.Path;
                item.StatusCode    = httpContext.Response?.StatusCode;
                item.Elapsed       = sw.Elapsed.ToString();
                item.RequestID     = httpContext.TraceIdentifier;

                var logs = _db.GetCollection <RequestLogItem>("RequestLogs");
                logs.Insert(item);
            }
        }
Exemple #10
0
        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)
            {
            }
        }
Exemple #11
0
 public override void Initialize()
 {
     DataBase = new LiteDatabase(ConnectionString);
     LCol     = DataBase.GetCollection <CacheItem>(CollectionName);
     LCol.EnsureIndex(c => c.Key);
     //CurrentCollectionCount = LCol.Count();
 }
Exemple #12
0
        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;
            }
        }
        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
                        });
                    }
                }
            }
        }
Exemple #14
0
        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);
        }
 // 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();
     }
 }
 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();
     }
 }
 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();
     }
 }
Exemple #18
0
 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;
 }
Exemple #19
0
 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;
     }
 }
Exemple #20
0
 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";
     }
 }
 public bool Delete(int laneId)
 {
     using (var database = new LiteDB.LiteDatabase(ConnectionString))
     {
         var lanes  = database.GetCollection <LaneDocument>();
         var result = lanes.Delete(laneId);
         return(result);
     }
 }
Exemple #22
0
        private LiteCollection <T> GetLiteCollection <T>()
        {
            using (var db = new LiteDB.LiteDatabase(_connectionString))
            {
                var q = db.GetCollection <T>(_tableName);

                return(q);
            }
        }
Exemple #23
0
 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;
     }
 }
 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;
     }
 }
 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);
     }
 }
Exemple #26
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);
                    }
                }
            }
        }
        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);
            }
        }
Exemple #28
0
        public void Bulk_Test()
        {
            using (var db = new LiteDatabase(new MemoryStream()))
            {
                var col = db.GetCollection("b");

                col.Insert(GetDocs());

                Assert.AreEqual(220, col.Count());
            }
        }
Exemple #29
0
 public Task<List<InventurItem>> GetDataAsync()
 {
     return Task.Factory.StartNew(() =>
     {
         using (var db = new LiteDatabase(dbName))
         {
             var col = db.GetCollection<InventurItem>(tabName);
             return col.Find(x=>x.Exported == false).OrderByDescending(x=>x.ChangedAt).ToList();
         }
     });
 }
 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
         });
     }
 }
        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);
        }
        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);
        }
        static void DeleteData()
        {
            int id;
            id = Convert.ToInt32(Console.ReadLine());
            using (var db = new LiteDatabase(@"testDB.db"))
            {
                var collection = db.GetCollection<Customer>("customer");

                collection.Delete(id);
                Console.WriteLine("Delete Item Success!");
            }
        }
Exemple #34
0
 private void button1_Click(object sender, EventArgs e)
 {
     //获取题目类型
     var typeName = comboBox1.Text.Trim();
     using (var db = new LiteDatabase("Prob.db"))
     {
         var col = db.GetCollection<Problem>("Problem");
         //先换行分割
         var prolist = textBox1.Text.Trim().Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
         Problem model ;
         Int32 index = 0;
         //题目列表,多行的每次读最后一个
         List<Problem> modelList = new List<Problem>();
         //根据每行的第一个字符和、号进行区分,如果不是新题目,就作为选项添加到上一个题目中去
         while (index <prolist.Length )
         {
             var item = prolist[index];
             if (String.IsNullOrEmpty(item)) continue;
             var titles = item.Trim().Split('、');
             if (titles.Length > 0)
             {
                 int number;
                 if(Int32.TryParse(titles[0],out number))
                 {   //是数字,添加
                     model = new Problem();  //如果分割第1个是数字,则说明是1个新的题目
                     model.ProbId = number;
                     model.ProbText = item;
                     model.TypeName = typeName;
                     //确定答案,答案在()里面,把括号里面是字符串分解并组合
                     var ans = item.Split('(', ')');
                     if (ans.Length < 2) model.Answer = string.Empty;
                     if (ans.Length > 1) model.Answer = ans[1];
                     if (ans.Length > 3) model.Answer = ans[1] + "\r\n" + ans[3];
                     modelList.Add(model);
                 }
                 else
                 {
                     //不是数字,就添加到前一个实体中去,并更新题目内容
                     modelList.Last().ProbText += ("\r\n" + item);
                 }
             }
             else
             {
                 //不是数字,就添加到前一个实体中去,并更新题目内容
                 modelList.Last().ProbText += ("\r\n" + item);
             }
             index++;
         }
         col.InsertBulk(modelList);
     }
     MessageBox.Show("导入完成,关闭软件,重新打开后生效");
 }
        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);
        }
Exemple #36
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);
        }
Exemple #37
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);
        }
Exemple #38
0
        public Task<int> DeleteDataAsync(InventurItem item)
        {
            return Task.Factory.StartNew(() =>
            {
                using (var db = new LiteDatabase(dbName))
                {
                    var col = db.GetCollection<InventurItem>(tabName);
                    var res = col.Delete(x => x.Id == item.Id);

                    return res;
                }
            });
        }
 public void Add(Uri uri, TorrentMovie movie)
 {
     using (var db = new LiteDatabase(PCinemaDbName))
     using (var trans = db.BeginTrans())
     {
         var c = db.GetCollection<TorrentMovie>(TorrentMovieCollectionName);
         if (!c.Update(movie))
         {
             c.Insert(movie);
         }
         trans.Commit();
     }
 }
Exemple #40
0
        public MainForm()
        {
            InitializeComponent();

            using (var db = new LiteDatabase("Prob.db"))
            {
                var col = db.GetCollection<Problem>("Problem");
                var c = col.Count();
                list = col.FindAll().ToList();
            }
            _proc = HookCallback;
            RunHook();
        }
Exemple #41
0
        // 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);
            }
        }
        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 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);
        }
        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);
        }
        public void Add(ImdbData movie)
        {
            movie.LastUpdated = DateTime.Now;

            using (var db = new LiteDatabase(PCinemaDbName))
            using (var trans = db.BeginTrans())
            {
                var c = db.GetCollection<ImdbData>(ImdbMovieCollectionName);
                if (!c.Update(movie))
                {
                    c.Insert(movie);
                }
                trans.Commit();
            }
        }
Exemple #46
0
        public Note Get(int id)
        {
            using (var db = new LiteDatabase(liteDBPath))
            {
                // Get a collection (or create, if not exits)
                var col = db.GetCollection<Note>("notes");
                col.EnsureIndex(x => x.Id);
                return col.FindOne(x => x.Id == id);
            }
            // Index document using document Name property
            //col.EnsureIndex(x => x.Name);

            // Use LINQ to query documents
            //var results = col.Find(x => x.Name.StartsWith("Jo"));
        }
Exemple #47
0
 //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);
     }
 }
Exemple #48
0
        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();
        }
Exemple #49
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);
        }
Exemple #50
0
        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);
        }
Exemple #51
0
        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();
            }
        }
Exemple #52
0
        public Task StoreAsync <T>(string key, T value)
        {
            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 serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);

                collection.Upsert(new LiteDbDataStoreItem()
                {
                    Id   = GenerateStoredKey(key, typeof(T)),
                    Data = serialized,
                });
            }

            return(CompletedTask);
        }
        public static async Task TestManyThread()
        {
            const int TOTAL_NUM   = 10000;
            const int TOTAL_TASKS = 2;

            // ensure using initialized database.
            if (File.Exists("manythread.db"))
            {
                File.Delete("manythread.db");
            }
            if (File.Exists("manythread-log.db"))
            {
                File.Delete("manythread-log.db");
            }

            using (var db = new LiteDB.LiteDatabase("manythread.db"))
            {
                await Task.WhenAll(
                    Enumerable.Range(0, TOTAL_TASKS).Select(async(idx) =>
                {
                    // concurrent insert task
                    await Task.Yield();
                    //db.BeginTrans();
                    var collection = db.GetCollection <EntityA>("HogeCollection");
                    for (int i = 0; i < TOTAL_NUM / TOTAL_TASKS; i++)
                    {
                        collection.Insert(new EntityA()
                        {
                            Id = Interlocked.Increment(ref _idValue),
                            X  = idx * 10000 + i,
                            Y  = $"{idx}_{i}"
                        });
                    }
                    //db.Commit();
                })
                    ).ConfigureAwait(false);
            }
        }
Exemple #54
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = dgReception.SelectedRows
                               .OfType <DataGridViewRow>()
                               .Where(r => !r.IsNewRow)
                               .ToArray();

            try
            {
                using (var db = new LiteDB.LiteDatabase(@"Database.db"))
                {
                    var col = db.GetCollection <Reserve>("Reserves");



                    int rowwIndex = dgReception.FirstDisplayedScrollingRowIndex;


                    foreach (var i in selectedRows)
                    {
                        var row = col.FindById((int)i.Cells[0].Value);
                        col.Delete(row.ID);
                    }



                    loadReserves();

                    dgReception.FirstDisplayedScrollingRowIndex = rowwIndex;
                }
            }
            catch (Exception exp)
            {
                // MessageBox.Show(exp.ToString());
            }
        }
Exemple #55
0
    //创建物体
    public static void SelectDB(AbstractMap _mapController)
    {
        using (var db = new LiteDB.LiteDatabase(Path.Combine(Application.streamingAssetsPath, "mylitedb.db")))
        {
            var placements = db.GetCollection <Placement>("placements");
            var result     = placements.FindAll();

            foreach (var VARIABLE in result)
            {
                Debug.Log(VARIABLE.Name);
                string[]        l               = SplitStr(VARIABLE.Latlon);
                string[]        r               = SplitStr(VARIABLE.Rotation);
                string[]        s               = SplitStr(VARIABLE.Scale);
                Vector2d        v2D             = new Vector2d(Convert.ToDouble(l[0]), Convert.ToDouble(l[1]));
                Vector3         rotation        = new Vector3(Convert.ToSingle(r[0]), Convert.ToSingle(r[1]), Convert.ToSingle(r[2]));
                Vector3         scale           = new Vector3(Convert.ToSingle(s[0]), Convert.ToSingle(s[1]), Convert.ToSingle(s[2]));
                PlaceMentSerial placeMentSerial = new PlaceMentSerial()
                {
                    Name     = VARIABLE.Name,
                    Latlon   = v2D,
                    Rotation = rotation,
                    Scale    = scale
                };

                PutObj.CreateBuildMap(_mapController, VARIABLE.Name, v2D, rotation, scale);
                Debug.Log(MapData.Placements);
                MapData.Placements.Add(placeMentSerial);
                foreach (var VARIABLE1 in MapData.Placements)
                {
                    Debug.Log(VARIABLE1.Name);
                    Debug.Log(VARIABLE1.Rotation);
                    Debug.Log(VARIABLE1.Scale);
                }
            }
        }
    }
Exemple #56
0
 /// <summary>
 /// Insert a new document into collection. Document Id must be a new value in collection - Returns document Id
 /// </summary>
 public BsonValue Insert <T>(T entity, string collectionName = null)
 {
     return(_db.GetCollection <T>(collectionName).Insert(entity));
 }
Exemple #57
0
        public IEnumerable <RequestLogItem> Get(int offset = 0, int limit = 20)
        {
            var logs = _db.GetCollection <RequestLogItem>("RequestLogs");

            return(logs.Find(Query.All("Timestamp", Query.Descending), offset, limit));
        }
Exemple #58
0
 /// <summary>
 /// Insert a new document into collection. Document Id must be a new value in collection - Returns document Id
 /// </summary>
 public void Insert <T>(T entity, string collectionName = null)
 {
     _db.GetCollection <T>(collectionName).Insert(entity);
 }
Exemple #59
0
        public async Task unreleasedBox()
        {
            using (var db = new LiteDB.LiteDatabase("hack.db")) {
                var boxes = db.GetCollection <HTBBox>("boxes");
                var box   = boxes.FindById(1); // get and check if unreleased box is in DB
                if (box == null)
                {
                    try {
                        box = await Helpers.Extensions.GetUnreleasedBox();
                    }

                    catch {
                        await ReplyAsync("Sorry, no unreleased box yet :sob:");

                        return;
                    }
                    boxes.Insert(box); // save to DB if absent
                    var builder = new EmbedBuilder()
                    {
                        Color       = new Color(0xFD3439),
                        Description = $":information_source: Unreleased boxes"
                    };

                    builder.AddField(x =>
                    {
                        x.Name  = $"**Name**: {box.name}\n";
                        x.Value =
                            $"**Retiring**  : {box.retiredbox}\n" +
                            $"**OS**: {box.os}\n" +
                            $"**Difficulty**: {Helpers.Extensions.HTBBoxDiffCalc(box.points)}\n" +
                            $"**Maker**: {box.maker.Username}\n" +
                            $"**Time Left**: {Helpers.Extensions.GetTimeLeft(box.release)}";
                        x.IsInline = false;
                    });

                    builder.WithThumbnailUrl(box.avatar_thumb);

                    await ReplyAsync("", embed : builder.Build());
                }
                else
                {
                    var builder = new EmbedBuilder()
                    {
                        Color       = new Color(0xFD3439),
                        Description = $":information_source: Unreleased boxes"
                    };

                    builder.AddField(x =>
                    {
                        x.Name  = $"**Name**: {box.name}\n";
                        x.Value =
                            $"**Retiring**  : {box.retiredbox}\n" +
                            $"**OS**: {box.os}\n" +
                            $"**Difficulty**: {Helpers.Extensions.HTBBoxDiffCalc(box.points)}\n" +
                            $"**Maker**: {box.maker.Username}\n" +
                            $"**Time Left**: {Helpers.Extensions.GetTimeLeft(box.release)}";
                        x.IsInline = false;
                    });

                    builder.WithThumbnailUrl(box.avatar_thumb);

                    await ReplyAsync("", embed : builder.Build());
                }
            }
        }