コード例 #1
0
ファイル: ServerHelpers.cs プロジェクト: 925coder/ravendb
		public static async Task<AsyncServerClient> CreateAsyncServerClient(IAsyncDocumentSession session, ServerRecord server, ServerCredentials serverCredentials = null)
		{
			var documentStore = (DocumentStore)session.Advanced.DocumentStore;
			var replicationInformer = new ReplicationInformer(new DocumentConvention
			{
				FailoverBehavior = FailoverBehavior.FailImmediately
			});

			ICredentials credentials = null;
			if (serverCredentials != null)
			{
				credentials = serverCredentials.GetCredentials();
			}
			else if (server.CredentialsId != null)
			{
				serverCredentials = await session.LoadAsync<ServerCredentials>(server.CredentialsId);
				if (serverCredentials == null)
				{
					server.CredentialsId = null;
				}
				else
				{
					credentials = serverCredentials.GetCredentials();
				}
			}

			return new AsyncServerClient(server.Url, documentStore.Conventions, credentials,
										 documentStore.JsonRequestFactory, null, s => replicationInformer, null, new IDocumentConflictListener[0]);
		}
        internal static async Task<AuthorizationCode> FromDbFormat(StoredAuthorizationCode code, IAsyncDocumentSession s, IScopeStore scopeStore)
        {
            var result = new AuthorizationCode
            {
                CreationTime = code.CreationTime,
                IsOpenId = code.IsOpenId,
                RedirectUri = code.RedirectUri,
                WasConsentShown = code.WasConsentShown,
                Nonce = code.Nonce,
                Client = Data.StoredClient.FromDbFormat(await s.LoadAsync<Data.StoredClient>("clients/" + code.Client)),
                CodeChallenge = code.CodeChallenge,
                CodeChallengeMethod = code.CodeChallengeMethod,
                SessionId = code.SessionId,
                RequestedScopes = await scopeStore.FindScopesAsync(code.RequestedScopes)
            };

            var claimsPrinciple = new ClaimsPrincipal();
            foreach (var id in code.Subject)
            {
                claimsPrinciple.AddIdentity(Data.StoredIdentity.FromDbFormat(id));
            }
            result.Subject = claimsPrinciple;

            return result;
        }
コード例 #3
0
		public IEnumerable<Task> Initialize(IAsyncDocumentSession session)
		{
			// those are no longer needed, when we request the
			// Silverlight UI from the server, those indexes will 
			// be created automatically

			//yield return session.Advanced.AsyncDatabaseCommands
			//    .PutIndexAsync<RavenDocumentsByEntityName>(true);

			//yield return session.Advanced.AsyncDatabaseCommands
			//    .PutIndexAsync<RavenCollections>(true);

			SimpleLogger.Start("preloading collection templates");
			var templateProvider = IoC.Get<IDocumentTemplateProvider>();
			var collections = session.Advanced.AsyncDatabaseCommands.GetCollectionsAsync(0, 25);
			yield return collections;

			var preloading  = collections.Result
				.Select(x=>x.Name)
				.Union(Enumeration.All<BuiltinCollectionName>().Select(x => x.Value))
				.Select(templateProvider.GetTemplateFor);

			foreach (var task in preloading)
				yield return task;

			SimpleLogger.End("preloading collection templates");
		}
コード例 #4
0
 public BlogPostController(IMvcLogger logger, IAsyncDocumentSession documentSession, IConfigurationManager configManager, AkismetClient akismetClient, IMappingEngine mapper)
     : base(logger, documentSession)
 {
     _configManager = configManager;
     _akismetClient = akismetClient;
     _mapper = mapper;
 }
 public static ContextBag CreateContextWithAsyncSessionPresent(this RavenDBPersistenceTestBase testBase, out IAsyncDocumentSession session)
 {
     var context = new ContextBag();
     session = testBase.OpenAsyncSession();
     context.Set(session);
     return context;
 }
コード例 #6
0
ファイル: RecordQueryer.cs プロジェクト: jncc/topcat
        public IQueryable<Record> AsyncQuery(IAsyncDocumentSession adb, RecordQueryInputModel input)
        {
            var query = adb.Query<RecordIndex.Result, RecordIndex>()
                .Statistics(out stats);

            return RecordQueryImpl(input, query);
        }
コード例 #7
0
		public IEnumerable<Task> Initialize(IAsyncDocumentSession session)
		{
			yield return session.Advanced.AsyncDatabaseCommands
				.PutIndexAsync(@"Studio/DocumentCollections",
				               new IndexDefinition
				               	{
				               		Map =
				               			@"from doc in docs
let Name = doc[""@metadata""][""Raven-Entity-Name""]
where Name != null
select new { Name , Count = 1}
",
				               		Reduce =
				               			@"from result in results
group result by result.Name into g
select new { Name = g.Key, Count = g.Sum(x=>x.Count) }"
				               	}, true);


			// preload collection templates
			var templateProvider = IoC.Get<IDocumentTemplateProvider>();
			var collections = session.Advanced.AsyncDatabaseCommands.GetCollectionsAsync(0, 25);
			yield return collections;

			var preloading  = collections.Result
				.Select(x=>x.Name)
				.Union(Enumeration.All<BuiltinCollectionName>().Select(x => x.Value))
				.Select(templateProvider.GetTemplateFor);

			foreach (var task in preloading)
				yield return task;
		}
