OpenAsyncSession() public method

public OpenAsyncSession ( ) : IAsyncDocumentSession
return IAsyncDocumentSession
Ejemplo n.º 1
0
		public void AsyncLoad()
		{
			using (GetNewServer())
			using (var store = new DocumentStore
			{
				Url = "http://localhost:8079"
			}.Initialize())
			{
				using (var session = store.OpenAsyncSession())
				{
					session.Store(new Dummy() );

					session.SaveChangesAsync().Wait();
				}
				using (var session = store.OpenAsyncSession())
				{
					session.LoadAsync<Dummy>("dummies/1").Wait();
					Assert.Equal(0, store.JsonRequestFactory.NumberOfCachedRequests);
				}
				using (var session = store.OpenAsyncSession())
				{
					session.LoadAsync<Dummy>("dummies/1").Wait();
					Assert.Equal(1, store.JsonRequestFactory.NumberOfCachedRequests);
				}
			}
		}
Ejemplo n.º 2
0
		public IEnumerable<Task> CanPerformASimpleWhere()
		{
			var dbname = GenerateNewDatabaseName();
			using (var documentStore = new DocumentStore {Url = Url + Port}.Initialize())
			{
				yield return documentStore.AsyncDatabaseCommands.EnsureDatabaseExistsAsync(dbname);

				var entity = new Company {Name = "Async Company #1", Id = "companies/1"};
				using (var session = documentStore.OpenAsyncSession(dbname))
				{
					session.Store(entity);
					yield return session.SaveChangesAsync();
				}

				using (var session = documentStore.OpenAsyncSession(dbname))
				{
					var query = session.Query<Company>()
						.Where(x => x.Name == "Async Company #1")
						.ToListAsync();
					yield return query;

					Assert.AreEqual(1, query.Result.Count);
					Assert.AreEqual("Async Company #1", query.Result[0].Name);
				}
			}
		}
Ejemplo n.º 3
0
		public IEnumerable<Task> IncludingARelatedEntityShouldAvoidHittingTheServerTwice()
		{
			var dbname = GenerateNewDatabaseName();
			using (var documentStore = new DocumentStore {Url = Url + Port}.Initialize())
			{
				yield return documentStore.AsyncDatabaseCommands.EnsureDatabaseExistsAsync(dbname);

				var customer = new Customer {Name = "Customer #1", Id = "customer/1", Email = "*****@*****.**"};
				var order = new Order {Id = "orders/1", Note = "Hello", Customer = new DenormalizedReference {Id = customer.Id, Name = customer.Name}};
				using (var session = documentStore.OpenAsyncSession(dbname))
				{
					session.Store(customer);
					session.Store(order);
					yield return session.SaveChangesAsync();
				}

				using (var session = documentStore.OpenAsyncSession(dbname))
				{
					var query = session.Advanced.AsyncLuceneQuery<Order>()
						.Include(x => x.Customer.Id)
						.WhereEquals("Id", "orders/1")
						.ToListAsync();
					yield return query;

					Assert.AreEqual("Hello", query.Result.Item2[0].Note);

					// NOTE: this call should not hit the server 
					var load = session.LoadAsync<Customer>(customer.Id);
					yield return load;

					Assert.AreEqual(1, session.Advanced.NumberOfRequests);
				}
			}
		}
Ejemplo n.º 4
0
		public IEnumerable<Task> CanGetTotalCount()
		{
			var dbname = GenerateNewDatabaseName();
			using (var documentStore = new DocumentStore {Url = Url + Port}.Initialize())
			{
				yield return documentStore.AsyncDatabaseCommands.EnsureDatabaseExistsAsync(dbname);

				var entity = new Company {Name = "Async Company #1", Id = "companies/1"};
				using (var session = documentStore.OpenAsyncSession(dbname))
				{
					session.Store(entity);
					yield return session.SaveChangesAsync();
				}

				using (var session = documentStore.OpenAsyncSession(dbname))
				{
					RavenQueryStatistics stats;
					var query = session.Query<Company>()
						.Customize(x => x.WaitForNonStaleResults())
						.Statistics(out stats)
						.Where(x => x.Name == "Async Company #1")
						.CountAsync();
					yield return query;

					Assert.AreEqual(1, query.Result);
				}
			}
		}
