public async Task <ReadingCategory <ReadingWord> > Add(ReadingCategory <ReadingWord> toAdd)
        {
            var dto = toAdd.ToDTO(ProgramId);

            if (dto.ActivityStatus.Type == ActivityStatusType.Planned && dto.ActivityStatus.SortingIndex < 0)
            {
                await SetSortIndexToLast(dto);
            }

            var nbrOfExistingCategoriesWithName = await _session.Query <ReadingCategoryDTO <ReadingWordDTO> >()
                                                  .CountAsync(x => x.Title.StartsWith(dto.Title));

            if (nbrOfExistingCategoriesWithName > 0)
            {
                dto.Title = dto.Title + " " + (nbrOfExistingCategoriesWithName + 1);
            }

            foreach (var card in dto.Cards)
            {
                var dictionaryResults = await _dictionary.LookupWord(card.Text);

                card.BaseDictionaryWord = dictionaryResults.FirstOrDefault()?.Word ?? card.Text;
            }

            await _session.StoreAsync(dto);

            await _session.SaveChangesAsync();

            return(dto.ToCategory());
        }
예제 #2
0
        /// <summary>
        /// Gets all resources.
        /// </summary>
        /// <returns></returns>
        public async Task <Resources> GetAllResourcesAsync()
        {
            var apiQuery = from api in _session.Query <Entity.ProtectResource>()
                           .Expand(string.Join(",", _expandApiProperttyList))
                           select api;

            var apiScopeQuery = from scope in _session.Query <Entity.ApiScope>()
                                .Expand(string.Join(",", _expandApiScopeProperttyList))
                                select scope;

            var identityQuery = from identity in _session.Query <Entity.IdentityResource>()
                                .Expand(string.Join(",", _expandIdentityProperttyList))
                                select identity;

            var apiList = await apiQuery.ToListAsync().ConfigureAwait(false);

            var apiScopeList = await apiScopeQuery.ToListAsync().ConfigureAwait(false);

            var identityList = await identityQuery.ToListAsync().ConfigureAwait(false);

            var apiResourceList = await ToApiResourceList(apiList).ConfigureAwait(false);

            var apiScopeResourceList = await ToApiScopeList(apiScopeList).ConfigureAwait(false);

            var identityResourceList = await ToIdentityResourceList(identityList).ConfigureAwait(false);

            return(new Resources
            {
                ApiResources = apiResourceList.ToList(),
                IdentityResources = identityResourceList.ToList(),
                ApiScopes = apiScopeResourceList.ToList()
            });
        }
예제 #3
0
 public async Task <IEnumerable <User> > Page(int start = 0, int length = 1024)
 {
     return(await _session.Query <User>()
            .Skip(start)
            .Take(length)
            .ToListAsync());
 }
예제 #4
0
        public async Task <TUser> FindByNameAsync(string userName)
        {
            ThrowIfDisposed();

            return(await _documentSession.Query <TUser>().FirstOrDefaultAsync(user => user.UserName == userName)
                   .ConfigureAwait(false));
        }
예제 #5
0
        public async Task <ActionResult <IEnumerable <Product> > > Get()
        {
            var products = await _asyncDocumentSession
                           .Query <Product>()
                           .ToListAsync();

            return(products);
        }
예제 #6
0
        public async Task <int> GetBasketItemCountAsync(string userName)
        {
            var items = await _session.Query <Basket>()
                        .Where(x => x.BuyerId == userName)
                        .Select(x => x.Items.Sum(i => i.Quantity))
                        .FirstOrDefaultAsync();

            return(items);
        }
        public async Task <IEnumerable <ReadingProgramInfo> > GetAllProgramsForUser(string userId)
        {
            var programDtoList = await _session.Query <ReadingProgram_ByUser.Result, ReadingProgram_ByUser>()
                                 .Where(x => x.UserIds.Any(u => u == userId)).OfType <ReadingProgramInfoDTO>().ToListAsync();

            var programList = programDtoList.Select(x => x.ToReadingProgramInfo());

            return(programList);
        }
예제 #8
0
 /// <inheritdoc />
 public Task <TEntity> FindOneAsync(ILinqSpecification <TEntity> specification, CancellationToken cancellationToken = default)
 {
     if (specification == null)
     {
         throw new ArgumentNullException(nameof(specification));
     }
     return(specification.SatisfyingElementsFrom(Session.Query <TEntity>())
            .SingleOrDefaultAsync(cancellationToken));
 }