コード例 #8
0
ファイル: DiscoveryModule.cs プロジェクト: 925coder/ravendb
		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";
			};
		}
コード例 #9
0
        public void DocumentBatchingTest()
        {
            var store = new DocumentStore("http://localhost:8080");
            Session = store.OpenAsyncSession();

            Session.StoreEntity(new JsonDocument()
                                    {
                                        Key = Guid.NewGuid().ToString(),
                                        DataAsJson = new JObject(),
                                        Metadata = new JObject()
                                    });

            Session.StoreEntity(new JsonDocument()
                                    {
                                        Key = Guid.NewGuid().ToString(),
                                        DataAsJson = new JObject(),
                                        Metadata = new JObject()
                                    });

            Session.StoreEntity(new JsonDocument()
                                    {
                                        Key = Guid.NewGuid().ToString(),
                                        DataAsJson = new JObject(),
                                        Metadata = new JObject()
                                    });

            Session.SaveChanges((result) => Assert.IsTrue(result.IsSuccess));
        }
コード例 #10
0
        public void ReleaseSession()
        {
            if (session == null)
                return;

            session.Dispose();
            session = null;
        }
コード例 #11
0
        public async override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) {
            using (Session = Store.OpenAsyncSession()) {
                var result = await base.ExecuteAsync(controllerContext, cancellationToken);
                await Session.SaveChangesAsync();

                return result;
            }
        }
コード例 #12
0
        public async Task DoStuff(EndpointConfiguration configuration, IAsyncDocumentSession someAsyncSession)
        {
            #region 3to4-ravensharedsession
            Func<IAsyncDocumentSession> sessionFactory = () => someAsyncSession;

            configuration.UsePersistence<RavenDBPersistence>()
                .UseSharedAsyncSession(sessionFactory);
            #endregion
        }
コード例 #13
0
        protected static async Task SaveEntities(IEnumerable<IEntity> entities, IAsyncDocumentSession session)
        {
            foreach (var entity in entities)
            {
                await session.StoreAsync(entity);
            }

            await session.SaveChangesAsync();
        }
コード例 #14
0
        void DoStuff(EndpointConfiguration endpointConfiguration, IAsyncDocumentSession someAsyncSession)
        {
            #region 3to4-ravensharedsession
            Func<IAsyncDocumentSession> sessionFactory = () => someAsyncSession;

            var persistence = endpointConfiguration.UsePersistence<RavenDBPersistence>();
            persistence.UseSharedAsyncSession(sessionFactory);
            #endregion
        }
コード例 #15
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();
        }
コード例 #16
0
 public void SetUp()
 {
     _store = new EmbeddableDocumentStore
     {
         RunInMemory = true,
         DataDirectory = Path.GetTempPath()
     };
     _store.Initialize();
     _session = _store.OpenAsyncSession();
 }
コード例 #17
0
 private async Task EnsureSubscriptionsExists(IAsyncDocumentSession session)
 {
     var subscription = await session.LoadAsync<Subscription>(Subscription.Id);
     if (subscription == null)
     {
         subscription = new Subscription();
         await session.StoreAsync(subscription);
         await session.SaveChangesAsync();
     }
 }
コード例 #18
0
 public void TestInitialize()
 {
     // Arrange
     _documentStore = new EmbeddableDocumentStore
     {
         ConnectionStringName = "RavenDB"
     };
     _documentStore.Initialize();
     _session = _documentStore.OpenAsyncSession();
     _controller = new MoviesController(_session);
 }
コード例 #19
0
ファイル: InitRepository.cs プロジェクト: plaurin/RavenDBDemo
        public static void CreateCustomer(IAsyncDocumentSession session, string name, AddressOptions addressOptions)
        {
            var entity = new Customer { Name = name };

            if (addressOptions == AddressOptions.Home || addressOptions == AddressOptions.HomeAndBusines)
                entity.Addresses.Add(CreateAddress(AddressOptions.Home));

            if (addressOptions == AddressOptions.Business || addressOptions == AddressOptions.HomeAndBusines)
                entity.Addresses.Add(CreateAddress(AddressOptions.Business));

            session.Store(entity);
        }
コード例 #20
0
 public void TestCleanup()
 {
     if (_session != null)
     {
         _session.Dispose();
         _session = null;
     }
     if (_documentStore != null)
     {
         _documentStore.Dispose();
         _documentStore = null;
     }
 }
コード例 #21
0
ファイル: IndexMerging.cs プロジェクト: jrusbatch/ravendb
        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();
        }
コード例 #22
0
ファイル: RavenDb4583.cs プロジェクト: IdanHaim/ravendb
        private static async Task CreateUsersAsync(IAsyncDocumentSession session)
        {
            var user1 = new User {Name = "Jane"};
            user1.OfficesIds.Add("office/1");
            user1.OfficesIds.Add("office/2");

            var user2 = new User {Name = "Bill"};
            user2.OfficesIds.Add("office/1");
            user2.OfficesIds.Add("office/3");

            await session.StoreAsync(user1);
            await session.StoreAsync(user2);
        }
