/// <inheritdoc/>
        public void SafetyCheck()
        {
            Plex.Objects.Logger.Log("Updating drive database...");
            var noEntityDrives = _drives.Find(x => _entityBackend.GetEntity(x.EntityId) == null);

            foreach (var drive in noEntityDrives)
            {
                Plex.Objects.Logger.Log($"Removing drive: //{drive.EntityId}/{drive.Mountpoint}. Entity not found.");
                var mount = _mounts.FirstOrDefault(x => x.DriveNumber == drive.Mountpoint && x.VolumeLabel == drive.VolumeLabel && x.SessionID == drive.EntityId);
                if (mount != null)
                {
                    mount.Dispose();
                    _mounts.Remove(mount);
                }
                File.Delete(Path.Combine(_drivePath, drive.ImagePath));
                _drives.Delete(x => x.Id == drive.Id);
            }
            Plex.Objects.Logger.Log("Mounting newly-created drives...");
            foreach (var drive in _drives.Find(x => _mounts.FirstOrDefault(y => y.DriveNumber == x.Mountpoint && y.SessionID == x.EntityId && y.VolumeLabel == x.VolumeLabel) == null))
            {
                Plex.Objects.Logger.Log($"Mounting {drive.ImagePath} to //{drive.EntityId}/{drive.Mountpoint}...");
                var fat = new PlexFATDriveMount(new MountInformation
                {
                    DriveNumber   = drive.Mountpoint,
                    ImageFilePath = Path.Combine(_drivePath, drive.ImagePath),
                    Specification = DriveSpec.PlexFAT,
                    VolumeLabel   = drive.VolumeLabel
                }, drive.EntityId);
                fat.EnsureDriveExistence();
                _mounts.Add(fat);
            }
        }
Example #2
0
        /// <summary>
        /// Batch equivalent of <see cref="Dequeue"/>
        /// </summary>
        /// <param name="batchSize">The maximum number of items to dequeue</param>
        /// <returns>The items found or an empty collection (never null)</returns>
        public List <QueueEntry <T> > Dequeue(int batchSize)
        {
            if (_transactional)
            {
                lock (_dequeueLock)
                {
                    var items = _collection.Find(x => !x.IsCheckedOut, 0, batchSize);

                    // Capture the result before changing IsCheckedOut, otherwise items is being changed
                    var result = new List <QueueEntry <T> >(items);

                    foreach (var item in result)
                    {
                        item.IsCheckedOut = true;
                        _collection.Update(item);
                    }

                    return(result);
                }
            }
            else
            {
                var items  = _collection.Find(x => true, 0, batchSize);
                var result = new List <QueueEntry <T> >(items);

                foreach (var item in items)
                {
                    _collection.Delete(new BsonValue(item.Id));
                }

                return(result);
            }
        }
        private void comboItemSelection_Changed(object sender, SelectionChangedEventArgs e)
        {
            if (comboItem1.SelectedIndex != -1 & comboItem2.SelectedIndex != -1)
            {
                using (var db = new LiteDatabase("pcclinic.db"))
                {
                    LiteCollection <Inventory> inventoryCollection = db.GetCollection <Inventory>("inventory");

                    IEnumerable <Inventory> itemId = inventoryCollection.Find(x => x.Id == int.Parse(Functions.GetUntilOrEmpty(comboItem1.SelectedValue.ToString(), ")")));
                    foreach (var item in itemId)
                    {
                        lblName1.Content     = item.ItemName.ToString();
                        lblType1.Content     = item.ItemDescription;
                        lblQuantity1.Content = item.ItemQuantity;
                        lblValue1.Content    = item.ItemValue;
                    }
                    var itemId2 = inventoryCollection.Find(x => x.Id == int.Parse(comboItem2.SelectedValue.ToString().ToCharArray()[0].ToString()));
                    foreach (var item in itemId2)
                    {
                        lblName2.Content     = item.ItemName;
                        lblType2.Content     = item.ItemDescription;
                        lblQuantity2.Content = item.ItemQuantity;
                        lblValue2.Content    = item.ItemValue;
                    }


                    //lblName1.Content = comboItem1.SelectedValue.ToString(); lblName2.Content = comboItem2.SelectedValue;
                    //lblType1.Content = comboItem1.SelectedValue.ToString(); lblType2.Content = comboItem2.SelectedValue;
                    //lblQuantity1.Content = comboItem1.SelectedValue.ToString(); lblQuantity2.Content = comboItem2.SelectedValue;
                    //lblValue1.Content = comboItem1.SelectedValue.ToString(); lblValue2.Content = comboItem2.SelectedValue;
                }
            }
        }