예제 #9
0
        public virtual async Task <PersistedGrant> GetAsync(string key)
        {
            var persistedGrant = await Session.Query <Entities.PersistedGrant>().FirstOrDefaultAsync(x => x.Key == key);

            var model = persistedGrant?.ToModel();

            Logger.LogDebug("{persistedGrantKey} found in database: {persistedGrantKeyFound}", key, model != null);

            return(model);
        }
예제 #10
0
                static async Task <(int CompaniesCount1, int CompaniesCount2)> GetItemsCount(IAsyncDocumentSession session)
                {
                    var query1 = session.Query <DocumentsIndex.Result, DocumentsIndex>()
                                 .Where(x => x.CompanyName == _companyName1).CountLazilyAsync();

                    var query2 = session.Query <DocumentsIndex.Result, DocumentsIndex>()
                                 .Where(x => x.CompanyName == _companyName2).CountLazilyAsync();

                    return(await query1.Value, await query2.Value);
                }
예제 #11
0
        public async Task <Models.DeviceCode> FindByDeviceCodeAsync(string deviceCode)
        {
            deviceCode = deviceCode ?? throw new ArgumentNullException(nameof(deviceCode));

            var entity = await _session.Query <DeviceCode>()
                         .FirstOrDefaultAsync(d => d.Code == deviceCode)
                         .ConfigureAwait(false);

            return(ToModel(entity));
        }
예제 #12
0
        public virtual async Task <DeviceCode> FindByDeviceCodeAsync(string deviceCode)
        {
            var deviceFlowCodes = await Session.Query <Entities.DeviceFlowCodes>().FirstOrDefaultAsync(x => x.DeviceCode == deviceCode);

            var model = ToModel(deviceFlowCodes?.Data);

            Logger.LogDebug("{deviceCode} found in database: {deviceCodeFound}", deviceCode, model != null);

            return(model);
        }
예제 #13
0
    public IRavenQueryable <T> Query <T>(string indexName = null, string collectionName = null, bool isMapReduce = false)
    {
        var query = _dbSession.Query <T>(indexName, collectionName, isMapReduce);

        if (typeof(T).GetInterfaces().Contains(typeof(ITenantedEntity)))
        {
            return(query.Where(r => (r as ITenantedEntity).TenantId == _currentTenantId));
        }

        return(query);
    }
        public async Task <IEnumerable <Scope> > FindScopesAsync(IEnumerable <string> scopeNames)
        {
            var query = session.Query <Scope, Scopes_Index>();

            if (scopeNames != null)
            {
                query = query.Where(x => x.Name.In(scopeNames));
            }

            return(await query.ToListAsync());
        }
예제 #15
0
        public async Task <PagedResult <Audit> > ReadAuditPaged(ODataQueryOptions <Audit> options, CancellationToken ctk = default)
        {
            var validations = new RavenDefaultODataValidationSettings()
            {
                AllowedOrderByProperties =
                {
                    "LastUpdatedUtc"
                },
            };

            var res = await _session.Query <Audit>().GetPagedWithODataOptions <Audit>(options, validations);

            return(res);
        }
예제 #16
0
        private async Task GenerateId(ChildDTO dto)
        {
            dto.Id = "Child/" + dto.LastName + ", " + dto.FirstName;

            var numberOfChildrenWithSameName = await _session.Query <ChildDTO>()
                                               .CountAsync(x => x.FirstName == dto.FirstName && x.LastName == dto.LastName);

            if (numberOfChildrenWithSameName > 0)
            {
                dto.Id += " - " + (numberOfChildrenWithSameName + 1);
                _logger.Debug("Found more children with same name, add number identifier {number} to id",
                              numberOfChildrenWithSameName + 1);
            }
        }
예제 #17
0
        public async Task <ActionResult <List <Starship> > > Get()
        {
            var result = new List <Starship>();
            await Agent.Tracer.CaptureTransaction("GetStarships", ApiConstants.TypeRequest,
                                                  async (transaction) =>
            {
                transaction.Labels["LabelTeste"] = "foo";

                result = await _db.Query <Starship>().ToListAsync();

                transaction.End();
            });

            return(Ok(result));
        }
예제 #18
0
        public async Task <Unit> Handle(StartConversationCommand request, CancellationToken cancellationToken)
        {
            var toss = await _session.LoadAsync <TossEntity>(_ravenDbIdUtil.GetRavenDbIdFromUrlId <TossEntity>(request.TossId));

            // we fail silently, there is no point in managing error when user hacked the desired behavior, this might change in the future
            if (toss == null)
            {
                throw new InvalidOperationException($"Toss does not exists : {request.TossId}");
            }
            var currentUser = await mediator.Send(new CurrentUserQuery());

            if (currentUser.Id == toss.UserId)
            {
                throw new InvalidOperationException($"Cannot create conversation when toss creator : {request.TossId}");
            }

            if (await _session.Query <TossConversation>().AnyAsync(c => c.CreatorUserId == currentUser.Id && c.TossId == toss.Id))
            {
                throw new InvalidOperationException($"Conversation already exists. User : {currentUser}, Toss: {toss.Id}");
            }

            TossConversation conversation = new TossConversation(toss, currentUser);
            await _session.StoreAsync(conversation);

            await mediator.Publish(new ConversationStarted(conversation));

            return(Unit.Value);
        }