コード例 #23
0
ファイル: AsyncRavenProjector.cs プロジェクト: robvdlv/Projac
        /// <summary>
        /// Projects the specified message asynchronously.
        /// </summary>
        /// <param name="session">The Raven session used during projection.</param>
        /// <param name="message">The message to project.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        ///     A <see cref="Task" />.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="session"/> or <paramref name="message"/> is <c>null</c>.</exception>
        public async Task ProjectAsync(IAsyncDocumentSession session, object message, CancellationToken cancellationToken)
        {
            if (session == null) throw new ArgumentNullException("session");
            if (message == null) throw new ArgumentNullException("message");

            RavenProjectionHandler[] handlers;
            if (_handlers.TryGetValue(message.GetType(), out handlers))
            {
                foreach (var handler in handlers)
                {
                    await handler.Handler(session, message, cancellationToken);
                }
            }
        }
        protected static AccountsController GetAccountsController(IAsyncDocumentSession session)
        {
            var appUserManager = GetApplicationUserManager(session);
            var appRoleManager = GetApplicationRoleManager(session);
            var mockUrlHelper = new Mock<UrlHelper>();
            mockUrlHelper.Setup(c => c.Link(It.IsAny<string>(), It.IsAny<object>())).Returns("http://location");

            var controller = new AccountsController(appUserManager,appRoleManager)
            {
                Url = mockUrlHelper.Object,
                Request = new HttpRequestMessage(),
                Configuration = new HttpConfiguration()
            };

            controller.Configuration.Routes.MapHttpRoute("GetUserById", "api/{controller}/{id}", new {id = RouteParameter.Optional});

            return controller;
        }
コード例 #25
0
ファイル: HomeController.cs プロジェクト: highwaychurch/web
        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();
        }
コード例 #26
0
        private static void CreateDefaultData(IAsyncDocumentSession session)
        {
            var role = new ApplicationRole("Admin");
            session.StoreAsync(role);

            var hasher = new PasswordHasher();
            var passwordHash = hasher.HashPassword("admin");
            var superUser = new ApplicationUser("SuperAdmin")
            {
                Email = "*****@*****.**",
                FirstName = "Super",
                LastName = "Admin",
                UserName = "******",
                PasswordHash = passwordHash,
                EmailConfirmed = true,
                Roles = {"Admin"}
            };

            session.StoreAsync(superUser);

            session.SaveChangesAsync();
        }
コード例 #27
0
        /// <inheritdoc />
        public async Task AddToRoleAsync(TUser user, string roleName, CancellationToken cancellationToken)
        {
            ThrowIfNullDisposedCancelled(user, cancellationToken);

            // See if we have an IdentityRole with that name.
            var identityUserCollection = _store.Conventions.GetCollectionName(typeof(TRole));
            var prefix = _store.Conventions.TransformTypeCollectionNameToDocumentIdPrefix(identityUserCollection);
            var identityPartSeperator = _store.Conventions.IdentityPartsSeparator;
            var roleNameLowered       = roleName.ToLowerInvariant();
            var roleId = prefix + identityPartSeperator + roleNameLowered;

            using (IAsyncDocumentSession session = _store.OpenAsyncSession())
            {
                var existingRoleOrNull = await session.LoadAsync <IdentityRole>(roleId, cancellationToken);

                if (existingRoleOrNull == null)
                {
                    ThrowIfDisposedOrCancelled(cancellationToken);
                    existingRoleOrNull      = new TRole();
                    existingRoleOrNull.Name = roleNameLowered;
                    await session.StoreAsync(existingRoleOrNull, roleId, cancellationToken);
                }

                // Use the real name (not normalized/uppered/lowered) of the role, as specified by the user.
                var roleRealName = existingRoleOrNull.Name;
                if (!user.Roles.Contains(roleRealName, StringComparer.InvariantCultureIgnoreCase))
                {
                    user.GetRolesList().Add(roleRealName);
                }

                if (!existingRoleOrNull.Users.Contains(user.Id, StringComparer.InvariantCultureIgnoreCase))
                {
                    existingRoleOrNull.Users.Add(user.Id);
                }

                await session.SaveChangesAsync(cancellationToken);
            }
        }
コード例 #28
0
ファイル: RavenDbSagaStorage.cs プロジェクト: zszqwe/Rebus
        static async Task <IEnumerable <string> > SaveCorrelationProperties(IAsyncDocumentSession session, ISagaData sagaData, IEnumerable <ISagaCorrelationProperty> correlationProperties, string sagaDataDocumentId)
        {
            var documentIds = new List <string>();

            foreach (var correlationProperty in correlationProperties)
            {
                var propertyName = correlationProperty.PropertyName;
                var value        = sagaData.GetType().GetProperty(propertyName).GetValue(sagaData)?.ToString();

                if (value == null)
                {
                    continue;
                }

                var documentId = SagaCorrelationPropertyDocument.GetIdForCorrelationProperty(correlationProperty.SagaDataType, propertyName, value);

                var existingSagaCorrelationPropertyDocument = await session.LoadAsync <SagaCorrelationPropertyDocument>(documentId);

                if (existingSagaCorrelationPropertyDocument != null)
                {
                    if (existingSagaCorrelationPropertyDocument.SagaDataDocumentId != sagaDataDocumentId)
                    {
                        throw new ConcurrencyException(
                                  $"Could not save correlation properties. The following correlation property already exists with the same value for another saga: {propertyName} = {value} (saga with ID {existingSagaCorrelationPropertyDocument.SagaDataDocumentId})");
                    }
                }
                else
                {
                    var sagaCorrelationPropertyDocument = new SagaCorrelationPropertyDocument(correlationProperty.SagaDataType, propertyName, value, sagaDataDocumentId);

                    await session.StoreAsync(sagaCorrelationPropertyDocument, documentId);
                }

                documentIds.Add(documentId);
            }

            return(documentIds);
        }