Example #4
0
        private void liImageItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (liImageItems.SelectedItem is string selected)
            {
                var item = liteCollection.Find(x =>
                                               x.Id == selected).FirstOrDefault();
                if (item != null)
                {
                    lblImageItemName.Text = item.Id;
                    liTagsOfItem.Items.Clear();
                    txbTagEdit.Text = "";

                    using (var ms = new MemoryStream())
                    {
                        liteDatabase.FileStorage.Download(item.Id, ms);
                        pictureBox2.Image = Image.FromStream(ms);

                        foreach (var itemTag in item.Tags)
                        {
                            liTagsOfItem.Items.Add(itemTag);
                        }
                    }
                }
            }
        }
Example #5
0
        private void ClientComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            List <TimesheetRecord> clientRecords = m_timesheets.Find(t => t.Client == ClientComboBox.Text).ToList();
            List <string>          projects      = clientRecords.Select(t => t.Project).Distinct().ToList();

            ProjectComboBox.DataSource = projects;
        }
        public async Task <List <Trade> > GetClosedTradesAsync()
        {
            var trades = _ordersAdapter.Find(x => !x.IsOpen).ToList();
            var items  = Mapping.Mapper.Map <List <Trade> >(trades);

            return(items);
        }
        public async Task <List <Trader> > GetAvailableTradersAsync()
        {
            var traders = _traderAdapter.Find(x => !x.IsBusy && !x.IsArchived).ToList();
            var items   = Mapping.Mapper.Map <List <Trader> >(traders);

            return(items);
        }
Example #8
0
 public ChatMessage[] GetAllTowardsEntity(string recipient)
 {
     if (_entityBackend.GetEntity(recipient) == null)
     {
         return(new ChatMessage[0]);
     }
     return(_messages.Find(x => x.RecipientEntityId == recipient).OrderByDescending(x => x.Timestamp).ToArray());
 }
        /// <summary>
        /// Query the blockchain API if there is any new unprocessed transactions.
        /// </summary>
        /// <returns>True if there is a new transaction. Otherwise returns false.</returns>
        public async Task <bool> IsNewTransactionAvailable()
        {
            var txs = await api.GetAllTransaction(contract.OwnerPublicAddress, contract.LastSyncedBlock);

            var ledgers = ledger.Find(l => l.Status == ProcessStatus.NotProcessed);

            return((txs.txs.Count() > 0) || (ledgers.Count() > 0));
        }
        /// <summary>
        /// Get first entity or default type value.
        /// </summary>
        /// <param name="predicate">Predicate for filter collection.</param>
        /// <param name="take">Number items in response.</param>
        /// <param name="skip">Shifting elements from the beginning of the list.</param>
        /// <typeparam name="T">Type of entity.</typeparam>
        public IEnumerable <T> Find(Expression <Func <T, bool> > predicate, int skip = 0, int take = int.MaxValue)
        {
            if (predicate == null)
            {
                return(m_Collection.FindAll());
            }

            return(m_Collection.Find(predicate, skip, take));
        }
        public Task <TUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();

            var query = _users.Find(u => u.NormalizedUserName == normalizedUserName).FirstOrDefault();

            return(Task.FromResult(query));
        }
Example #12
0
        public async Task <IEnumerable <Mediafile> > GetTracks()
        {
            IEnumerable <Mediafile> collection = null;
            await Core.SharedLogic.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                collection = tracks.Find(LiteDB.Query.All());
            });

            return(collection);
        }
        public async Task <IEnumerable <Mediafile> > GetTracks()
        {
            IEnumerable <Mediafile> collection = null;
            await Core.CoreMethods.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                Core.CoreMethods.LibVM.SongCount = tracks.Count();
                collection = tracks.Find(LiteDB.Query.All());
            });

            return(collection);
        }