예제 #19
0
        public IQueryable <Record> AsyncQuery(IAsyncDocumentSession adb, RecordQueryInputModel input)
        {
            var query = adb.Query <RecordIndex.Result, RecordIndex>()
                        .Statistics(out stats);

            return(RecordQueryImpl(input, query));
        }
예제 #20
0
        public async Task <List <DomainUpkFile> > LoadUpkFiles(CancellationToken token)
        {
            try
            {
                List <UpkFile> files = new List <UpkFile>();

                using (IAsyncDocumentSession session = store.Session)
                {
                    IRavenQueryable <UpkFile> query = session.Query <UpkFile, UpkFileCommonIndex>();

                    using (IAsyncEnumerator <StreamResult <UpkFile> > enumerator = await session.Advanced.StreamAsync(query, token))
                    {
                        while (await enumerator.MoveNextAsync())
                        {
                            files.Add(enumerator.Current.Document);
                        }
                    }
                }

                return(mapper.Map <List <DomainUpkFile> >(files));
            }
            catch (TaskCanceledException) { }
            catch (OperationCanceledException) { }

            return(new List <DomainUpkFile>());
        }
예제 #21
0
        public Task <TUser> FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken)
        {
            if (loginProvider == null)
            {
                throw new ArgumentNullException(nameof(loginProvider));
            }

            if (providerKey == null)
            {
                throw new ArgumentNullException(nameof(providerKey));
            }

            return(_session.Query <TUser>()
                   .Where(a => a.Logins.Any(b => b.LoginProvider == loginProvider && b.ProviderKey == providerKey))
                   .FirstOrDefaultAsync());
        }
예제 #22
0
        public async Task <Platform> UpdatePlatformAsync(PlatformId id, PlatformRequest platformRequest, IAsyncDocumentSession session)
        {
            var project = await session
                          .Query <Project>()
                          .Where(p => p.Platforms.Any(a => a.Id == id.Value))
                          .FirstOrDefaultAsync();

            var platform = project.Platforms?.FirstOrDefault();

            if (platform == null)
            {
                throw new ApiException("I couldn't find that platform. Are you sure it's the right token?", 404);
            }

            if (platform.ExportDataUri == platformRequest.ExportDataUri
                )
            {
                // Nothing to update
                throw new ApiException("That's the same information that I have. Great, so we agree.", 200);
            }
            platform.ExportDataUri = platformRequest.ExportDataUri;
            platform.LastUpdate    = DateTime.Now;
            // TODO: Save session changes once
            await session.SaveChangesAsync();

            return(platform);
        }
 public async Task <IEnumerable <UserAuthInfo> > FilterUsersByPredicateAsync(Expression <Func <UserAuthInfo, bool> > predicate)
 {
     return(await Queryable.Where(
                _connection.Query <UserAuthInfo>(),
                predicate)
            .ToListAsync());
 }
예제 #24
0
        public IQueryable<Record> AsyncQuery(IAsyncDocumentSession adb, RecordQueryInputModel input)
        {
            var query = adb.Query<RecordIndex.Result, RecordIndex>()
                .Statistics(out stats);

            return RecordQueryImpl(input, query);
        }
예제 #25
0
		public DiscoveryModule(IAsyncDocumentSession session)
			: base("/api/discovery")
		{
			this.session = session;

			Get["/start"] = parameters =>
			{
				var discoveryClient = new ClusterDiscoveryClient(SenderId, "http://localhost:9020/api/discovery/notify");
				discoveryClient.PublishMyPresenceAsync();
				return "started";
			};

			Post["/notify", true] = async (parameters, ct) =>
			{
				var input = this.Bind<ServerRecord>("Id");

				var server = await session.Query<ServerRecord>().Where(s => s.Url == input.Url).FirstOrDefaultAsync() ?? new ServerRecord();
				this.BindTo(server, "Id");
				await session.StoreAsync(server);

				await HealthMonitorTask.FetchServerDatabases(server, session.Advanced.DocumentStore);

				return "notified";
			};
		}
