Manages access to RavenDB and open sessions to work with RavenDB. Also supports hosting RavenDB in an embedded mode
Inheritance: Raven.Client.Document.DocumentStore
        public static IContainer InMemoryStartup()
        {
            var presentationdocumentStore = new EmbeddableDocumentStore
            {
                RunInMemory = true,
            };

            presentationdocumentStore.Initialize();

            ObjectFactory.Initialize(config =>
            {
                config.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();

                });
                config.AddRegistry(new CoreRegistry(presentationdocumentStore));

            });

            ObjectFactory.AssertConfigurationIsValid();
            ObjectFactory.WhatDoIHave();
            WaitForIndexes(presentationdocumentStore);
            IndexCreation.CreateIndexes(typeof(Users_ByUsername).Assembly, presentationdocumentStore);
            WaitForIndexes(presentationdocumentStore);

            return ObjectFactory.Container;
        }
Beispiel #2
0
        public void CanQueryMetadata()
        {
            using (var store = new EmbeddableDocumentStore { RunInMemory = true })
            {
                store.Initialize();
                using (var s = store.OpenSession())
                {
                    s.Store(new User
                    {
                        Metadata =
                        {
                            IsActive = true
                        }
                    });
                    s.SaveChanges();
                }

                using (var s = store.OpenSession())
                {
                    var actual = s.Query<User>()
                        .Customize(x=>x.WaitForNonStaleResultsAsOfLastWrite())
                        .Where(x => x.Metadata.IsActive == true)
                        .Count();
                    Assert.Equal(1, actual);
                }
            }
        }
Beispiel #3
0
		public void DocumentStoreWorksWhenAddingItemThenDeletingItAndThenGrabbingNonExistingItemAndStoringNewOne()
		{
			using (var documentStore = new EmbeddableDocumentStore { RunInMemory = true }.Initialize())
			{
				documentStore.Conventions.AllowQueriesOnId = true;
				using (var session = documentStore.OpenSession())
				{
					var deletedModel = new TestModel { Id = 1 };
					session.Store(deletedModel);
					session.SaveChanges();

					session.Delete(deletedModel);
					session.SaveChanges();

					TestModel testModelItem = session.Query<TestModel>().SingleOrDefault(t => t.Id == 2) ??
												  new TestModel { Id = 2 };
					Assert.NotNull(testModelItem);
					session.Store(testModelItem);
					session.SaveChanges();

					var list = session.Query<TestModel>()
						.Customize(x => x.WaitForNonStaleResults())
						.ToList();
					Assert.Equal(1, list.Count());
				}
			}
		}
Beispiel #4
0
 /// <summary>
 /// Configures StructureMap to look for registries.
 /// </summary>
 /// <returns></returns>
 public static IContainer Initialize()
 {
     ObjectFactory.Initialize(x => {
         var documentStore = new EmbeddableDocumentStore { ConnectionStringName = "RavenDB" };
         documentStore.Conventions.FindTypeTagName = type => typeof(IPageModel).IsAssignableFrom(type) ? "Pages" : null;
         documentStore.RegisterListener(new StoreListener());
         documentStore.Initialize();
         IndexCreation.CreateIndexes(typeof(Documents_ByParent).Assembly, documentStore);
         x.For<IDocumentStore>().Use(documentStore);
         x.For<IDocumentSession>()
             .HybridHttpOrThreadLocalScoped()
             .Use(y =>
             {
                 var store = y.GetInstance<IDocumentStore>();
                 return store.OpenSession();
             });
         x.For<IVirtualPathResolver>().Use<VirtualPathResolver>();
         x.For<IPathResolver>().Use<PathResolver>();
         x.For<IPathData>().Use<PathData>();
         x.For<IControllerMapper>().Use<ControllerMapper>();
         x.For<ISettings>().Use<Settings>();
         x.Scan(scanner =>
         {
             scanner.AssembliesFromApplicationBaseDirectory();
             scanner.Convention<PageTypeRegistrationConvetion>();
         });
         x.For<IPageModel>().UseSpecial(y => y.ConstructedBy( r => ((MvcHandler) HttpContext.Current.Handler).RequestContext.RouteData.GetCurrentPage<IPageModel>()));
         x.For<IStructureInfo>().UseSpecial(y => y.ConstructedBy(r => ((MvcHandler)HttpContext.Current.Handler).RequestContext.RouteData.Values["StructureInfo"] as IStructureInfo));
     });
     return ObjectFactory.Container;
 }
		public static void Startup() {
		
			var sampleFrameworkDb = new EmbeddableDocumentStore {
				DataDirectory = "App_Data\\RavenDb",
				UseEmbeddedHttpServer = true
			};
			
			sampleFrameworkDb.RegisterListener(new DocumentConversionListener());
			sampleFrameworkDb.Conventions.FindClrTypeName = FindClrTypeName;
			sampleFrameworkDb.Conventions.FindTypeTagName = FindTypeTagName;
			sampleFrameworkDb.Conventions.JsonContractResolver = new DPContractResolver();
			sampleFrameworkDb.Conventions.ShouldCacheRequest = url => false;
			sampleFrameworkDb.Conventions.CustomizeJsonSerializer = serializer => {
				serializer.ContractResolver = new DPContractResolver();
				serializer.Converters.Add(new ModelCreationConverter());
			};

			sampleFrameworkDb.Initialize();
			sampleFrameworkDb.DatabaseCommands.DisableAllCaching();

			ObjectFactory.Initialize(x => {

				x.AddRegistry(new RavenDbRegistry(sampleFrameworkDb));
				x.AddRegistry(new RepositoryRegistry());

			});

		}
