Example #1
0
 /// <summary>
 /// Insert or Update the user's contact. Public key is a primary key.
 /// </summary>
 /// <param name="name">Person's name or reference</param>
 /// <param name="publicKey">Valid Bitcoin-compatible Publickey (string)</param>
 /// <returns>An inserted or updated contact record.</returns>
 public Contact UpsertContact(string name, string publicKey)
 {
     try
     {
         var mycontact = collection.Find(c => c.Address == publicKey).FirstOrDefault();
         if (mycontact == null)
         {
             mycontact = new Contact()
             {
                 Name        = name,
                 Address     = publicKey,
                 AddressHash = new BitcoinPubKeyAddress(publicKey, MainNetwork).Hash.ToBytes()
             };
         }
         else
         {
             mycontact.Name = name;
         }
         collection.Upsert(mycontact);
         collection.EnsureIndex(c => c.Address);
         collection.EnsureIndex(c => c.AddressHash);
         collection.EnsureIndex(c => c.AddressHashString);
         return(mycontact);
     }
     catch (Exception)
     {
         return(null);
     }
 }
Example #2
0
 public void EnsureIndex(LiteCollection <Order> collection)
 {
     collection.EnsureIndex(x => x.ID);
     collection.EnsureIndex(x => x.ClientID);
     collection.EnsureIndex(x => x.ProductID);
     collection.EnsureIndex(x => x.Price);
 }
Example #3
0
 public void EnsureIndex(LiteCollection <Product> collection)
 {
     collection.EnsureIndex(x => x.ID);
     collection.EnsureIndex(x => x.Title);
     collection.EnsureIndex(x => x.Count);
     collection.EnsureIndex(x => x.Price);
 }
Example #4
0
        public AuthDbLdb(LiteDatabase database)
        {
            _db = database;

            _accounts = _db.GetCollection <AccountDataLdb>("accounts");
            _accounts.EnsureIndex(a => a.Username, new IndexOptions()
            {
                Unique = true, IgnoreCase = true, TrimWhitespace = true
            });
            _accounts.EnsureIndex(a => a.Email, new IndexOptions()
            {
                Unique = true, IgnoreCase = true, TrimWhitespace = true
            });

            _resetCodes = _db.GetCollection <PasswordResetData>("resets");
            _resetCodes.EnsureIndex(a => a.Email, new IndexOptions()
            {
                Unique = true, IgnoreCase = true, TrimWhitespace = true
            });

            _emailConfirmations = _db.GetCollection <EmailConfirmationData>("emailConf");
            _emailConfirmations.EnsureIndex(a => a.Email, new IndexOptions()
            {
                Unique = true, IgnoreCase = true, TrimWhitespace = true
            });
        }
        public virtual async void CreateDB()
        {
            try
            {
                db      = new LiteDatabase("filename=" + ApplicationData.Current.LocalFolder.Path + @"\breadplayer.db;journal=false;");
                IsValid = db.DbVersion.ToString() != "";
                if (IsValid)
                {
                    tracks    = db.GetCollection <Mediafile>("tracks");
                    playlists = db.GetCollection <Playlist>("playlists");
                    recent    = db.GetCollection <Mediafile>("recent");
                    tracks.EnsureIndex(t => t.Title);
                    tracks.EnsureIndex(t => t.LeadArtist);
                }
                else
                {
                    await ApplicationData.Current.ClearAsync();

                    CreateDB();
                }
                GetTrackCount();
            }
            catch (Exception)
            {
                await ApplicationData.Current.ClearAsync();

                CreateDB();
            }
        }
Example #6
0
 public DocumentStoreDatabaseService(string dbPath, string collectionName)
 {
     DB = StaticDocumentDatabase.GetDatabase(dbPath.ToLower() + ".db");
     currentCollection = DB.GetCollection <IDbRecord>(collectionName);
     currentCollection.EnsureIndex(t => t.Id);
     currentCollection.EnsureIndex(t => t.TextSearchKey);
 }