예제 #26
0
파일: SuggestAsync.cs 프로젝트: mow/ravendb
        public void DoWork()
        {
            using (var store = NewDocumentStore())
            {
                new People_ByName().Execute(store);
                using (IAsyncDocumentSession session = store.OpenAsyncSession())
                {
                    session.StoreAsync(new Person {
                        Name = "Jack", Age = 20
                    }).Wait();
                    session.StoreAsync(new Person {
                        Name = "Steve", Age = 74
                    }).Wait();
                    session.StoreAsync(new Person {
                        Name = "Martin", Age = 34
                    }).Wait();
                    session.StoreAsync(new Person {
                        Name = "George", Age = 12
                    }).Wait();

                    session.SaveChangesAsync().Wait();


                    IRavenQueryable <Person> query = session.Query <Person, People_ByName>()
                                                     .Search(p => p.Name, "martin");

                    query.SuggestAsync().Wait();
                }
            }
        }
예제 #27
0
        private async Task <bool> MoveStagedBatchesToForwardingBatch(IAsyncDocumentSession session)
        {
            isRecoveringFromPrematureShutdown = false;

            var stagingBatch = await session.Query <RetryBatch>()
                               .Customize(q => q.Include <RetryBatch, FailedMessageRetry>(b => b.FailureRetries))
                               .FirstOrDefaultAsync(b => b.Status == RetryBatchStatus.Staging)
                               .ConfigureAwait(false);

            if (stagingBatch != null)
            {
                redirects = await MessageRedirectsCollection.GetOrCreate(session).ConfigureAwait(false);

                var stagedMessages = await Stage(stagingBatch, session).ConfigureAwait(false);

                var skippedMessages = stagingBatch.InitialBatchSize - stagedMessages;
                await retryingManager.Skip(stagingBatch.RequestId, stagingBatch.RetryType, skippedMessages)
                .ConfigureAwait(false);

                if (stagedMessages > 0)
                {
                    await session.StoreAsync(new RetryBatchNowForwarding
                    {
                        RetryBatchId = stagingBatch.Id
                    }, RetryBatchNowForwarding.Id)
                    .ConfigureAwait(false);
                }

                return(true);
            }

            return(false);
        }
예제 #28
0
        public async Task <TossLastQueryItem> Handle(SponsoredTossQuery request, CancellationToken cancellationToken)
        {
            var resCollection = (await _session.Query <SponsoredTossEntity>()
                                 .Where(s => s.Tags.Contains(request.Hashtag))
                                 .Where(s => s.DisplayedCount > 0)
                                 .Select(t => new TossLastQueryItem()
            {
                Content = t.Content,
                CreatedOn = t.CreatedOn,
                Id = t.Id,
                UserName = t.UserId
            })
                                 .ToListAsync())
                                .ToLookup(t => t.UserName)
                                .ToArray();

            if (!resCollection.Any())
            {
                return(null);
            }
            var index    = random.NewRandom(resCollection.Length - 1);
            var userToss = resCollection[index].ToArray();
            var res      = userToss[random.NewRandom(userToss.Count() - 1)];
            await mediator.Publish(new SponsoredTossDisplayed(res.Id));

            return(res);
        }
예제 #29
0
 public async Task WaitForIndexAsync(string indexName, bool isMapReduce = false)
 {
     _ = await _asyncDocumentSession
         .Query <dynamic>(indexName, isMapReduce)
         .Customize(x => x.WaitForNonStaleResults())
         .FirstOrDefaultAsync().ConfigureAwait(false);
 }
예제 #30
0
        public async Task <IEnumerable <TEntity> > ListAllAsync()
        {
            using (IAsyncDocumentSession session = _db.OpenSessionAsync())
            {
                try
                {
                    var       docs            = new List <TEntity>();
                    var       nextGroupOfDocs = new List <TEntity>();
                    const int TakeLimit       = 512;
                    int       i           = 0;
                    int       skipResults = 0;

                    do
                    {
                        nextGroupOfDocs = (List <TEntity>) await session.Query <TEntity>().Statistics(out RavenQueryStatistics stats).Skip(i * TakeLimit + skipResults).Take(TakeLimit).ToListAsync();

                        i++;
                        skipResults += stats.SkippedResults;

                        docs = docs.Concat(nextGroupOfDocs).ToList();
                    }while (nextGroupOfDocs.Count == TakeLimit);

                    return(docs);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    return(null);
                }
            }
        }