コード例 #29
0
        public static Func <Task> GetHandler(
            IAsyncDocumentSession session,
            object @event)
        {
            Func <Guid, string> getDbId = ReadModels.MyClassifiedAds.GetDatabaseId;

            return(@event switch
            {
                Events.V1.ClassifiedAdCreated e =>
                () => CreateOrUpdate(e.OwnerId,
                                     myAds => myAds.MyAds.Add(
                                         new ReadModels.MyClassifiedAds.MyAd {
                    Id = e.Id
                }
                                         ),
                                     () => new ReadModels.MyClassifiedAds
                {
                    Id = getDbId(e.OwnerId),
                    MyAds = new List <ReadModels.MyClassifiedAds.MyAd>()
                }),
                Events.V1.ClassifiedAdTitleChanged e =>
                () => UpdateOneAd(e.OwnerId, e.Id,
                                  myAd => myAd.Title = e.Title),
                Events.V1.ClassifiedAdTextUpdated e =>
                () => UpdateOneAd(e.OwnerId, e.Id,
                                  myAd => myAd.Description = e.AdText),
                Events.V1.ClassifiedAdPriceUpdated e =>
                () => UpdateOneAd(e.OwnerId, e.Id,
                                  myAd => myAd.Price = e.Price),
                Events.V1.PictureAddedToAClassifiedAd e =>
                () => UpdateOneAd(e.OwnerId, e.ClassifiedAdId,
                                  myAd => myAd.PhotoUrls.Add(e.Url)),
                Events.V1.ClassifiedAdDeleted e =>
                () => Update(e.OwnerId,
                             myAd => myAd.MyAds
                             .RemoveAll(x => x.Id == e.Id)),
                _ => (Func <Task>)null
            });
コード例 #30
0
        public async Task FindAsync_Should_Find_The_User_If_Login_Exists()
        {
            const string userName      = "******";
            const string loginProvider = "Twitter";
            const string providerKey   = "12345678";

            using (IDocumentStore store = CreateEmbeddableStore())
            {
                // Arrange
                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    IUserLoginStore <RavenUser, string> userLoginStore = new RavenUserStore <RavenUser>(ses);
                    RavenUser      user      = new RavenUser(userName);
                    RavenUserLogin userLogin = new RavenUserLogin(user.Id, new UserLoginInfo(loginProvider, providerKey));
                    user.AddLogin(userLogin);
                    await ses.StoreAsync(user);

                    await ses.StoreAsync(userLogin);

                    await ses.SaveChangesAsync();
                }

                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    IUserLoginStore <RavenUser, string> userLoginStore = new RavenUserStore <RavenUser>(ses);

                    // Act
                    UserLoginInfo loginInfo = new UserLoginInfo(loginProvider, providerKey);
                    RavenUser     foundUser = await userLoginStore.FindAsync(loginInfo);

                    // Assert
                    Assert.NotNull(foundUser);
                    Assert.Equal(userName, foundUser.UserName);
                }
            }
        }
コード例 #31
0
        public async Task Add_Should_Add_New_Login_If_User_Exists()
        {
            const string userName      = "******";
            const string loginProvider = "Twitter";
            const string providerKey   = "12345678";

            using (IDocumentStore store = CreateEmbeddableStore())
            {
                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    IUserLoginStore <RavenUser, string> userLoginStore = new RavenUserStore <RavenUser>(ses);
                    RavenUser user = new RavenUser(userName);
                    await ses.StoreAsync(user);

                    await ses.SaveChangesAsync();
                }

                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    IUserLoginStore <RavenUser, string> userLoginStore = new RavenUserStore <RavenUser>(ses);
                    RavenUser user = await ses.LoadAsync <RavenUser>(RavenUser.GenerateKey(userName));

                    // Act
                    UserLoginInfo loginToAdd = new UserLoginInfo(loginProvider, providerKey);
                    await userLoginStore.AddLoginAsync(user, loginToAdd);

                    await ses.SaveChangesAsync();

                    // Assert
                    RavenUserLogin foundLogin = await ses.LoadAsync <RavenUserLogin>(RavenUserLogin.GenerateKey(loginProvider, providerKey));

                    Assert.Equal(1, user.Logins.Count());
                    Assert.NotNull(foundLogin);
                }
            }
        }