Ejemplo n.º 5
0
        public void Can_query_using_async_session()
        {
            using(GetNewServer())
            using(var store = new DocumentStore
            {
                Url = "http://localhost:8080"
            }.Initialize())
            {
                using (var s = store.OpenAsyncSession())
                {
                    s.Store(new {Name = "Ayende"});
                    s.SaveChangesAsync().Wait();
                }

                using(var s = store.OpenAsyncSession())
                {
                    var queryResultAsync = s.Advanced.AsyncLuceneQuery<dynamic>()
                        .WhereEquals("Name", "Ayende")
                        .ToListAsync();

                    queryResultAsync.Wait();

                    Assert.Equal("Ayende",
                        queryResultAsync.Result[0].Name);
                }
            }
        }
		public IEnumerable<Task> CanInsertAsyncAndMultiGetAsync()
		{
			var dbname = GenerateNewDatabaseName();
			using (var documentStore = new DocumentStore {Url = Url + Port}.Initialize())
			{
				yield return documentStore.AsyncDatabaseCommands.EnsureDatabaseExistsAsync(dbname);

				var entity1 = new Company {Name = "Async Company #1"};
				var entity2 = new Company {Name = "Async Company #2"};
				using (var session_for_storing = documentStore.OpenAsyncSession(dbname))
				{
					session_for_storing.Store(entity1);
					session_for_storing.Store(entity2);
					yield return session_for_storing.SaveChangesAsync();
				}

				using (var session_for_loading = documentStore.OpenAsyncSession(dbname))
				{
					var task = session_for_loading.LoadAsync<Company>(new[] {entity1.Id, entity2.Id});
					yield return task;

					Assert.AreEqual(entity1.Name, task.Result[0].Name);
					Assert.AreEqual(entity2.Name, task.Result[1].Name);
				}
			}
		}
Ejemplo n.º 7
0
		public IEnumerable<Task> CanQueryUsingAsyncSession()
		{
			var dbname = GenerateNewDatabaseName();
			using (var documentStore = new DocumentStore {Url = Url + Port}.Initialize())
			{
				yield return documentStore.AsyncDatabaseCommands.EnsureDatabaseExistsAsync(dbname);

				using (var s = documentStore.OpenAsyncSession(dbname))
				{
					s.Store(new User {Name = "Ayende"});
					yield return s.SaveChangesAsync();
				}

				using (var s = documentStore.OpenAsyncSession(dbname))
				{
					var queryResultAsync = s.Advanced.AsyncLuceneQuery<User>()
						.WhereEquals("Name", "Ayende")
						.ToListAsync();

					yield return queryResultAsync;

					Assert.AreEqual("Ayende", queryResultAsync.Result.Item2[0].Name);
				}
			}
		}
        private async Task InitializeDocumentsCursor(CancellationToken cancellation)
        {
            using (var store = new DocumentStore())
            {
                store.ParseConnectionString(configuration.ConnectionString);
                store.Initialize(false);

                using (var session = store.OpenAsyncSession())
                {
                    if (String.IsNullOrEmpty(configuration.Query))
                    {
                        documentsCursor = await session.Advanced.StreamAsync<RavenJObject>(Etag.Empty, 0, int.MaxValue, null, cancellation);
                    }
                    else
                    {
                        var query = String.IsNullOrEmpty(configuration.Index)
                            ? session.Advanced.AsyncDocumentQuery<RavenJObject>()
                            : session.Advanced.AsyncDocumentQuery<RavenJObject>(configuration.Index);

                        // Streaming query API does not create a dynamic index, so user have to specify one if query is provided: http://issues.hibernatingrhinos.com/issue/RavenDB-1410
                        documentsCursor = await session.Advanced.StreamAsync<RavenJObject>(
                            query.Where(configuration.Query).NoCaching().NoTracking(), cancellation);
                    }
                }
            }
        }
