public static IDocumentSession GetRavenDBConnection() { DocumentStore documentStore = new DocumentStore(); documentStore.ConnectionStringName="RavenDB"; documentStore.Initialize(); return documentStore.OpenSession(); }
public void CanOverwriteIndex() { using (var server = GetNewServer(port, path)) { var store = new DocumentStore { Url = "http://localhost:" + port }; store.Initialize(); store.DatabaseCommands.PutIndex("test", new IndexDefinition { Map = "from doc in docs select new { doc.Name }" }, overwrite: true); store.DatabaseCommands.PutIndex("test", new IndexDefinition { Map = "from doc in docs select new { doc.Name }" }, overwrite: true); store.DatabaseCommands.PutIndex("test", new IndexDefinition { Map = "from doc in docs select new { doc.Email }" }, overwrite: true); store.DatabaseCommands.PutIndex("test", new IndexDefinition { Map = "from doc in docs select new { doc.Email }" }, overwrite: true); } }
public void CanReplicateBetweenTwoMultiTenantDatabases() { using (var store = new DocumentStore { DefaultDatabase = "FailoverTest", Url = store1.Url, Conventions = { FailoverBehavior = FailoverBehavior.AllowReadsFromSecondariesAndWritesToSecondaries } }) { store.Initialize(); var replicationInformerForDatabase = store.GetReplicationInformerForDatabase(null); var databaseCommands = (ServerClient) store.DatabaseCommands; replicationInformerForDatabase.UpdateReplicationInformationIfNeeded(databaseCommands) .Wait(); var replicationDestinations = replicationInformerForDatabase.ReplicationDestinationsUrls; Assert.NotEmpty(replicationDestinations); using (var session = store.OpenSession()) { session.Store(new Item()); session.SaveChanges(); } var sanityCheck = store.DatabaseCommands.Head("items/1"); Assert.NotNull(sanityCheck); WaitForDocument(store2.DatabaseCommands.ForDatabase("FailoverTest"), "items/1"); } }
public void CanTrackPosts() { using (GetNewServer()) using (var store = new DocumentStore { Url = "http://localhost:8080" }) { store.Initialize(); // make the replication check here using (var session = store.OpenSession()) { session.Load<User>("users/1"); } Guid id; using (var session = store.OpenSession()) { session.Store(new User()); session.SaveChanges(); id = session.Advanced.DatabaseCommands.ProfilingInformation.Id; } var profilingInformation = store.GetProfilingInformationFor(id); Assert.Equal(1, profilingInformation.Requests.Count); } }
static void Main(string[] args) { var store = new DocumentStore {Url = "http://localhost:8082"}; store.Initialize(); //store.DatabaseCommands.EnsureDatabaseExists("TestDb"); //using(var session = store.OpenSession("TestDb")) //{ // var agency = new Agency(); // agency.Name = "TestAgency"; // session.Store(agency); // session.SaveChanges(); //} using (var session = store.OpenSession("TestDb")) { var agency = session.Query<Agency>() .Where(a => a.Name == "TestAgency") .SingleOrDefault(); if (agency != null) Console.WriteLine(agency.Name); } Console.ReadLine(); }
public RavenDbRegistry(string connectionStringName) { For<IDocumentStore>() .Singleton() .Use(x => { var store = new DocumentStore { ConnectionStringName = connectionStringName, }; store.Initialize(); // Index initialisation. IndexCreation.CreateIndexes(typeof(RecentTags).Assembly, store); return store; } ) .Named("RavenDB Document Store."); For<IDocumentSession>() .AlwaysUnique() .Use(x => { var store = x.GetInstance<IDocumentStore>(); return store.OpenSession(); }) .Named("RavenDB Session (aka. Unit of Work)."); }
public void Can_create_index_using_linq_from_client() { using (var server = GetNewServer(port, path)) { var documentStore = new DocumentStore { Url = "http://localhost:" + port }; documentStore.Initialize(); documentStore.DatabaseCommands.PutIndex("UsersByLocation", new IndexDefinition<LinqIndexesFromClient.User> { Map = users => from user in users where user.Location == "Tel Aviv" select new { user.Name }, }); using (var session = documentStore.OpenSession()) { session.Store(new LinqIndexesFromClient.User { Location = "Tel Aviv", Name = "Yael" }); session.SaveChanges(); LinqIndexesFromClient.User single = session.Advanced.LuceneQuery<LinqIndexesFromClient.User>("UsersByLocation") .Where("Name:Yael") .WaitForNonStaleResults() .Single(); Assert.Equal("Yael", single.Name); } } }
public void CanAccessDbUsingDifferentNames() { using (GetNewServer()) { using (var documentStore = new DocumentStore { Url = "http://localhost:8080" }) { documentStore.Initialize(); documentStore.DatabaseCommands.EnsureDatabaseExists("repro"); using (var session = documentStore.OpenSession("repro")) { session.Store(new Foo { Bar = "test" }); session.SaveChanges(); } using (var session = documentStore.OpenSession("Repro")) { Assert.NotNull(session.Load<Foo>("foos/1")); } } } }
public RavenDB_560() { server1DataDir = NewDataPath("D1"); server2DataDir = NewDataPath("D2"); server1 = CreateServer(8001, server1DataDir); server2 = CreateServer(8002, server2DataDir); store1 = new DocumentStore { DefaultDatabase = "Northwind", Url = "http://" + Environment.MachineName + ":8001", }; store1.Initialize(false); store2 = new DocumentStore { DefaultDatabase = "Northwind", Url = "http://" + Environment.MachineName + ":8002" }; store2.Initialize(false); store1.DatabaseCommands.GlobalAdmin.CreateDatabase(new DatabaseDocument { Id = "Northwind", Settings = { { "Raven/ActiveBundles", "replication" }, { "Raven/DataDir", @"~\Databases1\Northwind" } } }); store2.DatabaseCommands.GlobalAdmin.CreateDatabase(new DatabaseDocument { Id = "Northwind", Settings = { { "Raven/ActiveBundles", "replication" }, { "Raven/DataDir", @"~\Databases2\Northwind" } } }); }
public CompressionAndEncryption() { path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Versioning.Versioning)).CodeBase); path = Path.Combine(path, "TestDb").Substring(6); Raven.Database.Extensions.IOExtensions.DeleteDirectory(path); settings = new Raven.Database.Config.RavenConfiguration { Port = 8079, RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true, DataDirectory = path, Settings = { {"Raven/Encryption/Key", "3w17MIVIBLSWZpzH0YarqRlR2+yHiv1Zq3TCWXLEMI8="}, {"Raven/ActiveBundles", "Compression;Encryption"} } }; ConfigureServer(settings); settings.PostInit(); ravenDbServer = new RavenDbServer(settings); documentStore = new DocumentStore { Url = "http://localhost:8079" }; documentStore.Initialize(); }
public static void Configure() { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); //register RavenDb DocumentStore builder.Register(x => { var store = new DocumentStore { ConnectionStringName = "RavenDb" }; store.Initialize(); IndexCreation.CreateIndexes(Assembly.GetCallingAssembly(), store); return store; }); //register RavenDb DocumentSession per Http request and SaveChanges on release of scope builder.Register(x => x.Resolve<DocumentStore>().OpenSession()) .As<IDocumentSession>() .InstancePerHttpRequest(); //.OnRelease(x => { using (x) { x.SaveChanges(); } }); builder.RegisterType<SupplierNameResolver>().InstancePerHttpRequest(); builder.RegisterType<CategoryNameResolver>().InstancePerHttpRequest(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
public AggressiveCaching() { using (var documentStore = new DocumentStore { Url = "http://localhost:8080" }) { documentStore.Initialize(); #region should_cache_delegate documentStore.Conventions.ShouldCacheRequest = url => true; #endregion #region max_number_of_requests documentStore.MaxNumberOfCachedRequests = 2048; #endregion using (var session = documentStore.OpenSession()) { #region aggressive_cache_load using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(5))) { var user = session.Load<User>("users/1"); } #endregion } using (var session = documentStore.OpenSession()) { #region aggressive_cache_query using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(5))) { var users = session.Query<User>().ToList(); } #endregion } } }
public CascadeDelete() { path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(CascadeDelete)).CodeBase); path = Path.Combine(path, "TestDb").Substring(6); database::Raven.Database.Extensions.IOExtensions.DeleteDirectory("Data"); ravenDbServer = new RavenDbServer( new database::Raven.Database.Config.RavenConfiguration { Port = 58080, RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true, DataDirectory = path, Catalog = { Catalogs = { new AssemblyCatalog(typeof (CascadeDeleteTrigger).Assembly) } }, }); documentStore = new DocumentStore { Url = "http://localhost:58080" }; documentStore.Initialize(); }
public static IDocumentStore Production() { var store = new DocumentStore { ConnectionStringName = "Data" }; store.Initialize(); IndexCreation.CreateIndexes(typeof(Record).Assembly, store); return store; }
protected void Application_Start() { DocumentStore = new DocumentStore { DefaultDatabase = "Polyglot.UI.Orders", Url = "http://localhost:8080" }; DocumentStore.Initialize(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); Bus = Configure .With() .DefaultBuilder() .XmlSerializer() .MsmqTransport() .UnicastBus() .SendOnly(); }
public void can_use_RavenDB_in_a_remote_process_for_batch_operations() { var documentConvention = new DocumentConvention(); using (var driver = new RavenDBDriver("HelloShard", documentConvention)) { driver.Start(); using (var store = new DocumentStore() { Url = driver.Url, Conventions = documentConvention }) { store.Initialize(); using (var session = store.OpenSession()) { session.Advanced.DatabaseCommands.Batch(new[] {GetPutCommand()}); session.SaveChanges(); } } using (var store = driver.GetDocumentStore()) { should_find_expected_value_in(store); } } }
public ActionResult Index() { using (var documentStore = new DocumentStore { Url = "http://localhost:8080/", DefaultDatabase = "msftuservoice" }) { documentStore.Initialize(); IndexCreation.CreateIndexes(typeof(ByCategoryIndex).Assembly, documentStore); using(var session = documentStore.OpenSession()) { RavenQueryStatistics totalStats; var resultTotal = session.Query<Suggestion>(). Statistics(out totalStats). ToArray(); ViewBag.Total = totalStats.TotalResults; RavenQueryStatistics dateStats; var resultByDate = session.Query<ByDateIndex.ByDateResult, ByDateIndex>().Statistics(out dateStats).ToList(); var orderbyDate = resultByDate.OrderBy(x => x.ParsedDate).ToList(); string foobar = resultByDate.ToString(); } } return View(); }
static async Task AsyncMain() { using (new RavenHost()) { BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.RavenDBCustomSagaFinder"); busConfiguration.UseSerialization<JsonSerializer>(); busConfiguration.EnableInstallers(); busConfiguration.SendFailedMessagesTo("error"); DocumentStore documentStore = new DocumentStore { Url = "http://localhost:32076", DefaultDatabase = "NServiceBus" }; documentStore.RegisterListener(new UniqueConstraintsStoreListener()); documentStore.Initialize(); busConfiguration.UsePersistence<RavenDBPersistence>() .DoNotSetupDatabasePermissions() //Only required to simplify the sample setup .SetDefaultDocumentStore(documentStore); IEndpointInstance endpoint = await Endpoint.Start(busConfiguration); await endpoint.SendLocal(new StartOrder { OrderId = "123" }); Console.WriteLine("Press any key to exit"); Console.ReadKey(); await endpoint.Stop(); } }
public ActionResult AddCountSoldtoAlbum() { using (var documentStore = new DocumentStore { Url = "http://localhost:8080" }) { documentStore.Initialize(); using (var session = documentStore.OpenSession()) { int count = 0; do { var albums = session.Advanced.LuceneQuery<Album>() .Skip(count) .Take(128) .ToArray(); if (albums.Length == 0) break; foreach (var album in albums) { var result = session.Advanced.LuceneQuery<SoldAlbum>("SoldAlbums") .Where("Album:" + album.Id) .SingleOrDefault(); album.CountSold = result == null ? 0 : result.Quantity; } count += albums.Length; session.SaveChanges(); session.Advanced.Clear(); } while (true); } } return Content("OK"); }
public void ProperlyHandleDataDirectoryWhichEndsWithSlash() { server1 = CreateServer(8079, "D1"); store1 = new DocumentStore { DefaultDatabase = "Northwind", Url = "http://*****:*****@"~\D1\N" } } }); store1.DatabaseCommands.ForDatabase("Northwind").Get("force/load/of/db"); Assert.True( Directory.Exists(Path.Combine(server1.SystemDatabase.Configuration.DataDirectory, "N"))); }
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); } } }
private static void InitialiseRaven() { Store = new DocumentStore {ConnectionStringName = "RavenDB"}; Store.Initialize(); IndexCreation.CreateIndexes(Assembly.GetCallingAssembly(), Store); }
public void Given_WhenWhen_ShouldExpectedResult() { var documentStore = new DocumentStore { Url = "http://mamluka-pc:4253" }; documentStore.Initialize(); var fixture = new Fixture(); using (var session = documentStore.OpenSession()) { var theList = fixture.CreateMany<Contact>(1000).ToList(); theList.Take(500).ToList().ForEach(x => x.DomainGroup = "a"); theList.Skip(500).Take(500).ToList().ForEach(x => x.DomainGroup = "b"); var bigDoc = new Holder { TheList = theList }; session.Store(bigDoc); session.SaveChanges(); } documentStore.DatabaseCommands.PutIndex("Count_Contacts", new IndexDefinitionBuilder<Holder, SummeryOfDomains> { Map = contacts => contacts.SelectMany(x => x.TheList).Select(x => new { x.DomainGroup, Count = 1 }), Reduce = results => results.GroupBy(x => x.DomainGroup).Select(x => new { DomainGroup = x.Key, Count = x.Sum(m => m.Count) }) }, true); using (var session = documentStore.OpenSession()) { Trace.WriteLine(session.Query<List<int>>("Count_Contacts").First()); } }
public void CanFailoverReplicationBetweenTwoMultiTenantDatabases() { 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.OpenSession()) { session.Store(new Item()); session.SaveChanges(); } WaitForDocument(store2.DatabaseCommands.ForDatabase("FailoverTest"), "items/1"); servers[0].Dispose(); using (var session = store.OpenSession()) { var load = session.Load<Item>("items/1"); Assert.NotNull(load); } } }
public void CreateNewDocumentAnd_AndMakeChanges() { using (var docStore = new DocumentStore { Url = "http://localhost:8080", DefaultDatabase = "OptimisticConcurencyTestDB" }) { docStore.Initialize(); string id = null; using (var session = docStore.OpenSession()) { var item = new Item { Name = "ItemInInitialState" }; session.Store(item); session.SaveChanges(); id = item.Id; } using (var sessionFirst = docStore.OpenSession()) { using (var sessionSecond = docStore.OpenSession()) { sessionSecond.Advanced.UseOptimisticConcurrency = true; var itemFirst = sessionFirst.Load<Item>(id); var itemSecond = sessionSecond.Load<Item>(id); itemFirst.Name = "ChangedByItemFirst"; sessionFirst.SaveChanges(); itemSecond.Name = "ChangedbyItemSecond"; sessionSecond.SaveChanges(); // this line should throw if optimistic concurency is enabled. } } } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); Store = new DocumentStore() { ConnectionStringName = "Onboarding" }; Store.Initialize(); var builder = new ContainerBuilder(); Store.Conventions.RegisterIdConvention<User>((dbname, commands, user) => "users/" + user.UserName); builder.Register(c => { var store = new DocumentStore { ConnectionStringName = "Onboarding", DefaultDatabase = "Onboarding" }.Initialize(); return store; }).As<IDocumentStore>().SingleInstance(); builder.Register(c => c.Resolve<IDocumentStore>().OpenAsyncSession()).As<IAsyncDocumentSession>().InstancePerLifetimeScope(); }
public void LoadExistingDocument_AndMakeChanges() { using (var docStore = new DocumentStore { Url = "http://localhost:8080", DefaultDatabase = "OptimisticConcurencyTestDB" }) { docStore.Initialize(); string id = "items/33"; using (var sessionFirst = docStore.OpenSession()) { using (var sessionSecond = docStore.OpenSession()) { sessionSecond.Advanced.UseOptimisticConcurrency = true; var itemFirst = sessionFirst.Load<Item>(id); var itemSecond = sessionSecond.Load<Item>(id); itemFirst.Name = "ChangedByItemFirst"; sessionFirst.SaveChanges(); itemSecond.Name = "ChangedbyItemSecond"; sessionSecond.SaveChanges(); // this line should throw if optimistic concurency is enabled. } } } }
public Expiration() { path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Versioning.Versioning)).CodeBase); path = Path.Combine(path, "TestDb").Substring(6); database::Raven.Database.Extensions.IOExtensions.DeleteDirectory("Data"); ravenDbServer = new RavenDbServer( new database::Raven.Database.Config.RavenConfiguration { Port = 8079, RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true, DataDirectory = path, Catalog = { Catalogs = { new AssemblyCatalog(typeof (ExpirationReadTrigger).Assembly) } }, Settings = { {"Raven/Expiration/DeleteFrequencySeconds", "1"} } }); ExpirationReadTrigger.GetCurrentUtcDate = () => DateTime.UtcNow; documentStore = new DocumentStore { Url = "http://localhost:8079" }; documentStore.Initialize(); }
public void can_use_RavenDB_in_a_remote_process() { var documentConvention = new DocumentConvention(); using (var driver = new RavenDBDriver("HelloShard", documentConvention)) { driver.Start(); using (var store = new DocumentStore() { Url = driver.Url, Conventions = documentConvention }) { store.Initialize(); using (var session = store.OpenSession()) { session.Store(new Tuple<string, string>("hello", "world")); session.SaveChanges(); } } using (var store = driver.GetDocumentStore()) { should_find_expected_value_in(store); } } }
public static DocumentStore SpinUpNewDB() { DocumentStore documentStore = new DocumentStore { Url = "http://localhost:8080" }; documentStore.DefaultDatabase = "TestDB" + DateTime.Now.Ticks; documentStore.Initialize(); return documentStore; }
public void SearchGroupsTest() { var documentStore = new Raven.Client.Document.DocumentStore { Url = "http://localhost:8080", DefaultDatabase = "TestDB" }; documentStore.Initialize(); ProductGroupper target = new ProductGroupper(documentStore); string searchStr = "Acer*"; Dictionary <string, List <Product> > actual; actual = target.SearchStoreProductGroups(searchStr); Assert.IsNotNull(actual); Assert.IsTrue(actual.Count == 2); }