Example #14
0
        /* return all backup of user "clientID"
         * if there are no backups, returns an empty list */
        public static List <BackupRecord> getBackupList(string clientID, string timestamp)
        {
            List <BackupRecord> backupList = new List <BackupRecord>();

            using (var db = new LiteDatabase(DB_PATH))
            {
                // Get a collection (or create, if doesn't exist)
                LiteCollection <BackupRecord> col = db.GetCollection <BackupRecord>(DB_BACKUPS);

                // Index document using document userID property
                col.EnsureIndex(x => x.userID);

                // find all backup records with userID = clientID
                IEnumerable <BackupRecord> results;

                //retreive all backups if timestamp is null
                if (timestamp == null)
                {
                    results = col.Find(x => x.userID.Equals(clientID));
                }
                else
                {
                    results = col.Find(x => x.userID.Equals(clientID) && x.timestamp.Equals(timestamp));
                }

                Console.WriteLine("totale record trovati " + results.LongCount <BackupRecord>());

                //if (results.LongCount<BackupRecord>() <= 0)
                //throw new Exception("No backup found");

                //add backupRecord to list
                for (int i = 0; i < results.LongCount <BackupRecord>(); i++)
                {
                    //string recordString = JsonConvert.SerializeObject(results.ElementAt<BackupRecord>(i));
                    //BackupRecord record = JsonConvert.DeserializeObject<BackupRecord>(recordString);
                    BackupRecord record = results.ElementAt <BackupRecord>(i);
                    backupList.Add(record);

                    //fix for relativePath= null (caused by SQL logic)
                    foreach (myFileInfo info in record.fileInfoList)
                    {
                        if (info.RelativePath == null)
                        {
                            info.RelativePath = "";
                        }
                    }

                    Console.WriteLine("record " + i + " : " + record.userID + " " + record.timestamp);
                }
            }

            return(backupList);
        }
Example #15
0
        public void Get(ICollectionRequest req)
        {
            var q       = HttpUtility.ParseQueryString(req.Query);
            var name    = q.Get("name")?.ToLower();
            var country = q.Get("country");

            int.TryParse(q.Get("from"), out int from);
            int.TryParse(q.Get("limit"), out int limit);
            if (from < 0)
            {
                from = 0;
            }
            if (limit <= 0)
            {
                limit = 10;
            }

            // Put a max on the query result size
            if (limit > 50)
            {
                req.InvalidQuery("Limit must be 50 or less.");
                return;
            }

            IEnumerable <Customer> result = null;

            if (String.IsNullOrEmpty(name))
            {
                if (String.IsNullOrEmpty(country))
                {
                    result = customers.Find(Query.All("Name"), from, limit);
                }
                else
                {
                    result = customers.Find(Query.And(Query.All("Name"), Query.Where("Country", v => v.AsString == country)), from, limit);
                }
            }
            else
            if (String.IsNullOrEmpty(country))
            {
                result = customers.Find(Query.StartsWith("Name", name), from, limit);
            }
            else
            {
                result = customers.Find(Query.And(Query.StartsWith("Name", name), Query.Where("Country", v => v.AsString == country)), from, limit);
            }

            // Create a normalized query string with the properties in a set order.
            var normalizedQuery = String.Format("name={0}&country={1}&from={2}&limit={3}", name ?? "", country ?? "", from, limit);

            req.Collection(result.Select(c => new Ref("search.customer." + c.Id)), normalizedQuery);
        }
Example #16
0
        private int DeleteProgram(int programId, int groupId)
        {
            int deletedCount = _programsCollection.Delete(x => x.Id == programId);
            //is this the last program for program's group?
            IEnumerable <AudioProgram> programs = _programsCollection.Find(x => x.GroupId.Equals(groupId));

            if (programs.Count() == 0)
            {
                //there are no programs with groupId, so delete the group
                _groupsCollection.Delete(x => x.Id.Equals(groupId));
            }
            return(deletedCount);
        }
Example #17
0
 /// <summary>
 /// 获取菜单显示数据
 /// </summary>
 /// <returns></returns>
 public IEnumerable <TaskMenu> MenuData(string projectId)
 {
     return(_col.Find(t => t.ProjectId == projectId)
            .GroupBy(p => (p.ComponentName, p.ComponentId), (key, holeGroup) => new TaskMenu {
         Name = key.ComponentName, Id = key.ComponentId, Count = holeGroup.Count()
     }));
     //.GroupBy(p => p.ComponentName, (key, holeGroup) => new TaskMenu { Name = key, Id = key, Count = holeGroup.Count()});
     //.GroupBy(p => p.ComponentName, (key, holeGroup) => new TaskMenu { Name = key, Id = key, Bridge = holeGroup.Select(h => new entity.MenuData { Id = h.Id, Name = h.BridgeName })});
     //List<MenuData> menuData = new List<MenuData>();
     //foreach (var item in obj)
     //{
     //  menuData.Add(new MenuData { Id = item.Id, Name = item.BridgeName });
     //}
 }
 public async Task <IEnumerable <T> > GetRecords <T>()
 {
     return(await Task.Run(() =>
     {
         var records = currentCollection.Find(Query.All());
         if (records.Any())
         {
             return records.Cast <T>();
         }
         else
         {
             return null;
         }
     }).ConfigureAwait(false));
 }