Ejemplo n.º 9
0
		public async Task Sample()
		{
			using (var store = new DocumentStore())
			{
				var user = new RavenJObject
					{
						{"Name", "John"}
					};

				using (var session = store.OpenAsyncSession())
				{
					#region write_assurance_1
					await session.StoreAsync(user);
					await session.SaveChangesAsync();

					Etag userEtag = session
						.Advanced
						.GetEtagFor(user);

					int replicas = await store
						.Replication
						.WaitAsync(etag: userEtag, timeout: TimeSpan.FromMinutes(1), replicas: 1);
					#endregion

					#region write_assurance_2
					await store
						.Replication
						.WaitAsync();
					#endregion
				}
			}
		}
Ejemplo n.º 10
0
		public OpeningSession()
		{
			string databaseName = "DB1";

			using (var store = new DocumentStore())
			{
				#region open_session_2
				store.OpenSession(new OpenSessionOptions());
				#endregion

				#region open_session_3
				store.OpenSession(new OpenSessionOptions
									  {
										  Database = databaseName
									  });
				#endregion

				#region open_session_4
				using (IDocumentSession session = store.OpenSession())
				{
					// code here
				}
				#endregion

				#region open_session_5
				using (IAsyncDocumentSession session = store.OpenAsyncSession())
				{
					// async code here
				}
				#endregion
			}
		}
		public void Can_insert_sync_and_get_async()
		{
			using (var server = GetNewServer(port, path))
			{
				var documentStore = new DocumentStore { Url = "http://localhost:" + port };
				documentStore.Initialize();

				var entity = new Company { Name = "Async Company" };
				using (var session = documentStore.OpenSession())
				{
					session.Store(entity);
					session.SaveChanges();
				}

				using (var session = documentStore.OpenAsyncSession())
				{
					var asyncResult = session.BeginLoad(entity.Id, null, null);
					if (asyncResult.CompletedSynchronously == false)
						asyncResult.AsyncWaitHandle.WaitOne();

					var company = session.EndLoad<Company>(asyncResult);
					Assert.Equal("Async Company", company.Name);
				}
			}
		}
Ejemplo n.º 12
0
		public void WillResultInTheSameResults_Lucene_Async()
		{
			using (GetNewServer())
			using (var store = new DocumentStore
			{
				Url = "http://localhost:8079"
			}.Initialize())
			{
				using (var s = store.OpenSession())
				{
					s.Store(new User());
					s.Store(new User());
					s.SaveChanges();
				}

				using (var s = store.OpenAsyncSession())
				{
					var query = s.Advanced.AsyncLuceneQuery<User>();

					for (int i = 0; i < 5; i++)
					{
						var listAsync = query.ToListAsync();
						listAsync.Wait();
						foreach (var user in listAsync.Result.Item2)
						{
							Assert.NotNull(user.Id);
						}
					}
				}
			}
		}
Ejemplo n.º 13
0
		public async Task CanSaveAndLoad()
		{
			using (var store = new DocumentStore {Url = Url}.Initialize())
			{
				using (var session = store.OpenAsyncSession())
				{
					await session.StoreAsync(new User { Name = "Fitzchak" });
					await session.SaveChangesAsync();
				}

				using (var session = store.OpenAsyncSession())
				{
					var user = await session.LoadAsync<User>("users/1");
					Assert.NotNull(user);
					Assert.Equal("Fitzchak", user.Name);
				}
			}
		}
        public async Task CanStartWithoutServerAsync()
        {
            using (var store = new DocumentStore { Url = "http://localhost:8079" }.Initialize())
            {
                using (var session = store.OpenAsyncSession())
                {
                    await AssertAsync.Throws<HttpRequestException>(async () => await session.LoadAsync<User>("user/1"));
                }

                using (GetNewServer())
                {
                    using (var session = store.OpenAsyncSession())
                    {
                        Assert.Null(await session.LoadAsync<Item>("items/1"));
                    }
                }
            }
        }
		public async Task CanStartWithoutServerAsync()
		{
			using (var store = new DocumentStore { Url = "http://localhost:8079" }.Initialize())
			{
				using (var session = store.OpenAsyncSession())
				{
					var aggregateException = await AssertAsync.Throws<AggregateException>(async () => await session.LoadAsync<User>("user/1"));
					Assert.IsType<WebException>(aggregateException.Flatten().InnerException);
				}

				using (GetNewServer())
				{
					using (var session = store.OpenAsyncSession())
					{
						Assert.Null(await session.LoadAsync<Item>("items/1"));
					}
				}
			}
		}