예제 #31
0
        public DiscoveryModule(IAsyncDocumentSession session)
            : base("/api/discovery")
        {
            this.session = session;

            Get["/start"] = parameters =>
            {
                var discoveryClient = new ClusterDiscoveryClient(SenderId, "http://localhost:9020/api/discovery/notify");
                discoveryClient.PublishMyPresenceAsync();
                return("started");
            };

            Post["/notify", true] = async(parameters, ct) =>
            {
                var input = this.Bind <ServerRecord>("Id");

                var server = await session.Query <ServerRecord>().Where(s => s.Url == input.Url).FirstOrDefaultAsync() ?? new ServerRecord();

                this.BindTo(server, "Id");
                await session.StoreAsync(server);

                await HealthMonitorTask.FetchServerDatabases(server, session.Advanced.DocumentStore);

                return("notified");
            };
        }
예제 #32
0
        internal async Task <bool> AdoptOrphanedBatches(IAsyncDocumentSession session, DateTime cutoff)
        {
            var orphanedBatches = await session.Query <RetryBatch, RetryBatches_ByStatusAndSession>()
                                  .Customize(c => c.BeforeQueryExecution(index => index.Cutoff = cutoff))
                                  .Where(b => b.Status == RetryBatchStatus.MarkingDocuments && b.RetrySessionId != RetrySessionId)
                                  .Statistics(out var stats)
                                  .ToListAsync()
                                  .ConfigureAwait(false);

            log.InfoFormat("Found {0} orphaned retry batches from previous sessions", orphanedBatches.Count);

            // let's leave Task.Run for now due to sync sends
            await Task.WhenAll(orphanedBatches.Select(b => Task.Run(async() =>
            {
                log.InfoFormat("Adopting retry batch {0} from previous session with {1} messages", b.Id, b.FailureRetries.Count);
                await MoveBatchToStaging(b.Id).ConfigureAwait(false);
            }))).ConfigureAwait(false);

            foreach (var batch in orphanedBatches)
            {
                if (batch.RetryType != RetryType.MultipleMessages)
                {
                    OperationManager.Fail(batch.RetryType, batch.RequestId);
                }
            }

            if (abort)
            {
                return(false);
            }

            return(stats.IsStale || orphanedBatches.Any());
        }
예제 #33
0
        static Task<IList<string>> FirstQuery(IAsyncDocumentSession session)
        {
            var now = DateTime.UtcNow;

            RavenQueryStatistics stats;
            return session.Query<Logfile>()
                .Statistics(out stats)
                .Where(x => x.UploadDate >= now.AddMonths(-1))
                .Select(x => x.Owner)
                .Distinct()
                .Take(1024) // see 
                .ToListAsync();
        }
예제 #34
0
        public async Task<ActionResult> Index(IAsyncDocumentSession asyncSession)
        {
            // Remove when MVC 4 is released (http://forums.asp.net/p/1778103/4880898.aspx/1?Re+Using+an+Async+Action+to+Run+Synchronous+Code)
            await Task.Yield();

            var mike = (await asyncSession.Query<User>().Take(1).ToListAsync()).FirstOrDefault();
            if (mike == null)
            {
                mike = new User {FirstName = "Mike", LastName = "Noonan"};
                asyncSession.Store(mike);
                await asyncSession.SaveChangesAsync();
            }
            if (mike.F1AccessToken == null || mike.PCOAccessToken == null)
            {
                return RedirectToAction("Authenticate", "F1Auth");
            }

            return View();
        }
예제 #35
0
        private async Task<IEnumerable<Knock>> GetKnocksByFeedId(IAsyncDocumentSession session, string feedId)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));

            if (String.IsNullOrWhiteSpace(feedId))
                throw new ArgumentNullException(nameof(feedId));

            return await session.Query<Knock, Knock_ByFeed>().Where(knock => knock.FeedId==feedId).ToListAsync();
        }
예제 #36
0
 static Task<int> SecondQuery(IAsyncDocumentSession session)
 {
     return session.Query<Logfile>().Where(x => x.StoreId != SampleLogfileStoreId && x.SavedAnalyses.Any()).CountAsync();
 }
예제 #37
0
 static Task<int> ThirdQuery(IAsyncDocumentSession session)
 {
     return session.Query<Logfile>().Where(x => x.StoreId != SampleLogfileStoreId && x.SharedOnFacebookActionId != null).CountAsync();
 }
예제 #38
0
        private async Task<IEnumerable<Knock>> GetKnocksByLocation(IAsyncDocumentSession session, Location location, double radius)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));

            if (location == null)
                throw new ArgumentNullException(nameof(location));

            return await session.Query<Knock, Knock_ByLocation>()
                                .Spatial(x => x.Location, spatial => spatial.WithinRadius(radius, location.Latitude, location.Longitude))
                                .ToListAsync();
        }