Beispiel #6
0
        public void can_persist_and_query_documents()
        {
            using (var store = new EmbeddableDocumentStore
                {
                    RunInMemory = true,
                    DataDirectory = "RavenData"
                }
            )
            {

                store.Initialize();

                using (var session = store.OpenSession())
                {
                    var user = new User
                    {
                        Email = "*****@*****.**",
                        FirstName = "Micky",
                        LastName = "Bubbles",
                    };

                    session.Store(user);
                    session.SaveChanges();
                    Assert.AreEqual(true, session.Query<User>().Where(x => x.Email == "*****@*****.**").Any());

                }

            }
        }
Beispiel #7
0
		public RavenDB_2767()
		{
			store = NewDocumentStore();
			var workContext = store.SystemDatabase.WorkContext;
			prefetchingBehavior = new PrefetchingBehavior(PrefetchingUser.Indexer, workContext, new IndexBatchSizeAutoTuner(workContext));
			prefetchingBehavior.ShouldHandleUnusedDocumentsAddedAfterCommit = true;
		}
Beispiel #8
0
        public void WhenAnEventIsWrittenToTheSinkItIsRetrievableFromTheDocumentStore()
        {
            using (var documentStore = new EmbeddableDocumentStore {RunInMemory = true}.Initialize())
            {
                var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
                var exception = new ArgumentException("Mládek");
                const LogEventLevel level = LogEventLevel.Information;
                const string messageTemplate = "{Song}++";
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };

                using (var ravenSink = new RavenDBSink(documentStore, 2, TinyWait, null))
                {
                    var template = new MessageTemplateParser().Parse(messageTemplate);
                    var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties);
                    ravenSink.Emit(logEvent);
                }

                using (var session = documentStore.OpenSession())
                {
                    var events = session.Query<LogEvent>().Customize(x => x.WaitForNonStaleResults()).ToList();
                    Assert.AreEqual(1, events.Count);
                    var single = events.Single();
                    Assert.AreEqual(messageTemplate, single.MessageTemplate);
                    Assert.AreEqual("\"New Macabre\"++", single.RenderedMessage);
                    Assert.AreEqual(timestamp, single.Timestamp);
                    Assert.AreEqual(level, single.Level);
                    Assert.AreEqual(1, single.Properties.Count);
                    Assert.AreEqual("New Macabre", single.Properties["Song"]);
                    Assert.AreEqual(exception.Message, single.Exception.Message);
                }
            }
        }