コード例 #32
0
        GetPlatformConnectionsReadyForDataFetch(IAsyncDocumentSession session, CancellationToken cancellationToken)
        {
            var now = DateTimeOffset.UtcNow;

            var smallestExistingDataPullInterval = await session
                                                   .Query <Users_ByPlatformConnectionPossiblyRipeForDataFetch.Result,
                                                           Users_ByPlatformConnectionPossiblyRipeForDataFetch>()
                                                   .OrderBy(u => u.MinimumDataPullIntervalInSeconds).Take(1)
                                                   .Select(u => u.MinimumDataPullIntervalInSeconds).FirstOrDefaultAsync(cancellationToken);

            if (!smallestExistingDataPullInterval.HasValue)
            {
                return(new List <KeyValuePair <string, IEnumerable <PlatformConnection> > >());
            }

            var cutoff = now - TimeSpan.FromSeconds(smallestExistingDataPullInterval.Value);

            var userIdsThatPossibleHavePlatformConnectionsRipeForDataFetch = await session
                                                                             .Query <Users_ByPlatformConnectionPossiblyRipeForDataFetch.Result,
                                                                                     Users_ByPlatformConnectionPossiblyRipeForDataFetch>()
                                                                             .Where(u => u.EarliestPlatformConnectionDataFetchCompletion == DateTimeOffset.MinValue ||
                                                                                    u.EarliestPlatformConnectionDataFetchCompletion.Value < cutoff)
                                                                             .Select(u => u.UserId)
                                                                             .ToListAsync(cancellationToken);

            var usersThatPossibleHavePlatformConnectionsRipeForDataFetch =
                await session.LoadAsync <User>(userIdsThatPossibleHavePlatformConnectionsRipeForDataFetch,
                                               cancellationToken);

            var userIdsToPlatformConnectionsThatShouldBeUpdated =
                usersThatPossibleHavePlatformConnectionsRipeForDataFetch.Values
                .Where(u => u.PlatformConnections.Any(pc => IsPlatformConnectionRipeForUpdate(pc, now)))
                .Select(u => new KeyValuePair <string, IEnumerable <PlatformConnection> >(u.Id,
                                                                                          u.PlatformConnections.Where(pc => IsPlatformConnectionRipeForUpdate(pc, now)).ToList()))
                .ToList();

            return(userIdsToPlatformConnectionsThatShouldBeUpdated);
        }
コード例 #33
0
        public static Task <T> LoadByUniqueConstraintAsync <T>(this IAsyncDocumentSession session, Expression <Func <T, object> > keySelector, object value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "The unique value cannot be null");
            }
            var typeName     = session.Advanced.DocumentStore.Conventions.GetTypeTagName(typeof(T));
            var body         = (MemberExpression)keySelector.Body;
            var propertyName = body.Member.Name;

            var uniqueId = "UniqueConstraints/" + typeName.ToLowerInvariant() + "/" + propertyName.ToLowerInvariant() + "/" +
                           Raven.Bundles.UniqueConstraints.Util.EscapeUniqueValue(value);

            return(session.Include <ConstraintDocument>(x => x.RelatedId).LoadAsync(uniqueId)
                   .ContinueWith(x =>
            {
                if (x.Result == null)
                {
                    return new CompletedTask <T>(default(T));
                }
                return session.LoadAsync <T>(x.Result.RelatedId);
            }).Unwrap());
        }
コード例 #34
0
        private static async Task <bool> PreInsertSagaInstance <T>(IAsyncDocumentSession session, TSaga instance)
        {
            try
            {
                await session.StoreAsync(instance, GetSagaId(session, instance));

                await session.SaveChangesAsync();

                _log.DebugFormat("SAGA:{0}:{1} Insert {2}", TypeMetadataCache <TSaga> .ShortName, instance.CorrelationId,
                                 TypeMetadataCache <T> .ShortName);
                return(true);
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("SAGA:{0}:{1} Dupe {2} - {3}", TypeMetadataCache <TSaga> .ShortName,
                                     instance.CorrelationId,
                                     TypeMetadataCache <T> .ShortName, ex.Message);
                }
                return(false);
            }
        }
コード例 #35
0
        public async Task AddClaimAsync_Should_Add_The_Claim_Into_The_User_Claims_Collection()
        {
            string userName = "******";

            using (IDocumentStore store = base.CreateEmbeddableStore())
                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    IUserClaimStore <RavenUser> userClaimStore = new RavenUserStore <RavenUser>(ses, false);
                    RavenUser user = new RavenUser(userName);

                    await ses.StoreAsync(user);

                    await ses.SaveChangesAsync();

                    Claim claimToAdd = new Claim(ClaimTypes.Role, "Customer");
                    await userClaimStore.AddClaimAsync(user, claimToAdd);

                    Assert.Equal(1, user.Claims.Count());
                    Assert.Equal(claimToAdd.Value, user.Claims.FirstOrDefault().ClaimValue);
                    Assert.Equal(claimToAdd.Type, user.Claims.FirstOrDefault().ClaimType);
                }
        }
コード例 #36
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>());
        }
