//by serach public List <T> GetPageEntities(int pageIndex, int PageSize, Expression <Func <T, bool> > wheresearch) { try { //int result; using (var db = new LiteRepository(conStr)) { int totalCount = db.Query <T>().Count(); //计算页码 int pages = (int)Math.Ceiling((double)totalCount / (double)PageSize); if (pageIndex > pages) { return(null); } else { //Reverse 倒序排列 //var result = db.Query<T>().Where(wheresearch).ToList().Skip((pageIndex - 1) * PageSize).Take(PageSize).Reverse().ToList(); var result = db.Query <T>().Where(wheresearch).Skip((pageIndex - 1) * PageSize).ToList().Take(PageSize).Reverse().ToList(); return(result); } } } catch { return(null); } }
public List <Trade> GetBuysForPairAndQuantity(decimal sellPrice, decimal quantity, string baseCcy, string terms) { var enumerable = _db.Query <Trade>() .Where(x => x.Base == baseCcy && x.Terms == terms) .ToEnumerable(); var onlyBuys = enumerable.Where(x => x.Side == TradeSide.Buy); var tradesForPair = onlyBuys.OrderByDescending(x => x.TimeStamp); var trades = new List <Trade>(); var quanityChecked = 0m; foreach (var trade in tradesForPair) { if (quanityChecked >= quantity) { continue; } trades.Add(trade); quanityChecked = quanityChecked + trade.QuantityOfTrade; } return(trades); }
/// <summary> /// Stores a Key-Value pair to the /// persistence database. /// </summary> public static void SetConfigData(string key, string data) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException("key"); } using (var db = new LiteRepository(AppSettingsDBName)) { if (db.Query <AppSetting>().Where(p => p.Key == key).Exists()) { var existing = db.Query <AppSetting>().Where(p => p.Key == key).First(); existing.Value = data; db.Update <AppSetting>(existing); } else { db.Insert(new AppSetting() { Key = key, Value = data }); } } }
public List <T> GetRawDtos <T, K>(Expression <Func <T, bool> > predicate = null, Expression <Func <T, K> > orderBy = null, int?skip = null, int?limit = null) where T : IHasId <T> { var query = repo.Query <T>(); if (predicate != null) { query = query.Where(predicate); } if (orderBy != null) { query = query.OrderBy(orderBy); } if (skip != null || limit != null) { ILiteQueryableResult <T> result = null; if (skip != null) { result = query.Skip(skip.Value); } if (limit != null) { result = query.Limit(limit.Value); } return(result.ToList()); } return(query.ToList()); }
public Task <App[]> GetApps(AppQuery query) { var q = _liteRepository.Query <App>(); if (!string.IsNullOrEmpty(query.Id)) { q = q.Where(a => a.Id == query.Id); } return(Task.FromResult(q.OrderBy(a => a.IsSystemApp).ToArray())); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var allTimeUpdate = new List <decimal>(); while (!stoppingToken.IsCancellationRequested) { var stopWatch = new Stopwatch(); var singleTimeUpdate = new List <decimal>(); using (_repository) { var requiredGames = _repository.Query <RequiredGame>().ToList(); Console.WriteLine($"[{DateTime.Now:O}] Будет обновлено {requiredGames.Count} игр."); foreach (var requiredGame in requiredGames) { stopWatch.Restart(); var game = _repository.Query <Game>() .Include(g => g.Cards) .Where(g => g.SteamAppId == requiredGame.SteamAppId) .FirstOrDefault(); if (game is null) { game = await _gameInfoLoader.GetInfo(requiredGame.SteamAppId); } else { game = await _gameInfoLoader.UpdateInfo(game); } game.Cards.ForEach(card => _repository.Upsert(card)); _repository.Upsert(game); stopWatch.Stop(); singleTimeUpdate.Add((decimal)stopWatch.Elapsed.TotalMilliseconds); Console.WriteLine($"Игра {game.Name} обновлена за {stopWatch.Elapsed:g}."); } } if (singleTimeUpdate.Count > 0) { var singleAvgUpdateTime = (double)singleTimeUpdate.Average(); Console.WriteLine( $"Среднее время обновления игр за последний заход составило {TimeSpan.FromMilliseconds(singleAvgUpdateTime):g}."); allTimeUpdate.AddRange(singleTimeUpdate); var avgUpdateTime = (double)allTimeUpdate.Average(); Console.WriteLine( $"Общее среднее время обновления игр составляет {TimeSpan.FromMilliseconds(avgUpdateTime):g}."); } else { Console.WriteLine("В списке нет игр на обновление."); } await Task.Delay(TimeSpan.FromMinutes(_serviceOptions.UpdateDelay), stoppingToken); } }
public async Task <List <Item> > GetItemList() { var items = new List <Item>(); var weapons = _repository.Query <Weapon>().ToList(); var hats = _repository.Query <Hat>().ToList(); items.AddRange(weapons); items.AddRange(hats); return(await Task.FromResult(items)); }
IList <IItemActive> IDataService.GetItemActive() { IList <IItemActive> result = new List <IItemActive>(); var result2 = repo.Query <ItemActive>().ToList(); foreach (var item in result2) { result.Add(item); } return(result); }
public void Read_bson_with_more_fields_then_entity() { using var repo = new LiteRepository(dbFile).WithUtcDate(); repo.Insert(new BigEntity { Field1 = "111", Field2 = "222" }, "col"); var e = repo.Query <SmallEntity>("col").First(); e.Field1.Should().Be("111"); repo.Update(e, "col"); var e2 = repo.Query <BigEntity>("col").First(); e2.Field1.Should().Be("111"); e2.Field2.Should().BeNullOrEmpty(); }
public Task <ContentType[]> GetContentTypes(ContentTypeQuery query) { var q = _liteRepository.Query <ContentType>(); if (!string.IsNullOrEmpty(query.AppId)) { if (query.IncludeGlobalContentTypes) { q = q.Where(ct => ct.AppId == query.AppId || ct.AppId == null); } else { q = q.Where(ct => ct.AppId == query.AppId); } } if (!string.IsNullOrEmpty(query.Id)) { q = q.Where(ct => ct.Id == query.Id); } if (!string.IsNullOrEmpty(query.Name)) { q = q.Where(ct => ct.Name == query.Name); } var result = q.ToArray().OrderByDescending(ct => ct.AppId).OrderBy(ct => ct.Name).ToArray(); return(Task.FromResult(result)); }
public IEnumerable <T> GetAll() { using (var db = new LiteRepository(ConnectionString)) { return(db.Query <T>().ToEnumerable()); } }
public T Get(string id) { using (var db = new LiteRepository(ConnectionString)) { return(db.Query <T>().SingleById(id)); } }
public void Should_store_documents_with_int_key_in_sorted_order() { using (var repo = new LiteRepository(dbFile).WithUtcDate()) { repo.Insert(new EntityInt { Id = 5 }); repo.Insert(new EntityInt { Id = 4 }); repo.Insert(new EntityInt { Id = 7 }); repo.Insert(new EntityInt { Id = 3 }); } using (var repo = new LiteRepository(dbFile).WithUtcDate()) { var docs = repo.Query <EntityInt>().ToList(); docs[0].Id.Should().Be(3); docs[1].Id.Should().Be(4); docs[2].Id.Should().Be(5); docs[3].Id.Should().Be(7); } }
public Task Handle(OrderSubmission message, IMessageHandlerContext context) { var movie = db.Query <Movie>().Where(s => s.Id == message.Movie).SingleOrDefault(); var theater = TheatersContext.GetTheaters().Single(s => s.Id == message.Theater); var screenMessage = "Thank you for your order.<br /><br />"; screenMessage += "<table>"; screenMessage += $"<tr><td><b>Movie</b></td><td>: {movie.Title}</td></tr>"; screenMessage += $"<tr><td><b>Theater</b></td><td>: {theater.Name}</td></tr>"; screenMessage += $"<tr><td><b>Time</b></td><td>: {message.MovieTime}</td></tr>"; screenMessage += $"<tr><td><b>Tickets</b></td><td>: {message.NumberOfTickets}</td></tr>"; screenMessage += "</tr></table><br /><br />"; if (message.Approved) { screenMessage += $"Your order will soon arrive in your email."; } else { // For simplicity, it's always 2 weeks in advance. screenMessage += $"On <b>{DateTime.Now.AddDays(14):M}</b>, you'll receive an email and hear if you have been selected."; } var returnMessage = new { MovieTitle = movie.Title }; return(ticketHubContext.Clients.All.SendAsync("OrderSubmission", screenMessage)); }
public List <DeviceValue> GetValuesForDevice(int deviceId, DateTime?fromDateTime, DateTime?toDateTime) { var startDateTime = DateTime.Now.AddHours(2); var endDateTime = DateTime.Now; if (fromDateTime.HasValue) { startDateTime = fromDateTime.Value; } if (toDateTime.HasValue) { endDateTime = toDateTime.Value; } using (var db = new LiteRepository(_pathToRepo)) { _logging.LogDebug($"LiteDbRepo: selecting values for deviceId {deviceId} with starDateTime {startDateTime.ToString()} and endDateTime {endDateTime.ToString()}"); var foundValues = db.Query <DeviceValue>(DeviceValuesTable) .Where(x => x.DeviceId == deviceId && x.DateTimeOfMeasurment >= startDateTime && x.DateTimeOfMeasurment <= endDateTime) .ToList() .OrderBy(x => x.DateTimeOfMeasurment) .ToList(); return(foundValues); } }
public async Task Handle(OrderSubmission message, IMessageHandlerContext context) { if (!context.MessageHeaders.TryGetValue("SignalRConnectionId", out var userConnectionId)) { logger.LogError("Could not find SignalR ConnectionId from message headers."); return; } var movie = db.Query <Movie>().Where(s => s.Id == message.Movie).SingleOrDefault(); var theater = TheatersContext.GetTheaters().Single(s => s.Id == message.Theater); if (movie.TicketType == TicketType.DrawingTicket) { return; } var ticket = new { TheaterId = theater.Id.ToString(), Theater = theater.Name, MovieId = movie.Id.ToString(), MovieTitle = movie.Title, Time = message.MovieTime, NumberOfTickets = message.NumberOfTickets }; await ticketHubContext.Clients.Client(userConnectionId).SendAsync("OrderedRegularTicket", ticket); }
public IReadOnlyList <PvpApiRowModel> Get(BlizzardLocale locale = BlizzardLocale.All, WowPvpBracket bracket = WowPvpBracket.All, WowClass wowClass = WowClass.All, WowSpec spec = WowSpec.All, uint skip = 0, uint take = 100) { var query = _liteDbRepo.Query <PvpApiRowModel>(); if (locale != BlizzardLocale.All) { query = query.Where(row => row.Locale == (byte)locale); } if (bracket != WowPvpBracket.All) { query = query.Where(row => row.Bracket == (byte)bracket); } if (wowClass != WowClass.All) { query = query.Where(row => row.ClassId == (byte)wowClass); } if (spec != WowSpec.All) { query = query.Where(row => row.SpecId == (ushort)spec); } query = query.Where(Query.All("Rating")) .Where(Query.All("Name")) .Skip((int)skip) .Limit((int)take); IReadOnlyList <PvpApiRowModel> result = query.ToList(); return(result); }
/// <summary> /// Gets recorded chat rooms. /// </summary> /// <returns>Chat room list.</returns> public static List <ChatRoom> ListChatRooms() { using (var db = new LiteRepository(@"MyData.db")) { return(db.Query <ChatRoom>().ToList()); } }
private async Task MessageReceived(SocketMessage rawMessage) { // Ignore system messages and messages from bots if (!(rawMessage is SocketUserMessage message)) { return; } if (message.Source != MessageSource.User) { return; } var context = new SocketCommandContext(_discord, message); var guild = _repository.Query <DiscordGuild>() .Where(g => g.Id == context.Guild.Id) .FirstOrDefault(); var prefix = _config.BotConfig.Prefix; if (guild != null) { prefix = guild.Prefix; } int argPos = 0; // if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos)) return; if (!message.HasStringPrefix(prefix, ref argPos)) { return; } await _commands.ExecuteAsync(context, argPos, _provider); }
public IList <SyncAgentTask> GetAll() { using (var db = new LiteRepository(StoragePath)) { return(db.Query <SyncAgentTask>().ToList()); } }
public IEnumerable <Client> GetConnectedClients() { using (var db = new LiteRepository(ConnectionString)) { return(db.Query <Client>().Where(x => x.ConnenctionId != null).ToList()); } }
public IEnumerable <Registro> Listar(Expression <Func <Registro, bool> > predicate) { EnsureNotDisposed(); if (predicate != null) { return(_repositorio .Query <Registro>(ColecaoRegistros) .Where(predicate) .ToList()); } return(_repositorio .Query <Registro>(ColecaoRegistros) .ToList()); }
/// <summary> /// After ticket registration, immediately verify if it's a lottery ticket. /// </summary> public async Task ReportOnLottery(MovieTicket ticket, string connectionId) { var movieId = Guid.Parse(ticket.MovieId); var theaterId = Guid.Parse(ticket.TheaterId); var movie = db.Query <Movie>() .Where(s => s.Id == movieId) .Single(); if (movie.TicketType == TicketType.DrawingTicket) { var theater = TheatersContext.GetTheaters().Single(s => s.Id == theaterId); var message = new { Theater = theater.Name, MovieTitle = movie.Title, Time = ticket.Time, NumberOfTickets = ticket.NumberOfTickets, DrawingDate = DateTime.Now.AddDays(14).ToString("dddd, dd MMMM", CultureInfo.InvariantCulture) }; logger.LogInformation("Sending OrderedLotteryTicket", message); await hub.Clients.Client(connectionId).SendAsync("OrderedLotteryTicket", message); } }
public void Apply(LiteRepository repository) { List <ProfileEntity> profiles = repository.Query <ProfileEntity>().ToList(); foreach (ProfileEntity profileEntity in profiles) { foreach (FolderEntity profileEntityFolder in profileEntity.Folders) { profileEntityFolder.Enabled = true; foreach (LayerEffectEntity layerEffectEntity in profileEntityFolder.LayerEffects) { layerEffectEntity.Enabled = true; } } foreach (LayerEntity profileEntityLayer in profileEntity.Layers) { profileEntityLayer.Enabled = true; foreach (LayerEffectEntity layerEffectEntity in profileEntityLayer.LayerEffects) { layerEffectEntity.Enabled = true; } } repository.Upsert(profileEntity); } }
static void Main(string[] args) { // Open database (or create if doesn't exist) using (var db = new LiteRepository(@"../../../Customer.litedb")) { var id = db.Insert(new Customer() { Name = "John Doe", Phones = new string[] { "8000-0000", "9000-0000" }, Age = 39, IsActive = true }); var customer = db.SingleById <Customer>(99); customer.Name = "Very Old"; customer.Age = 500; var zz = db.Update(customer); // query using fluent query var result = db.Query <Customer>() .Where(x => x.Age > 499) // used indexes query .ToList(); } }
/// <summary> /// Returns new instance of LiteQueryable that provides all method to query any entity inside collection. Use fluent API to apply filter/includes an than run any execute command, like ToList() or First() /// </summary> public LiteQueryable <T> Query <T>(string collectionName = null) { using (var db = new LiteRepository(_configService.ConnectionString)) { return(db.Query <T>(collectionName)); } }
public async Task <IActionResult> IndexModel() { var user = await _userManager.GetUserAsync(User); var allitems = _db.Query <WorkingLogItem>().ToList() .Where(item => item.UserId == user.Id); var model = new JArray(allitems .OrderByDescending(item => item.Date) .ThenBy(item => item.Project) .ThenBy(item => item.WorkItem) .ThenBy(item => item.Type) .Select(item => new JObject { ["id"] = item.Id.ToString(), ["date"] = item.Date.ToString("yy/MM/dd"), ["project"] = item.Project, ["workItem"] = item.WorkItem, ["type"] = item.Type, ["hours"] = item.Hours, ["detail"] = item.Detail })).ToString(Formatting.None); return(Content(model)); }
public void Double() { var r = new Random(); using var repo = new LiteRepository(nameof(Double)); repo.Insert(new RecordDouble()); Assert.Equal(5.5d, repo.Query <RecordDouble>().OrderByDescending(x => x.Id).First().Double); }
public int GetMaxSettingsId() { using (var repository = new LiteRepository(_connectionStringProvider.ConnectionString)) { var entities = repository.Query <Settings>().ToList(); return(entities == null || entities.Count == 0 ? 0 : entities.Max(e => e.Id)); } }
public IEnumerable <EventStreamDataModel> GetStream() { using (var db = new LiteRepository(_context.Context)) { var dbModel = db.Query <EventStreamDataModel>().ToList(); return(dbModel); } }