Exemple #1
0
		public void NameConvention_ModifiedProperty()
		{
			using (var store = new EmbeddableDocumentStore
			{
				RunInMemory = true,
				Conventions =
					{
						FindIdentityProperty = info => info.Name == "Name"
					}
			}.Initialize())
			{
				using (var session = store.OpenSession())
				{
					session.Store(new Item
					{
						Name = "Ayende"
					});
					session.SaveChanges();
				}

				using (var session = store.OpenSession())
				{
					var item = session.Load<Item>("Ayende");
					item.Id = "items/2";
					item.Name = "abc";
					Assert.Throws<InvalidOperationException>(() => session.SaveChanges());
				}
			}
		}
		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 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();
            }
        }
Exemple #4
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);
					}
				}

				
			}
		}
Exemple #5
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);
                }
            }
        }
        public void Should_retrieve_all_entities_using_connection_string()
        {
            using (var documentStore = new EmbeddableDocumentStore
            {
                ConnectionStringName = "Local",
                Configuration =
                {
                    RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true
                }
            })
            {
                path = documentStore.DataDirectory;

                documentStore.Initialize();

                var session1 = documentStore.OpenSession();
                session1.Store(new Company { Name = "Company 1" });
                session1.Store(new Company { Name = "Company 2" });

                session1.SaveChanges();
                var session2 = documentStore.OpenSession();
                var companyFound = session2.Advanced.DocumentQuery<Company>()
                    .WaitForNonStaleResults()
                    .ToArray();

                Assert.Equal(2, companyFound.Length);
            }
        }
        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));
                }
            }
        }
		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>());
				}
			}
		}
		private static void DoTest(DateTime dt, DateTimeKind inKind, DateTimeKind outKind)
		{
			Assert.Equal(inKind, dt.Kind);

			using (var documentStore = new EmbeddableDocumentStore { RunInMemory = true })
			{
				documentStore.Initialize();

				using (var session = documentStore.OpenSession())
				{
					session.Store(new Foo { Id = "foos/1", DateTime = dt });
					session.SaveChanges();
				}

				using (var session = documentStore.OpenSession())
				{
					var foo = session.Query<Foo>()
									 .Customize(x => x.WaitForNonStaleResults())
									 .FirstOrDefault(x => x.DateTime == dt);

					WaitForUserToContinueTheTest(documentStore);

					Assert.Equal(dt, foo.DateTime);
					Assert.Equal(outKind, foo.DateTime.Kind);
				}
			}
		}
Exemple #10
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);
        }
        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);
                }
            }
        }
Exemple #12
0
		public void StandaloneTestForPostingOnStackOverflow()
		{
			var testDocument = new Cart { Email = "*****@*****.**" };
			using (var documentStore = new EmbeddableDocumentStore { RunInMemory = true })
			{
				documentStore.Initialize();

				using (var session = documentStore.OpenSession())
				{
					using (var transaction = new TransactionScope())
					{
						session.Store(testDocument);
						session.SaveChanges();
						transaction.Complete();
					}
				}
				using (var session = documentStore.OpenSession())
				{
					using (var transaction = new TransactionScope())
					{
						var documentToDelete = session
							.Query<Cart>()
							.Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
							.First(c => c.Email == testDocument.Email);

						session.Delete(documentToDelete);
						session.SaveChanges();
						transaction.Complete();
					}
				}

				using (var session = documentStore.OpenSession())
				{
					session.Advanced.AllowNonAuthoritativeInformation = false;
					RavenQueryStatistics statistics;
					Assert.Null(session
							.Query<Cart>()
							.Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
							.FirstOrDefault(c => c.Email == testDocument.Email));

					// we force a wait here, because there is no way to wait for NonAuthoritativeInformation on a count

					var actualCount = session
						.Query<Cart>()
						.Statistics(out statistics)
						.Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
						.Count(c => c.Email == testDocument.Email);

					Assert.False(statistics.IsStale);
					Assert.False(statistics.NonAuthoritativeInformation);
					Assert.Equal(0, actualCount);
				}
			}
		}
		public void can_index_on_a_reference2()
		{
			using (var store = new EmbeddableDocumentStore
			{
				RunInMemory = true
			})
			{

				store.Initialize();
				using (var session = store.OpenSession())
				{
					var category = new Category()
					{
						Name = "Parent"
					};

					category.Add(new Category()
					{
						Name = "Child"
					});

					session.Store(category);
					session.SaveChanges();
				}

				using (var session = store.OpenSession())
				{
					var results0 = session.Query<Category>()
						.Customize(x=>x.WaitForNonStaleResults(TimeSpan.FromHours(1)))
						.ToList();
					Assert.Equal(1, results0.Count);

					// WORKS
					var results1 = session.Query<Category>()
						.Customize(x => x.WaitForNonStaleResults())
						.Where(x => x.Children.Any(y => y.Name == "Child")).
						ToList();
					Assert.Equal(1, results1.Count);

					// FAILS
					var results2 = session.Query<Category>()
						.Customize(x => x.WaitForNonStaleResults())
						.Where(x => x.Children.Any(y => y.Parent.Name == "Parent"))
						.ToList();
					Assert.Equal(1, results2.Count);
				}
			}
		}