コード例 #37
0
        private async Task <bool> ForwardCurrentBatch(IAsyncDocumentSession session, CancellationToken cancellationToken)
        {
            Log.Debug("Looking for batch to forward");

            var nowForwarding = await session.Include <RetryBatchNowForwarding, RetryBatch>(r => r.RetryBatchId)
                                .LoadAsync <RetryBatchNowForwarding>(RetryBatchNowForwarding.Id)
                                .ConfigureAwait(false);

            if (nowForwarding != null)
            {
                Log.DebugFormat("Loading batch {0} for forwarding", nowForwarding.RetryBatchId);

                var forwardingBatch = await session.LoadAsync <RetryBatch>(nowForwarding.RetryBatchId, cancellationToken).ConfigureAwait(false);

                if (forwardingBatch != null)
                {
                    Log.InfoFormat("Found batch {0}. Forwarding...", forwardingBatch.Id);
                    await Forward(forwardingBatch, session, cancellationToken)
                    .ConfigureAwait(false);

                    Log.DebugFormat("Retry batch {0} forwarded.", forwardingBatch.Id);
                }
                else
                {
                    Log.WarnFormat("Could not find retry batch {0} to forward", nowForwarding.RetryBatchId);
                }

                Log.Debug("Removing Forwarding record");

                session.Delete(nowForwarding);
                return(true);
            }

            Log.Debug("No batch found to forward");

            return(false);
        }
コード例 #38
0
        public static async Task <T> LoadByUniqueConstraintAsync <T>(this IAsyncDocumentSession session, Expression <Func <T, object> > keySelector, object value)
        {
            var documentStoreListeners         = ((AsyncDocumentSession)session).Listeners.StoreListeners;
            var uniqueConstraintsStoreListener = documentStoreListeners.OfType <UniqueConstraintsStoreListener>().FirstOrDefault();

            if (uniqueConstraintsStoreListener == null)
            {
                throw new InvalidOperationException("Could not find UniqueConstraintsStoreListener in the session listeners, did you forget to register it?");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value", "The unique value cannot be null");
            }
            var typeName     = session.Advanced.DocumentStore.Conventions.GetTypeTagName(typeof(T));
            var body         = GetMemberExpression(keySelector, uniqueConstraintsStoreListener.UniqueConstraintsTypeDictionary);
            var propertyName = body.Member.Name;
            var att          = (UniqueConstraintAttribute)body.Member.GetCustomAttribute(typeof(UniqueConstraintAttribute));

            var escapedValue = Util.EscapeUniqueValue(value, att.CaseInsensitive);
            var uniqueId     = "UniqueConstraints/" + typeName.ToLowerInvariant() + "/" + propertyName.ToLowerInvariant() + "/" + escapedValue;

            var constraintDoc = await session
                                .Include <ConstraintDocument>(x => x.RelatedId)
                                .Include(x => x.Constraints.Values.Select(c => c.RelatedId))
                                .LoadAsync(uniqueId)
                                .ConfigureAwait(false);

            if (constraintDoc == null)
            {
                return(default(T));
            }

            session.Advanced.Evict(constraintDoc);

            return(await session.LoadAsync <T>(constraintDoc.GetRelatedIdFor(escapedValue)).ConfigureAwait(false));
        }
コード例 #39
0
        async Task Forward(RetryBatch forwardingBatch, IAsyncDocumentSession session, CancellationToken cancellationToken)
        {
            var messageCount = forwardingBatch.FailureRetries.Count;

            await retryingManager.Forwarding(forwardingBatch.RequestId, forwardingBatch.RetryType)
            .ConfigureAwait(false);

            if (isRecoveringFromPrematureShutdown)
            {
                Log.Warn($"Recovering from premature shutdown. Starting forwarder for batch {forwardingBatch.Id} in timeout mode.");
                await returnToSender.Run(forwardingBatch.Id, IsPartOfStagedBatch(forwardingBatch.StagingId), cancellationToken, null)
                .ConfigureAwait(false);

                await retryingManager.ForwardedBatch(forwardingBatch.RequestId, forwardingBatch.RetryType, forwardingBatch.InitialBatchSize)
                .ConfigureAwait(false);
            }
            else
            {
                if (messageCount == 0)
                {
                    Log.Info($"Skipping forwarding of batch {forwardingBatch.Id}: no messages to forward.");
                }
                else
                {
                    Log.Info($"Starting forwarder for batch {forwardingBatch.Id} with {messageCount} messages in counting mode.");
                    await returnToSender.Run(forwardingBatch.Id, IsPartOfStagedBatch(forwardingBatch.StagingId), cancellationToken, messageCount)
                    .ConfigureAwait(false);
                }

                await retryingManager.ForwardedBatch(forwardingBatch.RequestId, forwardingBatch.RetryType, messageCount)
                .ConfigureAwait(false);
            }

            session.Delete(forwardingBatch);

            Log.Info($"Done forwarding batch {forwardingBatch.Id}.");
        }