Example #7
0
        public HistoryManager(HistoryManagerData hmd)
        {
            Formatter          = new SmartHistoryFormatter();
            historyManagerData = hmd;

            #region CheckUpgrade
            AudioLogEntry[] moveData = null;

            var upgrader = new Deprecated.HistoryFile();
            // check if the old history database system can open it
            try
            {
                upgrader.OpenFile(historyManagerData.HistoryFile);
                Log.Write(Log.Level.Info, "Found old history database vesion, upgrading now.");

                moveData = upgrader
                           .GetAll()
                           .Select(x => new AudioLogEntry((int)x.Id, x.AudioResource)
                {
                    PlayCount    = x.PlayCount,
                    Timestamp    = x.Timestamp,
                    UserInvokeId = x.UserInvokeId,
                })
                           .ToArray();
                // the old database allowed 0-id, while the new one kinda doesn't
                var nullIdEntity = moveData.FirstOrDefault(x => x.Id == 0);
                if (nullIdEntity != null)
                {
                    nullIdEntity.Id = moveData.Select(x => x.Id).Max() + 1;
                }

                upgrader.CloseFile();
                upgrader.BackupFile();
                upgrader.historyFile.Delete();
            }
            // if not it is already the new one or corrupted
            catch (FormatException) { }
            finally
            {
                upgrader.Dispose();
            }
            #endregion

            Util.Init(ref unusedIds);
            var historyFile = new FileInfo(hmd.HistoryFile);
            database = new LiteDatabase(historyFile.FullName);

            audioLogEntries = database.GetCollection <AudioLogEntry>(AudioLogEntriesTable);
            audioLogEntries.EnsureIndex(x => x.AudioResource.ResourceTitle);
            audioLogEntries.EnsureIndex(x => x.AudioResource.UniqueId, true);

            RestoreFromFile();

            #region CheckUpgrade
            if (moveData != null)
            {
                audioLogEntries.Insert(moveData);
            }
            #endregion
        }
 public static void EnsureIndexes(this LiteCollection <BusinessCard> collection)
 {
     collection.EnsureIndex(x => x.Id, true);
     collection.EnsureIndex(x => x.FirstName);
     collection.EnsureIndex(x => x.LastName);
     collection.EnsureIndex(x => x.BirthDay);
 }
 public LiteDbService()
 {
     _db         = new LiteDatabase(Path.Combine(FileSystem.AppDataDirectory, "covid19.db"));
     _collection = _db.GetCollection <T>();
     _collection.EnsureIndex("country");
     _collection.EnsureIndex("countryPtBR");
 }
 protected override void EnsureIndeces(LiteCollection <FundRequestDTO> coll)
 {
     coll.EnsureIndex(_ => _.SerialNum);
     //coll.EnsureIndex(_ => _.RequestDate);
     coll.EnsureIndex(_ => _.DateOffset);
     coll.EnsureIndex(_ => _.BankAccountId);
 }
 private void DoIndexing(LiteCollection <ApplicationsModel> collections)
 {
     collections.EnsureIndex(x => x.Id);
     collections.EnsureIndex(x => x.Name);
     collections.EnsureIndex(x => x.ConnectionString);
     collections.EnsureIndex(x => x.IsActive);
 }
Example #12
0
        public virtual async void CreateDB()
        {
            try
            {
                IsValid = StaticDatabase.DB.Engine != null;
                if (IsValid)
                {
                    tracks    = StaticDatabase.DB.GetCollection <Mediafile>("tracks");
                    playlists = StaticDatabase.DB.GetCollection <Playlist>("playlists");
                    recent    = StaticDatabase.DB.GetCollection <Mediafile>("recent");
                    tracks.EnsureIndex(t => t.Title);
                    tracks.EnsureIndex(t => t.LeadArtist);
                }
                else
                {
                    await ApplicationData.Current.ClearAsync();

                    CreateDB();
                }
                GetTrackCount();
            }
            catch (Exception)
            {
                await ApplicationData.Current.ClearAsync();

                CreateDB();
            }
        }
        /// <summary>
        ///     Constructor
        ///     - initializes LiteDB database
        ///     - opens collects for transactions and blocks, and ensures indexes
        /// </summary>
        /// <param name="fileName"></param>
        public DatabaseConsumer(string fileName) : base()
        {
            var database = new LiteDatabase(fileName);

            _transactions = database.GetCollection <Transaction>("transactions");
            _transactions.EnsureIndex(x => x.TXIDHex, true);
            _blocks = database.GetCollection <Block>("block");
            _blocks.EnsureIndex(x => x.BlockHash, true);
            _blocks.EnsureIndex(x => x.Height);
            _subscriptions = database.GetCollection <Subscription>("subscriptions");
            _subscriptions.EnsureIndex(x => x.subTo, true);

            var mapper = BsonMapper.Global;

            // exclude fields Transactions and LengthMatch from block database storage
            mapper.Entity <Block>().Ignore(x => x.Transactions).Ignore(x => x.LengthMatch);
            // exclude field LengthMatch from block database storage
            mapper.Entity <Transaction>().Ignore(x => x.LengthMatch);
            // get the chaintip hash
            var chainTip = _blocks.FindOne(x => x.IsChainTip);

            if (chainTip != null)
            {
                _chainTipHash = chainTip.BlockHash;
            }
        }