Ejemplo n.º 16
0
		public async Task When_replicating_can_do_read_striping()
		{
			var store1 = CreateStore();
            var store2 = CreateStore();
            var store3 = CreateStore();

			using (var session = store1.OpenAsyncSession())
			{
				await session.StoreAsync(new Company());
				await session.SaveChangesAsync();
			}

			SetupReplication(store1.DatabaseCommands, store2, store3);

			WaitForDocument(store2.DatabaseCommands, "companies/1");
			WaitForDocument(store3.DatabaseCommands, "companies/1");

		    await PauseReplicationAsync(0, store1.DefaultDatabase);
            await PauseReplicationAsync(1, store2.DefaultDatabase);
            await PauseReplicationAsync(2, store3.DefaultDatabase);

		    using(var store = new DocumentStore
			{
				Url = store1.Url,
				Conventions =
					{
						FailoverBehavior = FailoverBehavior.ReadFromAllServers
					},
                    DefaultDatabase = store1.DefaultDatabase
			})
			{
				store.Initialize();
				var replicationInformerForDatabase = store.GetReplicationInformerForDatabase();
				await replicationInformerForDatabase.UpdateReplicationInformationIfNeeded((AsyncServerClient)store.AsyncDatabaseCommands);
				Assert.Equal(2, replicationInformerForDatabase.ReplicationDestinationsUrls.Count);

				foreach (var ravenDbServer in servers)
				{
					ravenDbServer.Server.ResetNumberOfRequests();
                    Assert.Equal(0, ravenDbServer.Server.NumberOfRequests);
				}

				for (int i = 0; i < 6; i++)
				{
					using(var session = store.OpenAsyncSession())
					{
						Assert.NotNull(await session.LoadAsync<Company>("companies/1"));
					}
				}
			}
			foreach (var ravenDbServer in servers)
			{
                Assert.True(2 == ravenDbServer.Server.NumberOfRequests, string.Format("Server at port: {0}. Requests: #{1}", ravenDbServer.SystemDatabase.Configuration.Port, ravenDbServer.Server.NumberOfRequests));
			}
		}
Ejemplo n.º 17
0
		public async Task AsyncQuery_WithWhereClause()
		{
			using (GetNewServer())
			using (var store = new DocumentStore {Url = "http://localhost:8079"}.Initialize())
			{
				using (var session = store.OpenAsyncSession())
				{
					await session.StoreAsync(new Dummy {Name = "oren"});
					await session.SaveChangesAsync();
				}
				using (var session = store.OpenAsyncSession())
				{
					var results = await session.Query<Dummy>()
					                           .Customize(x => x.WaitForNonStaleResults())
					                           .Where(x => x.Name == "oren")
					                           .ToListAsync();
					Assert.Equal(1, results.Count);
				}
			}
		}
		public void ExecutionExceptionsAreRethrown()
		{
			using (GetNewServer(port, path))
			using (var shard1 = new DocumentStore { Url = "http://localhost:8079" }.Initialize())
			using (var session = shard1.OpenAsyncSession())
			{
				var parallelShardAccessStrategy = new ParallelShardAccessStrategy();
				Assert.Throws<ApplicationException>(() => parallelShardAccessStrategy.ApplyAsync<object>(new[] { shard1.AsyncDatabaseCommands },
					new ShardRequestData(), (x, i) => { throw new ApplicationException(); }).Wait());
			}
		}
Ejemplo n.º 19
0
		public async Task AsyncLoadNonExistant()
		{
			// load a non-existant entity
			using (GetNewServer())
			using (var store = new DocumentStore {Url = "http://localhost:8079"}.Initialize())
			using (var session = store.OpenAsyncSession())
			{
				var loaded = await session.LoadAsync<Dummy>("dummies/-1337");
				Assert.Null(loaded);
			}
		}
Ejemplo n.º 20
0
        private static void RegisterRavenDB(Container container)
        {
            var store = new DocumentStore { ConnectionStringName = "Server" };

            store.Initialize();

            container.RegisterSingle<IDocumentStore>(store);

            container.RegisterPerWebRequest<IAsyncDocumentSession>(() => store.OpenAsyncSession());

            container.RegisterPerWebRequest<IDocumentSession>(() => store.OpenSession());
        }