Beispiel #9
0
        public ProjectionTests()
        {
            documentStore = NewDocumentStore(configureStore: store => store.RegisterListener(new NoStaleQueriesAllowed()));
            session = documentStore.OpenSession();

            Setup();
        }
		public void SuccessTest1()
		{
			using (IDocumentStore documentStore = new EmbeddableDocumentStore
			{
				RunInMemory = true
			}.Initialize())
			{
				dynamic expando = new ExpandoObject();

				using (IDocumentSession session = documentStore.OpenSession())
				{
					session.Store(expando);

					RavenJObject metadata =
						session.Advanced.GetMetadataFor((ExpandoObject)expando);

					metadata[PropertyName] = RavenJToken.FromObject(true);

					session.SaveChanges();
				}

				using (IDocumentSession session = documentStore.OpenSession())
				{
					var loaded =
						session.Load<dynamic>((string)expando.Id);

					RavenJObject metadata =
						session.Advanced.GetMetadataFor((DynamicJsonObject)loaded);
					RavenJToken token = metadata[PropertyName];

					Assert.NotNull(token);
					Assert.True(token.Value<bool>());
				}
			}
		}
        public void Should_give_documents_where_ExpirationDate_is_null_or_expirationdate_greater_than_today()
        {
            using (var documentStore = new EmbeddableDocumentStore
                                           {
                                               RunInMemory = true,
                                               Conventions =
                                                   {
                                                       DefaultQueryingConsistency =
                                                           ConsistencyOptions.QueryYourWrites
                                                   }
                                           })
            {
                documentStore.Initialize();

                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo());
                    session.Store(new Foo());
                    session.SaveChanges();
                }
                using (var session = documentStore.OpenSession())
                {
                    var bar =
                        session.Query<Foo>()
                               .Where(foo => foo.ExpirationTime == null || foo.ExpirationTime > DateTime.Now)
                               .ToList();
                    Assert.That(bar.Count, Is.EqualTo(2));
                }
            }
        }
        static void Main(string[] args)
        {
            var cfg = new HttpSelfHostConfiguration("http://localhost:1337");

            cfg.MaxReceivedMessageSize = 16L * 1024 * 1024 * 1024;
            cfg.TransferMode = TransferMode.StreamedRequest;
            cfg.ReceiveTimeout = TimeSpan.FromMinutes(20);

            cfg.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            cfg.Routes.MapHttpRoute(
                "Default", "{*res}",
                new { controller = "StaticFile", res = RouteParameter.Optional });

            var db = new EmbeddableDocumentStore { DataDirectory = new FileInfo("db/").DirectoryName };
            db.Initialize();
            cfg.Filters.Add(new RavenDbApiAttribute(db));

            using (HttpSelfHostServer server = new HttpSelfHostServer(cfg))
            {
                Console.WriteLine("Initializing server.");
                server.OpenAsync().Wait();
                Console.WriteLine("Server ready at: " + cfg.BaseAddress);
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
        public void ReturnsBooksByPriceLimit()
        {
            using (var docStore = new EmbeddableDocumentStore { RunInMemory = true }
                .Initialize()
                )
            {
                using (var session = docStore.OpenSession())
                {
                    // Store test data
                    session.Store(new Book { Title = "Test book", YearPublished = 2013, Price = 12.99 });
                    session.SaveChanges();
                }

                var controller = new BooksController { RavenSession = docStore.OpenSession() };

                var viewResult = (ViewResult)controller.ListByPriceLimit(15);
                var result = viewResult.ViewData.Model as List<Book>;
                Assert.IsNotNull(result);
                Assert.AreEqual(1, result.Count);

                viewResult = (ViewResult)controller.ListByPriceLimit(10);
                result = viewResult.ViewData.Model as List<Book>;
                Assert.IsNotNull(result);
                Assert.AreEqual(0, result.Count);

                controller.RavenSession.Dispose();
            }
        }
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredIfValidator));
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(AssertThatAttribute), typeof(AssertThatValidator));

            // override standard error messages
            ClientDataTypeModelValidatorProvider.ResourceClassKey = "DefaultResources";
            DefaultModelBinder.ResourceClassKey = "DefaultResources";

            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(MyRequiredAttributeAdapter));

            // setting locale
            var culture = new CultureInfo("nb-NO");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;

            // init log4net
            log4net.Config.XmlConfigurator.Configure();

            MvcHandler.DisableMvcResponseHeader = true;

            Store = new EmbeddableDocumentStore { ConnectionStringName = "RavenDB" };
            Store.Initialize();
        }
Beispiel #15
0
		public void ShouldOnlyBeInDataDir()
		{
			IOExtensions.DeleteDirectory("App_Data");
			IOExtensions.DeleteDirectory("Data");

			Assert.False(Directory.Exists("App_Data"));
			Assert.False(Directory.Exists("Data"));


			using (var store = new EmbeddableDocumentStore {DataDirectory = "App_Data"}.Initialize())
			{
				using (var session = store.OpenSession())
				{
					string someEmail = "*****@*****.**";
					session.Query<User>().Where(u => u.Email == someEmail).FirstOrDefault();
					session.Store(new User {Email = "*****@*****.**"});
					session.SaveChanges();
					session.Query<User>()
						.Customize(x => x.WaitForNonStaleResultsAsOfNow())
						.Where(u => u.Email == someEmail)
						.Single();
				}
			}

			Assert.True(Directory.Exists("App_Data"));
			Assert.False(Directory.Exists("Data"));

			IOExtensions.DeleteDirectory("App_Data");
			IOExtensions.DeleteDirectory("Data");

		}