Example #14
0
        /// <inheritdoc/>
        public override void ForkStateReferences <T>(
            Guid sourceChainId,
            Guid destinationChainId,
            Block <T> branchPoint)
        {
            string srcCollId = StateRefId(sourceChainId);
            string dstCollId = StateRefId(destinationChainId);
            LiteCollection <StateRefDoc> srcColl = _db.GetCollection <StateRefDoc>(srcCollId),
                                         dstColl = _db.GetCollection <StateRefDoc>(dstCollId);

            Query srcQuery = Query.And(
                Query.GT("BlockIndex", 0),
                Query.LTE("BlockIndex", branchPoint.Index)
                );
            IEnumerable <StateRefDoc> srcStateRefs = srcColl.Find(srcQuery);

            dstColl.InsertBulk(srcStateRefs);

            if (!dstColl.Exists(_ => true) && CountIndex(sourceChainId) < 1)
            {
                throw new ChainIdNotFoundException(
                          sourceChainId,
                          "The source chain to be forked does not exist."
                          );
            }

            dstColl.EnsureIndex("AddressString");
            dstColl.EnsureIndex("BlockIndex");

            _lastStateRefCaches.Remove(destinationChainId);
        }
Example #15
0
 /// <summary>
 /// Uses the provided database collection
 /// </summary>
 /// <param name="collection">A LiteDB collection.</param>
 /// <param name="transactional">Whether the queue should use transaction logic, default true</param>
 public LiteQueue(LiteCollection <QueueEntry <T> > collection, bool transactional = true)
 {
     _collection    = collection;
     _transactional = transactional;
     _collection.EnsureIndex(x => x.Id);
     _collection.EnsureIndex(x => x.IsCheckedOut);
 }
Example #16
0
        /// <inheritdoc/>
        public override void ForkStateReferences <T>(
            Guid sourceChainId,
            Guid destinationChainId,
            Block <T> branchPoint)
        {
            string srcCollId = StateRefId(sourceChainId);
            string dstCollId = StateRefId(destinationChainId);
            LiteCollection <StateRefDoc> srcColl = _liteDb.GetCollection <StateRefDoc>(srcCollId),
                                         dstColl = _liteDb.GetCollection <StateRefDoc>(dstCollId);

            dstColl.InsertBulk(srcColl.Find(Query.LTE("BlockIndex", branchPoint.Index)));

            if (!dstColl.Exists(_ => true) && CountIndex(sourceChainId) < 1)
            {
                throw new ChainIdNotFoundException(
                          sourceChainId,
                          "The source chain to be forked does not exist."
                          );
            }

            dstColl.EnsureIndex(nameof(StateRefDoc.StateKey));
            dstColl.EnsureIndex(nameof(StateRefDoc.BlockIndex));

            _lastStateRefCaches.Remove(destinationChainId);
        }
Example #17
0
 public void EnsureIndex(LiteCollection <ServiceTicket> collection)
 {
     collection.EnsureIndex(x => x.ID);
     collection.EnsureIndex(x => x.ClientID);
     collection.EnsureIndex(x => x.Title);
     collection.EnsureIndex(x => x.Problem);
     collection.EnsureIndex(x => x.Price);
 }
Example #18
0
        public TokenManager(DbStore database)
        {
            dbTokenList = database.GetCollection <DbApiToken>(ApiTokenTable);
            dbTokenList.EnsureIndex(x => x.UserUid, true);
            dbTokenList.EnsureIndex(x => x.Token, true);

            database.GetMetaData(ApiTokenTable);
        }
Example #19
0
 private void bulkInsert(LiteCollection <BsonDocument> liteCollection, IEnumerable <BsonDocument> IFCBson)
 {
     //用List<>
     liteCollection.Insert(IFCBson);
     liteCollection.EnsureIndex("_P21id");
     liteCollection.EnsureIndex("_EntityName");
     liteCollection.EnsureIndex("GlobalId");
 }
 private void DoIndexing(LiteCollection <QueryModel> collections)
 {
     collections.EnsureIndex(x => x.Id);
     collections.EnsureIndex(x => x.ApplicationId);
     collections.EnsureIndex(x => x.Name);
     collections.EnsureIndex(x => x.Query);
     collections.EnsureIndex(x => x.IsActive);
 }