Ejemplo n.º 21
0
		public async Task AsyncQuery()
		{
			using (GetNewServer())
			using (var store = new DocumentStore {Url = "http://localhost:8079"}.Initialize())
			using (var session = store.OpenAsyncSession())
			{
				var results = await session.Query<Dummy>().ToListAsync();
				Assert.Equal(0, results.Count);
				var results2 = await session.Query<Dummy>().ToListAsync();
				Assert.Equal(0, results2.Count);
			}
		}
Ejemplo n.º 22
0
 private static async Task DoTestAsync(DocumentStore store, int index)
 {
     using (var session = store.OpenAsyncSession())
     {
         await session.StoreAsync(new User
         {
             FirstName = "name-" + index,
             LastName = "last"
         });
         await session.SaveChangesAsync();
     }
 }
Ejemplo n.º 23
0
		public void Can_put_and_load_documet()
		{
			using (var store = new DocumentStore
			{
				Url = "http://localhost:8080"
			}.Initialize())
			{
				using (var session = store.OpenAsyncSession())
				{
					session.Store(new Item {Name = "Ayende", Id = "abc"});
					session.SaveChangesAsync().Wait();
				}

				using (var session = store.OpenAsyncSession())
				{
					var loadAsync = session.LoadAsync<dynamic>("abc");

					Assert.AreEqual("Ayende", loadAsync.Result.Name);
				}
			}
		}
		public IEnumerable<Task> CanInsertAsyncAndDeleteAsync()
		{
			var dbname = GenerateNewDatabaseName();
			using (var documentStore = new DocumentStore {Url = Url + Port}.Initialize())
			{
				yield return documentStore.AsyncDatabaseCommands.EnsureDatabaseExistsAsync(dbname);

				var entity = new Company {Name = "Async Company #1", Id = "companies/1"};
				using (var session = documentStore.OpenAsyncSession(dbname))
				{
					session.Store(entity);
					yield return session.SaveChangesAsync();
				}

				using (var for_loading = documentStore.OpenAsyncSession(dbname))
				{
					var loading = for_loading.LoadAsync<Company>(entity.Id);
					yield return loading;
					Assert.IsNotNull(loading.Result);
				}

				using (var for_deleting = documentStore.OpenAsyncSession(dbname))
				{
					var loading = for_deleting.LoadAsync<Company>(entity.Id);
					yield return loading;

					for_deleting.Delete(loading.Result);
					yield return for_deleting.SaveChangesAsync();
				}

				using (var for_verifying = documentStore.OpenAsyncSession(dbname))
				{
					var verification = for_verifying.LoadAsync<Company>(entity.Id);
					yield return verification;

					Assert.IsNull(verification.Result);
				}
			}
		}
		public void NullResultIsNotAnException()
		{
			using(GetNewServer(port, path))
			using (var shard1 = new DocumentStore { Url = "http://localhost:8079" }.Initialize())
			using (var session = shard1.OpenAsyncSession())
			{
				var results = new ParallelShardAccessStrategy().ApplyAsync(new[] { shard1.AsyncDatabaseCommands },
					new ShardRequestData(), (x, i) => CompletedTask.With((IList<Company>)null).Task).Result;

				Assert.Equal(1, results.Length);
				Assert.Null(results[0]);
			}
		}
Ejemplo n.º 26
0
		public void WithAsynchronousApiIdsAreGeneratedOnStoreAsync()
		{
			using (GetNewServer())
			using (var store = new DocumentStore
			{
				Url = "http://localhost:8079"
			}.Initialize())
			using (var session = store.OpenAsyncSession())
			{
				var obj = new TestObject { Name = "Test object" };
				session.StoreAsync(obj).Wait();
				Assert.NotNull(obj.Id);
			}
		}