Example #19
0
 public Task <IEnumerable <T> > GetRangeOfRecords <T>(long index, long limit)
 {
     return(Task.Run(() =>
     {
         var records = currentCollection.Find(Query.All(), (int)index, (int)limit);
         if (records.Any())
         {
             return records.Cast <T>();
         }
         else
         {
             return null;
         }
     }));
 }
Example #20
0
        /// <inheritdoc/>
        public override IEnumerable <Tuple <HashDigest <SHA256>, long> > IterateStateReferences(
            Guid chainId,
            Address address,
            long?highestIndex,
            long?lowestIndex,
            int?limit)
        {
            highestIndex = highestIndex ?? long.MaxValue;
            lowestIndex  = lowestIndex ?? 0;

            if (highestIndex < lowestIndex)
            {
                var message =
                    $"highestIndex({highestIndex}) must be greater than or equal to " +
                    $"lowestIndex({lowestIndex})";
                throw new ArgumentException(
                          message,
                          nameof(highestIndex));
            }

            string collId = StateRefId(chainId);
            LiteCollection <StateRefDoc> coll = _db.GetCollection <StateRefDoc>(collId);
            string addressString = address.ToHex().ToLower(CultureInfo.InvariantCulture);
            IEnumerable <StateRefDoc> stateRefs = coll.Find(
                Query.And(
                    Query.All("BlockIndex", Query.Descending),
                    Query.EQ("AddressString", addressString),
                    Query.Between("BlockIndex", lowestIndex, highestIndex)
                    ), limit: limit ?? int.MaxValue
                );

            return(stateRefs
                   .Select(doc => new Tuple <HashDigest <SHA256>, long>(doc.BlockHash, doc.BlockIndex)));
        }
Example #21
0
        /// <summary>Gets all Entries matching the search criteria.
        /// The entries are sorted by last playtime descending.</summary>
        /// <param name="search">All search criteria.</param>
        /// <returns>A list of all found entries.</returns>
        public IEnumerable <AudioLogEntry> Search(SeachQuery search)
        {
            if (search == null)
            {
                throw new ArgumentNullException(nameof(search));
            }

            if (search.MaxResults <= 0)
            {
                return(Enumerable.Empty <AudioLogEntry>());
            }

            var query = Query.All(nameof(AudioLogEntry.Timestamp), Query.Descending);

            if (!string.IsNullOrEmpty(search.TitlePart))
            {
                query = Query.And(query, Query.Where(ResourceTitleQueryColumn, val => val.AsString.ToLowerInvariant().Contains(search.TitlePart)));
            }

            if (search.UserId.HasValue)
            {
                query = Query.And(query, Query.EQ(nameof(AudioLogEntry.UserInvokeId), (long)search.UserId.Value));
            }

            if (search.LastInvokedAfter.HasValue)
            {
                query = Query.And(query, Query.GTE(nameof(AudioLogEntry.Timestamp), search.LastInvokedAfter.Value));
            }

            return(audioLogEntries.Find(query, 0, search.MaxResults));
        }
Example #22
0
 public IEnumerable <Minyan> getNearbyMinyan(double latitude, double longitude, double degreesAroundToCheck)
 {
     //To keep it simple add 180 to each value to prevent negatives and then compare
     latitude  = latitude + 90;
     longitude = longitude + 180;
     return(mMinyan.Find((n) => ((((latitude > n.Latitude + 80) ? latitude - (n.Latitude + 80) : (n.Latitude + 80) - latitude) <= degreesAroundToCheck) || (((longitude > n.Longitude + 180) ? longitude - (n.Latitude + 180) : (n.Longitude + 180) - longitude) <= degreesAroundToCheck))));
 }