Beispiel #16
0
        public Class1()
        {
            Person myObject = new Person()
                                   {
                                       Date = DateTime.Now,
                                       Name = "Jack"
                                   };

            var documentStore = new EmbeddableDocumentStore()
                                    {
                                        DataDirectory = "Data"
                                    };
            documentStore.Initialize();
            Console.WriteLine("inited");
            var session = documentStore.OpenSession();
            Console.WriteLine("session open");
            session.Store(myObject);
            session.SaveChanges();
            Console.WriteLine("changes saved");
            Thread.Sleep(1000);
            foreach (Person queryResponse in session.Query<Person>().Where(o => o.Name == "Jack"))
            {
                Console.WriteLine(queryResponse.Name + ".");
            }
            Console.WriteLine("done");
            Console.ReadLine();
        }
Beispiel #17
0
        public ScriptHelper()
        {
            var p1 = Path.Combine("Data", "System.db");
            SystemStore = new EmbeddableDocumentStore { DataDirectory = p1 };
            SystemStore.Initialize();
            System = SystemStore.OpenSession();
            SystemStore.Conventions.RegisterIdConvention<DbSetting>((db, cmds, setting) => "Settings/" + setting.Name);
            SystemStore.Conventions.RegisterIdConvention<DbScript>((db, cmds, script) => "Scripts/" + script.Name);
            try
            {
                SystemStore.DatabaseCommands.PutIndex("Settings/ByName", new IndexDefinitionBuilder<DbSetting>
                {
                    Map = settings =>
                          from setting
                              in settings
                          select new { setting.Name }
                });
                SystemStore.DatabaseCommands.PutIndex("Scripts/ByName", new IndexDefinitionBuilder<DbScript>
                {
                    Map = scripts =>
                          from script
                              in scripts
                          select new { script.Name }
                });
            }
            catch (Exception)
            {

            }

            IndexCreation.CreateIndexes(typeof(DbScript).Assembly,SystemStore);
            IndexCreation.CreateIndexes(typeof(DbSetting).Assembly, SystemStore);
        }
Beispiel #18
0
        public void AddTest()
        {
            var cacheKey = new CacheKey("/api/Cars", new[] { "1234", "abcdef" });
            var documentStore = new EmbeddableDocumentStore()
            {
                RunInMemory = true
            }.Initialize();

            new RavenDocumentsByEntityName().Execute(documentStore);

            var store = new RavenDbEntityTagStore(documentStore);
            var value = new TimedEntityTagHeaderValue("\"abcdef1234\"") { LastModified = DateTime.Now };

            // first remove them
            store.RemoveAllByRoutePattern(cacheKey.RoutePattern);

            // add
            store.AddOrUpdate(cacheKey, value);

            // get
            TimedEntityTagHeaderValue dbValue;
            store.TryGetValue(cacheKey, out dbValue);

            Assert.AreEqual(value.Tag, dbValue.Tag);
            Assert.AreEqual(value.LastModified.ToString(), dbValue.LastModified.ToString());
        }
        public when_querying_cases_by_name_using_danish_collation()
        {
            var culture = new CultureInfo("da");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;

            store = new EmbeddableDocumentStore
            {
                RunInMemory = true
            };
            store.Initialize();

            using (var session = store.OpenSession())
            {
                session.Store(new Case { Name = "bcda" });
                session.Store(new Case { Name = "dacb" });
                session.Store(new Case { Name = "daab" });
                session.Store(new Case { Name = "dacb" });
                session.Store(new Case { Name = "aacb" });
                session.Store(new Case { Name = "aaac" });
                session.Store(new Case { Name = "bcbb" });
                session.Store(new Case { Name = "acba" });
                session.Store(new Case { Name = "aaaa" });
                session.Store(new Case { Name = "dada" });
                session.SaveChanges();
            }
        }
        public IDocumentStore GetRavenDBStore()
        {
            var hasRavenConnectionString = ConfigurationManager.ConnectionStrings["RavenDB"] != null;
            IDocumentStore docStore;
            if (hasRavenConnectionString)
            {
                docStore = new DocumentStore
                    {
                        ConnectionStringName = "RavenDB",
                        DefaultDatabase = "BusRouteLondonDB"
                    };
            }
            else
            {
                //NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8080);
                docStore = new EmbeddableDocumentStore
                    {
                        //RunInMemory = true,
                        DataDirectory = "~/App_Data/Raven",
                        //UseEmbeddedHttpServer = true
                    };
            }

            docStore.Initialize();

            docStore.Conventions.RegisterIdConvention<BusRoute>(
                (dbName, command, route) =>
                string.Format("busroutes/{0}-{1}-{2}", route.Route, route.Run, route.Sequence));

            return docStore;
        }