Ejemplo n.º 27
0
		public void When_replicating_can_do_read_striping()
		{
			var store1 = CreateStore();
			var store2 = CreateStore();
			var store3 = CreateStore();

			using (var session = store1.OpenAsyncSession())
			{
				session.Store(new Company());
				session.SaveChangesAsync().Wait();
			}

			SetupReplication(store1.DatabaseCommands, store2.Url, store3.Url);

			WaitForDocument(store2.DatabaseCommands, "companies/1");
			WaitForDocument(store3.DatabaseCommands, "companies/1");

			using(var store = new DocumentStore
			{
				Url = store1.Url,
				Conventions =
					{
						FailoverBehavior = FailoverBehavior.ReadFromAllServers
					}
			})
			{
				store.Initialize();
				var replicationInformerForDatabase = store.GetReplicationInformerForDatabase();
				replicationInformerForDatabase.UpdateReplicationInformationIfNeeded((ServerClient) store.DatabaseCommands)
					.Wait();
				Assert.Equal(2, replicationInformerForDatabase.ReplicationDestinations.Count);

				foreach (var ravenDbServer in servers)
				{
					ravenDbServer.Server.ResetNumberOfRequests();
				}

				for (int i = 0; i < 6; i++)
				{
					using(var session = store.OpenAsyncSession())
					{
						Assert.NotNull(session.LoadAsync<Company>("companies/1").Result);
					}
				}
			}
			foreach (var ravenDbServer in servers)
			{
				Assert.Equal(2, ravenDbServer.Server.NumberOfRequests);
			}
		}
Ejemplo n.º 28
0
        public void Can_insert_async_and_multi_get_async()
        {
            using (var server = GetNewServer(port, path))
            {
                var documentStore = new DocumentStore { Url = "http://localhost:" + port };
                documentStore.Initialize();

                var entity1 = new Company { Name = "Async Company #1" };
                var entity2 = new Company { Name = "Async Company #2" };
                using (var session = documentStore.OpenAsyncSession())
                {
                    session.Store(entity1);
                    session.Store(entity2);
                    session.SaveChangesAsync().Wait();
                }

                using (var session = documentStore.OpenAsyncSession())
                {
                    var task = session.MultiLoadAsync<Company>(new[]{entity1.Id, entity2.Id});
                    Assert.Equal(entity1.Name, task.Result[0].Name);
                    Assert.Equal(entity2.Name, task.Result[1].Name);
                }
            }
        }
Ejemplo n.º 29
0
		public void CanChangeConventionJustForOneType_Async()
		{
			using(GetNewServer())
			using (var store = new DocumentStore{Url = "http://localhost:8079"}.Initialize())
			{
				store.Conventions.RegisterAsyncIdConvention<User>((dbName, cmds, user) => new CompletedTask<string>("users/" + user.Name));

				using (var session = store.OpenAsyncSession())
				{
					var entity = new User { Name = "Ayende" };
					session.Store(entity);
					session.SaveChangesAsync().Wait();
					Assert.Equal("users/Ayende", session.Advanced.GetDocumentId(entity));
				}
			}
		}
		public void CanFailoverReplicationBetweenTwoMultiTenantDatabases()
		{
			var store1 = CreateStore();
			var store2 = CreateStore();

			store1.DatabaseCommands.EnsureDatabaseExists("FailoverTest");
			store2.DatabaseCommands.EnsureDatabaseExists("FailoverTest");

			SetupReplication(store1.DatabaseCommands.ForDatabase("FailoverTest"),
			                 store2.Url + "/databases/FailoverTest");

			using (var store = new DocumentStore
			                   	{
			                   		DefaultDatabase = "FailoverTest",
			                   		Url = store1.Url,
			                   		Conventions =
			                   			{
			                   				FailoverBehavior = FailoverBehavior.AllowReadsFromSecondariesAndWritesToSecondaries
			                   			}
			                   	})
			{
				store.Initialize();
				var replicationInformerForDatabase = store.GetReplicationInformerForDatabase(null);
				replicationInformerForDatabase.UpdateReplicationInformationIfNeeded((ServerClient) store.DatabaseCommands)
					.Wait();

				using (var session = store.OpenAsyncSession())
				{
					session.Store(new Item {});
					session.SaveChangesAsync().Wait();
				}


				WaitForDocument(store2.DatabaseCommands.ForDatabase("FailoverTest"), "items/1");

				servers[0].Dispose();

				using (var session = store.OpenAsyncSession())
				{
					var load = session.LoadAsync<Item>("items/1").Result;
					Assert.NotNull(load);
				}
			}
		}