Example #23
0
 private List <SubjectValueMod> FindMods(LiteCollection <SubjectValueMod> col, uint subjectId)
 {
     col.EnsureIndex(x => x.SubjectID);
     return(col.Find(x => x.SubjectID == subjectId)
            .OrderBy(x => x.Timestamp)
            .ToList());
 }
Example #24
0
        /// <summary>
        /// 添加一条数据
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>成功:返回项目中所有操作员,失败:放回状态false</returns>
        public new ReturnPost Insert(T data)
        {
            if (_col.FindOne(item => item.sName == data.sName) == null)
            {
                _col.Insert(data);

                return(new ReturnPost()
                {
                    Data = _col.Find(item => item.ParentId == data.ParentId), Message = true
                });
            }
            return(new ReturnPost()
            {
                Message = false
            });
        }
Example #25
0
        /// <summary>
        /// 删除远程连接条目
        /// </summary>
        public static void Delete(RemoteType type, string id)
        {
            if (type == RemoteType.dir)
            {
                var dirItems = _tableDirectory.Find(m => m.ParentId == id);
                foreach (var item in dirItems)
                {
                    Delete(RemoteType.dir, item.Id);
                }
                var linkItems = _tableRemoteLink.Find(m => m.ParentId == id);
                foreach (var item in linkItems)
                {
                    Delete((RemoteType)item.Type, item.Id);
                }
                _tableDirectory.Delete(id);
            }
            if (_tableRemoteLink.Delete(id))
            {
                switch (type)
                {
                case RemoteType.rdp:
                    _tableSetting_rdp.Delete(id);
                    break;

                case RemoteType.ssh:
                    _tableSetting_ssh.Delete(id);
                    break;

                case RemoteType.telnet:
                    break;
                }
            }
        }
Example #26
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 #27
0
        /// <inheritdoc/>
        public override IEnumerable <Tuple <HashDigest <SHA256>, long> > IterateStateReferences(
            Guid chainId,
            string key,
            long?highestIndex,
            long?lowestIndex,
            int?limit)
        {
            highestIndex = highestIndex ?? long.MaxValue;
            lowestIndex  = lowestIndex ?? 0;

            if (highestIndex < lowestIndex)
            {
                var message =
                    $"highestIndex({highestIndex}) must be greater than or equal to " +
                    $"lowestIndex({lowestIndex})";
                throw new ArgumentException(
                          message,
                          nameof(highestIndex));
            }

            string collId = StateRefId(chainId);
            LiteCollection <StateRefDoc> coll      = _liteDb.GetCollection <StateRefDoc>(collId);
            IEnumerable <StateRefDoc>    stateRefs = coll.Find(
                Query.And(
                    Query.All(nameof(StateRefDoc.BlockIndex), Query.Descending),
                    Query.EQ(nameof(StateRefDoc.StateKey), key),
                    Query.Between(nameof(StateRefDoc.BlockIndex), lowestIndex, highestIndex)
                    ), limit: limit ?? int.MaxValue
                );

            return(stateRefs
                   .Select(doc => new Tuple <HashDigest <SHA256>, long>(doc.BlockHash, doc.BlockIndex)));
        }
Example #28
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 #29
0
        public string Get(int?count)
        {
            if (count == null)
            {
                count = 5;
            }
            else if (count > 50)
            {
                count = 50;
            }
            else if (count < 1)
            {
                return("[]");
            }
            var result = new List <Dictionary <string, string> >();

            _collection.Find(Query.All("KillToDeathRatio._value", Query.Descending), 0, count.Value).ForEach(x =>
            {
                if (x["KillToDeathRatio._deaths"].AsInt32 == 0 || x["TotalMatchesPlayed._count"].AsInt32 < 10)
                {
                    return;
                }
                var dict = new Dictionary <string, string>
                {
                    { "name", x["PlayerName"].AsString },
                    { "killToDeathRatio", x["KillToDeathRatio._value"].AsString }
                };
                result.Add(dict);
            });
            return(JsonConvert.SerializeObject(result));
        }
        public async Task SaveWalletTransactionAsync(WalletTransaction walletTransaction)
        {
            var item = Mapping.Mapper.Map <WalletTransactionAdapter>(walletTransaction);
            WalletTransactionAdapter checkExist = _walletTransactionsAdapter.Find(x => x.Id.Equals(item.Id)).FirstOrDefault();

            _walletTransactionsAdapter.Upsert(item);
        }