Beispiel #21
0
		protected AuthenticationTest()
		{
			database::Raven.Database.Extensions.IOExtensions.DeleteDirectory("Data");
			embeddedStore = new EmbeddableDocumentStore()
			{
				Configuration = 
					{
						AnonymousUserAccessMode = database::Raven.Database.Server.AnonymousUserAccessMode.Get,
						Catalog = {Catalogs = {new AssemblyCatalog(typeof (AuthenticationUser).Assembly)}},
						DataDirectory = "Data",
						RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true,
						AuthenticationMode = "oauth",
						Port = 8079,
						OAuthTokenCertificate = database::Raven.Database.Config.CertGenerator.GenerateNewCertificate("RavenDB.Test")
					},
				UseEmbeddedHttpServer = true,
			};

			embeddedStore.Configuration.Initialize();
			embeddedStore.Initialize();
			store = new DocumentStore
			{
				Url = embeddedStore.Configuration.ServerUrl,
			};
			store.Initialize();
			store.JsonRequestFactory.
				EnableBasicAuthenticationOverUnsecureHttpEvenThoughPasswordsWouldBeSentOverTheWireInClearTextToBeStolenByHackers =
				true;
			foreach (DictionaryEntry de in HttpRuntime.Cache)
			{
				HttpRuntime.Cache.Remove((string)de.Key);
			}
		}
Beispiel #22
0
		public void WorkWithTransactionAndNoAllowNonAutoritiveInformation()
		{
			using (var store = new EmbeddableDocumentStore
			{
				RunInMemory = true
			}.Initialize())
			{
				using (new TransactionScope())
				{
					using (IDocumentSession session = store.OpenSession())
					{
						var user = new User {Id = "users/[email protected]"};
						session.Store(user);
						session.SaveChanges();
					}

					using(new TransactionScope(TransactionScopeOption.Suppress))
					using (IDocumentSession session = store.OpenSession())
					{
						var user = session.Load<User>("users/[email protected]");
						Assert.Null(user);
					}
				}

				
			}
		}
        public PostSchedulingStrategyTests()
        {
            Now = DateTimeOffset.Now;

            DocumentStore = new EmbeddableDocumentStore { RunInMemory = true }.Initialize();
            Session = DocumentStore.OpenSession();
        }
Beispiel #24
0
        public void Test_paralel_operations_with_multiple_EmbeddableDocumentStores()
        {
            Action storeAndRead = () =>
            {
                using (var store = new EmbeddableDocumentStore
                {
                    RunInMemory = true
                })
                {
                    store.Initialize();
                    using (var session = store.OpenSession())
                    {
                        session.Store(new Document { Value = "foo" }, "documents/1");
                        session.SaveChanges();
                    }
                    using (var session = store.OpenSession())
                    {
                        var doc = session.Load<Document>("documents/1");
                        Assert.Equal("foo", doc.Value);
                    }
                }
            };

            storeAndRead();

            var tasks = Enumerable.Range(1, 10).Select(_ => Task.Run(storeAndRead)).ToArray();

            Task.WaitAll(tasks);
        }
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var documentStore = new EmbeddableDocumentStore
                {
                    UseEmbeddedHttpServer = true,
                    DataDirectory = "App_Data",
                    Configuration =
                        {
                            Port = 12345,
                        },
                    Conventions =
                        {
                            CustomizeJsonSerializer = MvcApplication.SetupSerializer
                        }
                };
            documentStore.Initialize();
            var manager = new SubscriptionManager(documentStore);

            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            kernel.Bind<IDocumentStore>()
                  .ToMethod(context => documentStore)
                  .InSingletonScope();
            RegisterServices(kernel);
            kernel.Bind<SubscriptionManager>().ToMethod(context => manager).InSingletonScope();
            return kernel;
        }
 public RavenServer(Action<EmbeddableDocumentStore> initialization = null)
 {
     int port = 32076;
     DocumentStore = new EmbeddableDocumentStore
     {
         DataDirectory = "Data",
         UseEmbeddedHttpServer = true,
         DefaultDatabase = "NServiceBus",
         Configuration =
         {
             Port = port,
             PluginsDirectory = Environment.CurrentDirectory,
             HostName = "localhost"
         }
     };
     if (initialization != null)
     {
         initialization(DocumentStore);
     }
     DocumentStore.Initialize();
     //since we are hosting a fake raven server in process we need to remove it from the logging pipeline
     Trace.Listeners.Clear();
     Trace.Listeners.Add(new DefaultTraceListener());
     ManagementUrl = string.Format("http://localhost:{0}/", port);
     Console.WriteLine("Raven server started on {0}" + ManagementUrl);
 }