コード例 #40
0
        public async Task SaveUpkFile(List <DomainUpkFile> Files)
        {
            if (Files == null || !Files.Any())
            {
                return;
            }

            List <UpkFile> files = mapper.Map <List <UpkFile> >(Files);

            using (IAsyncDocumentSession session = store.Session)
            {
                for (int index = 0; index < files.Count(f => !String.IsNullOrEmpty(f.Id)); index += 1024)
                {
                    List <UpkFile> dbFiles = (await session.LoadAsync <UpkFile>(files.Where(f => !String.IsNullOrEmpty(f.Id))
                                                                                .Skip(index).Take(1024)
                                                                                .Select(f => f.Id))).Where(result => result.Value != null)
                                             .Select(result => result.Value)
                                             .ToList();

                    var items = (from row1 in dbFiles
                                 join row2 in files on row1.Id equals row2.Id
                                 select new { DbFile = row1, File = row2 }).ToList();

                    items.ForEach(item => mapper.Map(item.File, item.DbFile));
                }

                foreach (UpkFile file in files.Where(f => String.IsNullOrEmpty(f.Id)))
                {
                    await session.StoreAsync(file);
                }

                await session.SaveChangesAsync();

                Files.Zip(files, Tuple.Create).ForEach(t => t.Item1.Id = t.Item2.Id);
            }
        }
コード例 #41
0
        public async Task DoWork()
        {
            using (var store = GetDocumentStore())
            {
                new People_ByName().Execute(store);
                using (IAsyncDocumentSession session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(new Person { Name = "Jack", Age = 20 });

                    await session.StoreAsync(new Person { Name = "Steve", Age = 74 });

                    await session.StoreAsync(new Person { Name = "Martin", Age = 34 });

                    await session.StoreAsync(new Person { Name = "George", Age = 12 });

                    await session.SaveChangesAsync();

                    var query = session.Query <Person, People_ByName>()
                                .SuggestUsing(x => x.ByField(y => y.Name, "martin"));

                    await query.ExecuteAsync();
                }
            }
        }
コード例 #42
0
        public void InitializeAsyncContext(string connectionString, params object[] parameters)
        {
            string[] vs = connectionString.Split(new char[] { ';' });

            Dictionary <string, string> properties = new Dictionary <string, string>();

            foreach (var se in vs)
            {
                var keyvalue = se.Split(new char[] { '=' });
                properties.Add(keyvalue[0], keyvalue[1]);
            }

            string storeKey = connectionString;

            if (stores.ContainsKey(storeKey))
            {
                docStore = stores[storeKey];
            }
            else
            {
                InitStore(properties, storeKey);
            }
            asyncSession = docStore.OpenAsyncSession();
        }
コード例 #43
0
        // privates
        private static async Task AddUsers(IAsyncDocumentSession ses)
        {
            await ses.StoreAsync(new RavenUser { UserName = "******", Roles = new List <RavenUserRole> {
                                                     new RavenUserRole {
                                                         Id = "Admin"
                                                     }, new RavenUserRole {
                                                         Id = "Guest"
                                                     }
                                                 } });

            await ses.StoreAsync(new RavenUser { UserName = "******", Roles = new List <RavenUserRole> {
                                                     new RavenUserRole {
                                                         Id = "Admin"
                                                     }
                                                 } });

            await ses.StoreAsync(new RavenUser { UserName = "******", Roles = new List <RavenUserRole> {
                                                     new RavenUserRole {
                                                         Id = "Guest"
                                                     }
                                                 } });

            await ses.SaveChangesAsync();
        }
コード例 #44
0
        void Forward(RetryBatch forwardingBatch, IAsyncDocumentSession session, CancellationToken cancellationToken)
        {
            var messageCount = forwardingBatch.FailureRetries.Count;

            Log.InfoFormat("Forwarding batch {0} with {1} messages", forwardingBatch.Id, messageCount);
            retryingManager.Forwarding(forwardingBatch.RequestId, forwardingBatch.RetryType);

            if (isRecoveringFromPrematureShutdown)
            {
                Log.Warn("Recovering from premature shutdown. Starting forwarder in timeout mode");
                returnToSender.Run(IsPartOfStagedBatch(forwardingBatch.StagingId), cancellationToken);
                retryingManager.ForwardedBatch(forwardingBatch.RequestId, forwardingBatch.RetryType, forwardingBatch.InitialBatchSize);
            }
            else
            {
                Log.DebugFormat("Starting forwarder in counting mode with {0} messages", messageCount);
                returnToSender.Run(IsPartOfStagedBatch(forwardingBatch.StagingId), cancellationToken, messageCount);
                retryingManager.ForwardedBatch(forwardingBatch.RequestId, forwardingBatch.RetryType, messageCount);
            }

            session.Delete(forwardingBatch);

            Log.InfoFormat("Retry batch {0} done", forwardingBatch.Id);
        }
コード例 #45
0
        public async Task <Platform> GetPlatformAsync(PlatformId id, IAsyncDocumentSession session)
        {
            var project = await
                          session
                          .Query <Project>()
                          .Where(p => p.Platforms.Any(a => a.Id == id.Value))
                          .FirstOrDefaultAsync();

            if (project != null)
            {
                return(project?
                       .Platforms?
                       .FirstOrDefault());
            }
            var testProject = await
                              session
                              .Query <TestProject>()
                              .Where(p => p.Platforms.Any(a => a.Id == id.Value))
                              .FirstOrDefaultAsync();

            return(testProject?
                   .Platforms?
                   .FirstOrDefault());
        }
