[Fact] // FAILS public void NotContainsWhenEmpty() { using (var store = GetDocumentStore()) { using (var s = store.OpenSession()) { s.Store(new MyDoc { DocArrayProp = new[] { 1, 2 } }); s.Store(new MyDoc { DocArrayProp = new int[0] }); s.SaveChanges(); } IndexCreation.CreateIndexes(new[] { new MyIndex() }, store); WaitForIndexing(store); using (var s = store.OpenSession()) { var results = s.Query <MyIndex.ReduceResult, MyIndex>().Where(d => !d.IndexArrayProp.Contains(1)).OfType <MyDoc>().ToArray(); Assert.Equal(1, results.Length); // FAILS HERE Assert.Empty(results.Single().DocArrayProp); } } }
public void write_then_read_from_complex_entity_types() { using (EmbeddableDocumentStore documentStore = NewDocumentStore()) { IndexCreation.CreateIndexes(typeof(QuestionWithVoteTotalIndex).Assembly, documentStore); string answerId = CreateEntities(documentStore); // Working using (IDocumentSession session = documentStore.OpenSession()) { AnswerEntity answerInfo = session.Query <Answer, Answers_ByAnswerEntity>() .Customize(x => x.WaitForNonStaleResultsAsOfNow()) .Where(x => x.Id == answerId) .As <AnswerEntity>() .SingleOrDefault(); Assert.NotNull(answerInfo); Assert.NotNull(answerInfo.Question); } // Failing using (IDocumentSession session = documentStore.OpenSession()) { AnswerVoteEntity[] votes = session.Query <AnswerVote, Votes_ByAnswerEntity>() .Customize(x => x.WaitForNonStaleResultsAsOfNow()) .Where(x => x.AnswerId == answerId) .As <AnswerVoteEntity>() .ToArray(); Assert.NotNull(votes); Assert.True(votes.Length == 2); Assert.NotNull(votes[0].Answer); Assert.True(votes[0].Answer.Id == answerId); Assert.NotNull(votes[1].Answer); Assert.True(votes[1].Answer.Id == answerId); } } }
static void Main(string[] args) { Console.WriteLine("Prepairing Database for sample"); var url = "http://localhost:8080"; var database = "ravendb-dependency-injection"; var store = new DocumentStore { Urls = new[] { url }, Database = database }; store.Initialize(); var doc = new DatabaseRecord(database); store.Maintenance.Server.Send(new CreateDatabaseOperation(doc)); IndexCreation.CreateIndexes(typeof(Article_ByName).Assembly, store); using (BulkInsertOperation bulkInsert = store.BulkInsert()) { for (int i = 0; i < 50; i++) { bulkInsert.Store(new Article { Name = "Article #" + i }); } } }
private static void TryCreatingIndexesOrRedirectToErrorPage() { try { IndexCreation.CreateIndexes(typeof(Tags_Count).Assembly, DocumentStore); } catch (WebException e) { var socketException = e.InnerException as SocketException; if (socketException == null) { throw; } switch (socketException.SocketErrorCode) { case SocketError.AddressNotAvailable: case SocketError.NetworkDown: case SocketError.NetworkUnreachable: case SocketError.ConnectionAborted: case SocketError.ConnectionReset: case SocketError.TimedOut: case SocketError.ConnectionRefused: case SocketError.HostDown: case SocketError.HostUnreachable: case SocketError.HostNotFound: HttpContext.Current.Response.Redirect("~/RavenNotReachable.htm"); break; default: throw; } } }
public void CanCreateIndexes() { using (var store = GetDocumentStore()) { IndexCreation.CreateIndexes(new AbstractIndexCreationTask[] { new AllDocs1(), new AllDocs2() }, store); } }
/// <inheritdoc /> public virtual Task ExecuteIndexesAsync(IEnumerable <AbstractIndexCreationTask> tasks, string database = null, CancellationToken token = default) { AssertInitialized(); var indexesToAdd = IndexCreation.CreateIndexesToAdd(tasks, Conventions); return(Maintenance.ForDatabase(database ?? Database).SendAsync(new PutIndexesOperation(indexesToAdd), token)); }
public DocumentStoreHolder(IOptions <RavenSettings> ravenSettings, ILogger <DocumentStoreHolder> logger) { this._logger = logger; var settings = ravenSettings.Value; Store = new DocumentStore() { Urls = new[] { settings.Url }, Database = settings.Database }; //Store.Conventions.UseOptimisticConcurrency = true; //Store.Conventions.CustomizeJsonSerializer = (serializer) => //{ // serializer. //} Store.Initialize(); CreateDatabaseIfNotExists(); IndexCreation.CreateIndexes( typeof(Talks_BySpeaker).Assembly, Store ); using (var session = Store.OpenSession()) { session.Load <Talk>("Talks/1"); } // TODO: Connect to RavenDB this._logger.LogWarning("**Initailized RavenDB document store for {0} at {1}", settings.Database, settings.Url); }
/// <summary> /// Executes indexes creation. /// </summary> public virtual Task ExecuteIndexesAsync(IEnumerable <AbstractIndexCreationTask> tasks, CancellationToken token = default(CancellationToken)) { AssertInitialized(); var indexesToAdd = IndexCreation.CreateIndexesToAdd(tasks, Conventions); return(Admin.SendAsync(new PutIndexesOperation(indexesToAdd), token)); }
public void BootstrapOrganisation(Organisation organisation) { MasterRavenDatabaseCommands.EnsureDatabaseExists(_organisation.FriendlyId); var docStore = _documentStoreFactory.Create(organisation.RavenInstance); IndexCreation.CreateIndexes( new CompositionContainer(new AssemblyCatalog(typeof(Indexing.Issues).Assembly), new ExportProvider[0]), RavenDatabaseCommands, docStore.Conventions); _organisationSession = docStore.OpenSession(_organisation.FriendlyId); _organisationSession.Advanced.MaxNumberOfRequestsPerSession = 500; var facets = new List <Facet> { new Facet { Name = "Status" }, }; _organisationSession.Store(new FacetSetup { Id = CoreConstants.FacetDocuments.IssueStatus, Facets = facets }); _organisationSession.SaveChanges(); }
public static void Startup() { var documentStore = new DocumentStore { ConnectionStringName = "RavenDB" }.Initialize(); documentStore.DatabaseCommands.EnsureDatabaseExists("RepositoryExample"); ObjectFactory.Initialize(config => { config.For <IAuctionRepository>().Use <AuctionRepository>(); config.For <IBidHistoryRepository>().Use <Infrastructure.BidHistoryRepository>(); config.For <IClock>().Use <SystemClock>(); config.For <IDocumentStore>().Use(documentStore); config.For <IDocumentSession>() .HybridHttpOrThreadLocalScoped() .Use(x => { var store = x.GetInstance <IDocumentStore>(); var session = store.OpenSession(); session.Advanced.UseOptimisticConcurrency = true; return(session); }); IndexCreation.CreateIndexes(typeof(BidHistory_NumberOfBids).Assembly, documentStore); }); }
private static void CreateIndexes(IServiceCollection services) { var serviceProvider = services.BuildServiceProvider(); var store = serviceProvider.GetService <IDocumentStore>(); IndexCreation.CreateIndexes(typeof(RavenModule).Assembly, store); }
/* Uncomment to enable ServiceStack Authentication and CustomUserSession * private void ConfigureAuth(Funq.Container container) * { * var appSettings = new AppSettings(); * * //Default route: /auth/{provider} * Plugins.Add(new AuthFeature(this, () => new CustomUserSession(), * new IAuthProvider[] { * new CredentialsAuthProvider(appSettings), * new FacebookAuthProvider(appSettings), * new TwitterAuthProvider(appSettings), * new BasicAuthProvider(appSettings), * })); * * //Default route: /register * Plugins.Add(new RegistrationFeature()); * * //Requires ConnectionString configured in Web.Config * var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString; * container.Register<IDbConnectionFactory>(c => * new OrmLiteConnectionFactory(connectionString, SqlServerOrmLiteDialectProvider.Instance)); * * container.Register<IUserAuthRepository>(c => * new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); * * var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>(); * authRepo.CreateMissingTables(); * } */ public static void Start() { Raven.Database.Server.NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8887); #if DEBUG MvcApplication.Store = new DocumentStore { ConnectionStringName = "localRaven" }; #else MvcApplication.Store = new EmbeddableDocumentStore { UseEmbeddedHttpServer = false }; #endif MvcApplication.Store.Initialize(); //MvcApplication.Store.DatabaseCommands.PutIndex("Reminders/ToBeSent", // new IndexDefinitionBuilder<Reminder> // { // Map = reminders => from reminder in reminders // select reminder , // Reduce = result => from r in result // where r.RemindersSent < 3 // select r // }); IndexCreation.CreateIndexes(Assembly.GetCallingAssembly(), MvcApplication.Store); new AppHost(MvcApplication.Store).Init(); }
/// <summary> /// Configures the document store internal. /// </summary> /// <param name="documentStore">The document store.</param> private void ConfigureDocumentStoreInternal(EmbeddableDocumentStore documentStore) { documentStore.RegisterListener(new StoreListener(this.OnPagePublish, this.OnPageSave, this.OnPageUnPublish)); documentStore.RegisterListener(new DeleteListener(this.OnDocumentDelete)); IndexCreation.CreateIndexes(typeof(DefaultBrickPileBootstrapper).Assembly, documentStore); }
public void CanLoadFromIndex() { using (var documentStore = NewDocumentStore()) { using (var session = documentStore.OpenSession()) { IndexCreation.CreateIndexes(typeof(Doc).Assembly, documentStore); session.Store(new Doc { Id = "test/doc1", Date = SystemTime.UtcNow }); session.Store(new Doc { Id = "test/doc2", Date = null }); session.SaveChanges(); } using (var session = documentStore.OpenSession()) { session .Query <Doc, UnsetDocs>() .Customize(x => x.WaitForNonStaleResults()) .AsProjection <DocSummary>() .ToArray(); } } }
public void SideBySideIndexCreated() { using (var store = NewDocumentStore()) { IndexCreation.CreateIndexes(new CompositionContainer(new TypeCatalog(typeof(OldIndex))), store); WaitForIndexing(store); var e = Assert.Throws <InvalidOperationException>(() => { using (var session = store.OpenSession()) { var count = session.Query <Person, OldIndex>() .Count(x => x.LastName == "Doe"); } }); Assert.Contains("The field 'LastName' is not indexed, cannot query on fields that are not indexed", e.InnerException.Message); var mre = new ManualResetEventSlim(false); var documentDatabase = store.ServerIfEmbedded.Server.GetDatabaseInternal(store.DefaultDatabase).Result; documentDatabase.IndexReplacer.IndexReplaced += s => { mre.Set(); }; IndexCreation.SideBySideCreateIndexes(new CompositionContainer(new TypeCatalog(typeof(NewIndex))), store); WaitForUserToContinueTheTest(store); Assert.True(mre.Wait(10000)); Assert.Equal(2, store.DatabaseCommands.GetStatistics().CountOfIndexes); } }
public void DefineMapReduceIndex() { //Define indexes from class IndexCreation.CreateIndexes(typeof(BlogPosts_PostsCountByTag).Assembly, DocumentStore); //Directly define index DocumentStore.DatabaseCommands .PutIndex("BlogPosts/PostsCountByTag", new IndexDefinitionBuilder <BlogPost, BlogTagPostsCount> { // The Map function: for each tag of each post, create a new BlogTagPostsCount // object with the name of a tag and a count of one. Map = posts => from post in posts from tag in post.Tags select new { Tag = tag, Count = 1 }, // The Reduce function: group all the BlogTagPostsCount objects we got back // from the Map function, use the Tag name as the key, and sum up all the // counts. Since the Map function gives each tag a Count of 1, when the Reduce // function returns we are going to have the correct Count of posts filed under // each tag. Reduce = results => from result in results group result by result.Tag into g select new { Tag = g.Key, Count = g.Sum(x => x.Count) } }); }
public void SetUp() { _store = NewDocumentStore(); _store.Initialize(); // We first have to create the static indexes IndexCreation.CreateIndexes(typeof(Player_Index_R03).Assembly, _store); _teams = DataGenerator.CreateTeamList(); // Store some players and teams in the database using (var session = _store.OpenSession()) { foreach (var team in _teams) { session.Store(team); } _players = DataGenerator.CreatePlayerListWithTeams(); foreach (var player in _players) { session.Store(player); } session.SaveChanges(); } // Let's wait for indexing to happen // this method is part of RavenTestBase and thus should only be used in tests WaitForIndexing(_store); }
public void CanUseTranslatorToModifyQueryResults_UsingClientGeneratedIndex() { using (var ds = NewDocumentStore()) { using (var s = ds.OpenSession()) { var entity = new User { Name = "Ayende", Age = 1 }; s.Store(entity); s.Store(new User { Name = "Oren", PartnerId = entity.Id, Age = 1 }); s.SaveChanges(); } IndexCreation.CreateIndexes( new CompositionContainer(new TypeCatalog(typeof(Users))), ds); using (var s = ds.OpenSession()) { var first = s.Query <User, Users>() .Customize(x => x.WaitForNonStaleResults()) .Where(x => x.Name == "Oren") .As <UserWithPartner>() .First(); Assert.Equal("Oren", first.User); Assert.Equal("Ayende", first.Partner); } } }
public DocumentStoreHolder(string urlDatabase) : base(urlDatabase) { var asm = Assembly.GetExecutingAssembly(); IndexCreation.CreateIndexes(asm, Instance); }
public void WhenTransformResultsHasAnError() { using (var ds = NewDocumentStore()) { using (var s = ds.OpenSession()) { var entity = new User { Name = "Ayende" }; s.Store(entity); s.Store(new User { Name = "Oren", PartnerId = entity.Id }); s.SaveChanges(); } IndexCreation.CreateIndexes( new CompositionContainer(new TypeCatalog(typeof(Users))), ds); using (var s = ds.OpenSession()) { var exception = Assert.Throws <InvalidOperationException>(() => s.Query <User, Users>() .Customize(x => x.WaitForNonStaleResults()) .Where(x => x.Name == "Ayende") .As <UserWithPartner>() .First()); dynamic dynamicNullObject = new DynamicNullObject(); var expectedError = Assert.Throws <DivideByZeroException>(() => 1 / dynamicNullObject); Assert.Equal("The transform results function failed.\r\nDoc 'users/1', Error: " + expectedError.Message, exception.Message); } } }
public void CanAutomaticallyCreateIndexes() { using (var store = NewDocumentStore()) { IndexCreation.CreateIndexes(typeof(Movies_ByActor).Assembly, store); using (var s = store.OpenSession()) { s.Store(new Movie { Name = "Hello Dolly", Tagline = "She's a jolly good" }); s.SaveChanges(); } using (var s = store.OpenSession()) { var movies = s.Advanced.LuceneQuery <Movie>("Movies/ByActor") .Where("Name:Dolly") .WaitForNonStaleResults() .ToList(); Assert.Equal(1, movies.Count); } } }
public void CollectionNameWithDashesCanBeIndexed() { using (var store = GetDocumentStore(new Options() { ModifyDocumentStore = a => a.Conventions.FindCollectionName = t => String.Join("-", t.Name.ToCharArray()) })) { IndexCreation.CreateIndexes(new AbstractIndexCreationTask[] { new ThingIndex(), new ThingIndex2() }, store); using (var session = store.OpenSession()) { session.Store(new Thing { Name = "Oren" }); session.SaveChanges(); } Indexes.WaitForIndexing(store); WaitForUserToContinueTheTest(store); using (var session = store.OpenSession()) { Assert.NotEmpty(session.Query <Thing, ThingIndex>().Where(x => x.Name == "Oren").ToList()); Assert.NotEmpty(session.Query <Thing, ThingIndex2>().Where(x => x.Name == "Oren").ToList()); } } }
public void CanCreateIndex() { using (var store = NewDocumentStore()) { IndexCreation.CreateIndexes(new CompositionContainer(new TypeCatalog(typeof(Transaction_ByMrn))), store); } }
public override void Configure(Container container) { Licensing.RegisterLicense(new AppSettings().GetString("servicestack:license")); SetConfig(new HostConfig { DebugMode = true, WriteErrorsToResponse = true, }); JsConfig.DateHandler = DateHandler.ISO8601; Plugins.Add(new CorsFeature()); Plugins.Add(new SwaggerFeature()); Plugins.Add(new PostmanFeature { DefaultLabelFmt = new List <string> { "route" } }); var documentStore = new DocumentStore { DefaultDatabase = "PowerDeploy", Url = "http://localhost:8080", }.Initialize(); IndexCreation.CreateIndexes(typeof(Deployment_Latest).Assembly, documentStore); Bootstrapper.ConfigureDependencies(container, documentStore); DataInitializer.InitializerWithDefaultValuesIfEmpty(documentStore); }
public void TestFixtureSetUp() { _store = NewDocumentStore(); IndexCreation.CreateIndexes(typeof(Player_Index_R03).Assembly, _store); var playerDictionary = DataGenerator.CreatePlayerList().ToDictionary(p => p.Id); var teamDictionary = DataGenerator.CreateTeamList().ToDictionary(p => p.Id); var employmentList = DataGenerator.CreateEmploymentList(); using (var bulkInsert = _store.BulkInsert(null, new BulkInsertOptions { OverwriteExisting = true })) { foreach (var player in playerDictionary.Values) { bulkInsert.Store(player); } foreach (var team in teamDictionary.Values) { bulkInsert.Store(team); } foreach (var employment in employmentList) { bulkInsert.Store(employment); } } WaitForIndexing(_store); }
public static void Initialize(IContainer container) { if (_documentStore != null) { return; } var documentStore = new EmbeddableDocumentStore { //DataDirectory = "App_Data", RunInMemory = true, UseEmbeddedHttpServer = true }; documentStore.Configuration.PluginsDirectory = System.IO.Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "Plugins"); documentStore.RegisterListener(new DocumentStoreListener()); documentStore.Initialize(); _documentStore = documentStore; IndexCreation.CreateIndexes(typeof(RavenConfig).Assembly, _documentStore); RavenProfiler.InitializeFor(_documentStore); using (var session = _documentStore.OpenSession()) { RavenQueryStatistics stats; session.Query <Document>().Statistics(out stats).Take(0).ToList(); if (stats.TotalResults == 0) { // we need to create some documents var rootDoc = new Document { Slug = string.Empty, Title = "Home page", Body = "<p>Welcome to this site. Go and see <a href=\"/blog\">the blog</a>.</p><p><a href=\"/about\">here</a> is the about page.</p>" }; session.Store(rootDoc); session.Store(new Document { ParentId = rootDoc.Id, Slug = "about", Title = "About", Body = "This is about this site." }); var blogDoc = new Document { ParentId = rootDoc.Id, Slug = "blog", Title = "Blog", Body = "This is my blog." }; session.Store(blogDoc); session.Store(new Document { ParentId = blogDoc.Id, Slug = "First", Title = "my first blog post", Body = "Hooray" }); session.SaveChanges(); } } container.Configure(x => x.For <IDocumentSession>().HybridHttpOrThreadLocalScoped().Use(() => _documentStore.OpenSession())); }
//public override void ConfigureConventions(BrickPileConventions brickPileConventions) //{ // brickPileConventions.VirtualPathProviderConventions.Register("static", () => new NativeVirtualPathProvider()); //} public override void ConfigureDocumentStore(IDocumentStore documentStore) { IndexCreation.CreateIndexes(typeof(CustomBootstrapper).Assembly, documentStore); // Initialize MiniProfiler //MvcMiniProfiler.RavenDb.Profiler.AttachTo(documentStore); }
public static void InitializeWithDefaults(this IDocumentStore documentStore, bool isDataToBeSeeded, IList <Type> indexesToExecute) { Condition.Requires(documentStore).IsNotNull(); // Default initializtion; documentStore.Initialize(); // Index initialisation. if (indexesToExecute != null) { Type[] indexes = (from type in indexesToExecute where type.IsSubclassOf(typeof(AbstractIndexCreationTask)) select type).ToArray(); IndexCreation.CreateIndexes(new CompositionContainer(new TypeCatalog(indexes)), documentStore); } else { IndexCreation.CreateIndexes(typeof(RecentPopularTags).Assembly, documentStore); } // Create our Seed Data (if required). // NOTE: This would be handled differently if it was a -real- production system. // Like, wrapping this called in a #if RELEASE #endif, for example. if (isDataToBeSeeded) { HelperUtilities.CreateSeedData(documentStore); } // Now lets check to make sure there are now errors. documentStore.AssertDocumentStoreErrors(); }
public void ServerShouldThrow() { var exception = Assert.Throws <IndexCompilationException>( () => { using (var store = NewDocumentStore()) { var container = new CompositionContainer(new TypeCatalog(typeof(Index), typeof(Record))); IndexCreation.CreateIndexes(container, store); } }); Assert.Equal("Reduce cannot contain Average() methods in grouping.", exception.Message); exception = Assert.Throws <IndexCompilationException>( () => { using (var store = NewDocumentStore()) { var container = new CompositionContainer(new TypeCatalog(typeof(FancyIndex), typeof(Record))); IndexCreation.CreateIndexes(container, store); } }); Assert.Equal("Reduce cannot contain Average() methods in grouping.", exception.Message); }
private static void TryCreatingIndexesOrRedirectToErrorPage() { try { IndexCreation.CreateIndexes(Assembly.GetAssembly(typeof(Company)), DocumentStore); } catch (WebException e) { var socketException = e.InnerException as SocketException; if (socketException == null) { throw; } switch (socketException.SocketErrorCode) { case SocketError.AddressNotAvailable: case SocketError.NetworkDown: case SocketError.NetworkUnreachable: case SocketError.ConnectionAborted: case SocketError.ConnectionReset: case SocketError.TimedOut: case SocketError.ConnectionRefused: case SocketError.HostDown: case SocketError.HostUnreachable: case SocketError.HostNotFound: // Shameless "borrow" from RacoonBlog, to show a nice page if it can't connect to RavenDB HttpContext.Current.Response.Redirect("~/RavenNotReachable.htm"); break; default: throw; } } }