Beispiel #27
0
		public EmbeddableDocumentStore NewDocumentStore(string storageType, bool inMemory, int? allocatedMemory)
		{
			path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(DocumentStoreServerTests)).CodeBase);
			path = Path.Combine(path, "TestDb").Substring(6);

			var documentStore = new EmbeddableDocumentStore()
			{
				Configuration =
					{
						DataDirectory = path,
						RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true,
						DefaultStorageTypeName = storageType,
						RunInMemory = inMemory,
					}
			};

			ModifyStore(documentStore);
			ModifyConfiguration(documentStore.Configuration);

			if (documentStore.Configuration.RunInMemory == false)
				IOExtensions.DeleteDirectory(path);
			documentStore.Initialize();

			CreateDefaultIndexes(documentStore);

			if (allocatedMemory != null && inMemory)
			{
				var transactionalStorage = ((TransactionalStorage)documentStore.DocumentDatabase.TransactionalStorage);
				transactionalStorage.EnsureCapacity(allocatedMemory.Value);
			}

			return documentStore;
		}
        public void ShouldWork()
        {
            using (var _documentStore = new EmbeddableDocumentStore
                                           {
                                               RunInMemory = true,
                                               Conventions =
                                                   {
                                                       DefaultQueryingConsistency =
                                                           ConsistencyOptions.QueryYourWrites
                                                   }
                                           })
            {
                _documentStore.Initialize();

                using (var session = _documentStore.OpenSession())
                {
                    session.Store(new Foo());
                    session.Store(new Foo());
                    session.SaveChanges();
                }

                using (var session = _documentStore.OpenSession())
                {
                    var bar = session.Query<Foo>().Where(foo => foo.ExpirationTime == null || foo.ExpirationTime > DateTime.Now).ToList();
                    Assert.Equal(2, bar.Count);
                }
            }
        }
		public void SuccessTest2()
		{
			using (IDocumentStore documentStore = new EmbeddableDocumentStore
			{
				RunInMemory = true
			}.Initialize())
			{
				dynamic expando = new ExpandoObject();

				using (IDocumentSession session = documentStore.OpenSession())
				{
					session.Store(expando);

					RavenJObject metadata =
						session.Advanced.GetMetadataFor((ExpandoObject)expando);

					metadata[PropertyName] = RavenJToken.FromObject(true);

					session.SaveChanges();
				}

				using (IDocumentSession session = documentStore.OpenSession())
				{
					dynamic loaded = session.Advanced.LuceneQuery<dynamic>()
						.WhereEquals("@metadata.Raven-Entity-Name",
									 documentStore.Conventions.GetTypeTagName(typeof(ExpandoObject)))
						.FirstOrDefault();

					Assert.NotNull(loaded);
				}
			}
		}
 public CommandStorageTests()
 {
     _store = new EmbeddableDocumentStore();
     // _store.DataDirectory = Environment.CurrentDirectory + "Db";
     _store.RunInMemory = true;
     _store.Initialize();
 }
        protected IDocumentStore NewInMemoryStore()
        {
            IDocumentStore documentStore = new Raven.Client.Embedded.EmbeddableDocumentStore()
            {
                RunInMemory = true,
            };

            documentStore.Initialize();
            return(documentStore);
        }
 public EmbeddedAsyncServerClient(EmbeddableDocumentStore db, IDatabaseCommands databaseCommands)
 {
     this.db = db;
     this.databaseCommands = databaseCommands;
     OperationsHeaders     = new DictionaryWrapper(databaseCommands.OperationsHeaders);
 }