Example #21
0
 public void EnsureIndex(LiteCollection <Client> collection)
 {
     collection.EnsureIndex(x => x.ID);
     collection.EnsureIndex(x => x.Name);
     collection.EnsureIndex(x => x.Adress);
     collection.EnsureIndex(x => x.Phone);
     collection.EnsureIndex(x => x.Discount);
 }
Example #22
0
        public void Initialize()
        {
            dbTokenList = Database.GetCollection <DbApiToken>(ApiTokenTable);
            dbTokenList.EnsureIndex(x => x.UserUid, true);
            dbTokenList.EnsureIndex(x => x.Token, true);

            Database.GetMetaData(ApiTokenTable);
        }
        private void Initialize()
        {
            var meta = database.GetMetaData(AudioLogEntriesTable);

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

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

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

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

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

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

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

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

            default:
                Log.Info("Database table \"{0}\" upgraded to {1}", AudioLogEntriesTable, meta.Version);
                break;
            }
        }
Example #24
0
 public void CreateDB()
 {
     db        = new LiteDatabase("filename=" + ApplicationData.Current.LocalFolder.Path + @"\breadplayer.db;journal=false;");
     tracks    = db.GetCollection <Mediafile>("tracks");
     playlists = db.GetCollection <Playlist>("playlists");
     recent    = db.GetCollection <Mediafile>("recent");
     tracks.EnsureIndex(t => t.Title);
     tracks.EnsureIndex(t => t.LeadArtist);
 }
Example #25
0
        public LiteDbContentRepository(IOptions <LiteDbContentOptions> options, IHostingEnvironment env)
        {
            var file = $"{env.ContentRootPath}/{options.Value.DataFile}";

            _db = new LiteDatabase(file);
            _contentCollection = _db.GetCollection <Content>();
            _contentCollection.EnsureIndex(x => x.ParentId);
            _contentCollection.EnsureIndex(x => x.Urls);
        }
Example #26
0
        public TrackItemService(LiteDatabase db = null)
        {
            var homedir = Environment.GetEnvironmentVariable("TRACKMAT_HOME", EnvironmentVariableTarget.User) ?? Environment.GetEnvironmentVariable("TRACKMAT_HOME");

            Db         = db ?? new LiteDatabase(Path.Combine(homedir, "trackmat.db"));
            TrackItems = Db.GetCollection <TrackItem>();
            TrackItems.EnsureIndex(item => item.Item);
            TrackItems.EnsureIndex(item => item.Date);
        }
        public void GlobalSetupSimpleIndexBaseline()
        {
            DatabaseInstance    = new LiteDatabase(ConnectionString);
            _fileMetaCollection = DatabaseInstance.GetCollection <FileMetaBase>();
            _fileMetaCollection.EnsureIndex(fileMeta => fileMeta.ShouldBeShown);
            _fileMetaCollection.EnsureIndex(fileMeta => fileMeta.IsFavorite);

            _fileMetaCollection.Insert(FileMetaGenerator <FileMetaBase> .GenerateList(N)); // executed once per each N value
        }
Example #28
0
 public void InsertTag(StorageTag tag)
 {
     lock (dbLock)
     {
         _tagCollection.Insert(tag);
         _tagCollection.EnsureIndex(x => x.TagName);
         _tagCollection.EnsureIndex(x => x.ProjectId);
     }
 }
Example #29
0
 public void InsertImage(StorageImage image)
 {
     lock (dbLock)
     {
         _storageCollection.Insert(image);
         _storageCollection.EnsureIndex(x => x.FullFileName);
         _storageCollection.EnsureIndex(x => x.ProjectId);
     }
 }
Example #30
0
        /// <summary>
        /// Метод проверяет существует ли такой контрагент в базе
        /// </summary>
        /// <param name="_inn"></param>
        /// <param name="_kpp"></param>
        /// <returns></returns>
        public bool CheckExist(string _inn, string _kpp)
        {
            LiteCollection <Contractor> collection = database.GetCollection <Contractor>("contractors");

            collection.EnsureIndex(a => a.INN);
            collection.EnsureIndex(a => a.KPP);
            bool result = collection.Exists(a => a.INN == _inn && a.KPP == _kpp);

            return(result);
        }
Example #31
0
        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);
        }      
Example #32
0
 public static void ClassInit(TestContext context)
 {
     db = new LiteDatabase(new MemoryStream());
     col = db.GetCollection<TestPocoClass>("col1");
     col.EnsureIndex(o => o.Key);
 }