Exemple #14
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");

		}
Exemple #15
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);
        }
        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 PostSchedulingStrategyTests()
        {
            Now = DateTimeOffset.Now;

            DocumentStore = new EmbeddableDocumentStore { RunInMemory = true }.Initialize();
            Session = DocumentStore.OpenSession();
        }
Exemple #18
0
		public void CanPassOperationHeadersUsingEmbedded()
		{
            using (var documentStore = new EmbeddableDocumentStore
			{
				Configuration = 
				{
					Catalog =
						{
							Catalogs = { new TypeCatalog(typeof(RecordOperationHeaders)) }
						},
					DataDirectory = path,
					RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true
				}

			}.Initialize())
			{
				RecordOperationHeaders.Hello = null;
				using(var session = documentStore.OpenSession())
				{
                    session.Advanced.DatabaseCommands.OperationsHeaders["Hello"] = "World";
					session.Store(new { Bar = "foo"});
					session.SaveChanges();

					Assert.Equal("World", RecordOperationHeaders.Hello);
				}
			}
		}
Exemple #19
0
        static void Main(string[] args)
        {
            var sub = new TestThingySub { Name = "Sub Thingy", widgetCount = 2 };
            var thingy = new TestThingy
            {
                Name = "Balls",
                SubThingy=sub,
                WidgetIDs = Enumerable.Range(0, 23).ToList()
            };
            thingy.SetId(342);

            TestThingy thing2;
            using (var documentStore = new EmbeddableDocumentStore { DataDirectory = @"C:\Users\Andrew\Dropbox\Code\Projects\RavenDBEmbeddedPOC\packages\RavenDB-Embedded.1.0.701\lib\net40" })
            {
                documentStore.Initialize();
                using (var session = documentStore.OpenSession())
                {
                    thing2 = (from t in session.Query<TestThingy>()
                                 select t).First();
                }
            }

            Console.WriteLine("we just ran this bitch");
            Console.Read();
        }
Exemple #20
0
        public ProjectionTests()
        {
            documentStore = NewDocumentStore(configureStore: store => store.RegisterListener(new NoStaleQueriesAllowed()));
            session = documentStore.OpenSession();

            Setup();
        }
Exemple #21
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());
				}
			}
		}
Exemple #22
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();
        }
Exemple #23
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);
                }
            }
        }
Exemple #24
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());

                }

            }
        }
 public void SetupTests()
 {
     _embeddedDocStore = new EmbeddableDocumentStore { RunInMemory = true };
     _embeddedDocStore.Initialize();
     var documentSession = _embeddedDocStore.OpenSession();
     documentSession.Store(new UserAccount { Username = "******", Status = UserStatus.Active });
     documentSession.SaveChanges();
 }
        public void WillSaveNewNetwork()
        {
            using(var store = new EmbeddableDocumentStore{RunInMemory=true}.Initialize())
            {
                var controller = new NetworkController {Session = store.OpenSession()};

                controller.New("cnn");

                controller.Session.SaveChanges();

                using(var session = store.OpenSession())
                {
                    var network = session.Load<CableNetwork>("cablenetworks/1");
                    Assert.Equal("cnn", network.Name);
                }
            }
        }
 public void Setup()
 {
     DocumentStore = new EmbeddableDocumentStore
         {
             RunInMemory = true
         };
     DocumentStore.Initialize();
     Session = DocumentStore.OpenSession();
 }
 public WhereStringEqualsInCollection()
 {
     store = NewDocumentStore();
     using (var session = store.OpenSession())
     {
         session.Store(new MyEntity { StringData = "Entity with collection", StringCollection = new List<string> { "CollectionItem1", "CollectionItem2" } });
         session.SaveChanges();
     }
 }
        protected static IDocumentSession WithEmptySession()
        {
            var store = new EmbeddableDocumentStore
            {
                RunInMemory = true
            }.Initialize();

            return store.OpenSession();
        }
        protected static IDocumentSession WithEmptySession()
        {
            var store = new EmbeddableDocumentStore
            {
                RunInMemory = true,
                Configuration = { Storage = { Voron = { AllowOn32Bits = true } } }
            }.Initialize();

            return store.OpenSession();
        }