コード例 #46
0
        private static FailedMessageView Map(FailedMessage message, IAsyncDocumentSession session)
        {
            var processingAttempt = message.ProcessingAttempts.Last();

            var metadata       = processingAttempt.MessageMetadata;
            var failureDetails = processingAttempt.FailureDetails;

            return(new FailedMessageView
            {
                Id = message.UniqueMessageId,
                MessageType = metadata.GetAsStringOrNull("MessageType"),
                IsSystemMessage = metadata.GetOrDefault <bool>("IsSystemMessage"),
                SendingEndpoint = metadata.GetOrDefault <EndpointDetails>("SendingEndpoint"),
                ReceivingEndpoint = metadata.GetOrDefault <EndpointDetails>("ReceivingEndpoint"),
                TimeSent = metadata.GetAsNullableDatetime("TimeSent"),
                MessageId = metadata.GetAsStringOrNull("MessageId"),
                Exception = failureDetails.Exception,
                QueueAddress = failureDetails.AddressOfFailingEndpoint,
                NumberOfProcessingAttempts = message.ProcessingAttempts.Count,
                Status = message.Status,
                TimeOfFailure = failureDetails.TimeOfFailure,
                LastModified = session.Advanced.GetMetadataFor(message)["Last-Modified"].Value <DateTime>()
            });
        }
コード例 #47
0
 public DeleteSubscriptionCommandHandler(IAsyncDocumentSession session)
 {
     _session = session;
 }
コード例 #48
0
 private static IAdminStore <Entity.RelyingPartyClaimMapping> CreateSut(IAsyncDocumentSession session, ILogger <AdminStore <Entity.RelyingPartyClaimMapping> > logger)
 => new RelyingPartyClaimMappingStore(new ScopedAsynDocumentcSession(session), logger);
コード例 #49
0
 public AmikiriConfigurationProvider(IAsyncDocumentSession documentSession)
 {
     _documentSession = documentSession;
 }
コード例 #50
0
ファイル: UserStore.cs プロジェクト: rohith/raven-identity
 public UserStore(IAsyncDocumentSession session)
 {
     Session = session;
 }
コード例 #51
0
 public UserRepository(IAsyncDocumentSession session) : base(session)
 {
 }
コード例 #52
0
 public ProjectTaskRepo(IAsyncDocumentSession asyncDocumentSession, ILogger <ProjectTaskRepo> logger)
 {
     this.asyncDocumentSession = asyncDocumentSession;
     this.logger = logger;
 }
コード例 #53
0
 protected override IAdminStore <ApiClaim> CreateSut(IAsyncDocumentSession session, ILogger <AdminStore <ApiClaim> > logger)
 => new ApiClaimStore(new ScopedAsynDocumentcSession(session), logger);
コード例 #54
0
 public CustomFieldByIdQueryService(IAsyncDocumentSession dbSession, IBacklogItemByCustomFieldQueryService backlogService) : base(dbSession)
 {
     _backlogService = backlogService;
 }
コード例 #55
0
 protected async Task Delete(IAsyncDocumentSession session, TObject entity)
 {
     session.Delete(entity);
     await session.SaveChangesAsync();
 }
コード例 #56
0
        public async Task <Platform> CreatePlatform(string name,
                                                    PlatformAuthenticationMechanism authMechanism, PlatformIntegrationType platformIntegrationType,
                                                    RatingInfo ratingInfo, int?dataPollIntervalInSeconds, Guid externalPlatformId, string description,
                                                    string logoUrl, string websiteUrl, IAsyncDocumentSession session, bool isInactive = false,
                                                    CancellationToken cancellationToken = default)
        {
            try
            {
                await GetPlatformByExternalId(externalPlatformId, session, cancellationToken);

                throw new PlatformAlreadyExistsException(
                          $"Platform with external id {externalPlatformId} already exists. Name: {name}");
            }
            catch (PlatformDoNotExistException)
            {
                var platform = new Platform(name, externalPlatformId, authMechanism, platformIntegrationType,
                                            ratingInfo, description, logoUrl, websiteUrl, dataPollIntervalInSeconds, isInactive);
                await session.StoreAsync(platform, cancellationToken);

                return(platform);
            }
        }
コード例 #57
0
 public async Task <IList <Platform> > GetAllPlatforms(IAsyncDocumentSession session,
                                                       CancellationToken cancellationToken = default)
 {
     return(await session.Query <Platform>().Where(p => !p.IsInactive).ToListAsync(cancellationToken));
 }
コード例 #58
0
		private void StoreVersioningData(IEnumerable<VersioningConfiguration> versioningData, IAsyncDocumentSession session)
		{
			foreach (var data in versioningData)
			{
				if (data.Id.StartsWith("Raven/Versioning/", StringComparison.InvariantCultureIgnoreCase) == false)
					data.Id = "Raven/Versioning/" + data.Id;
				session.Store(data);
			}
		}
コード例 #59
0
		private void StoreAuthorizationData(AuthorizationSettingsSectionModel authorizationSection, IAsyncDocumentSession session)
		{
			foreach (var authorizationRole in authorizationSection.AuthorizationRoles)
			{
				session.Store(authorizationRole);
			}

			foreach (var authorizationUser in authorizationSection.AuthorizationUsers)
			{
				session.Store(authorizationUser);
			}
		}
コード例 #60
0
 public SupplierService(IAsyncDocumentSession session, IPrincipal user) : base(session, user)
 {
 }