Ejemplo n.º 1
0
        public void AbstractScriptedIndexCreationTaskWillCreateIndexAndDocument1()
        {
            using (var store = NewDocumentStore())
            {
                IndexCreation.CreateIndexes(new CompositionContainer(new TypeCatalog(typeof(People_By_Name_With_Scripts))), store);

                var index           = new People_By_Name_With_Scripts();
                var indexDefinition = store.DatabaseCommands.GetIndex(index.IndexName);
                Assert.NotNull(indexDefinition);

                using (var session = store.OpenSession())
                {
                    var indexDocument = session.Load <ScriptedIndexResults>(ScriptedIndexResults.IdPrefix + index.IndexName);
                    Assert.NotNull(indexDocument);
                    Assert.Equal(index.DeleteScript, indexDocument.DeleteScript);
                    Assert.Equal(index.IndexScript, indexDocument.IndexScript);
                    Assert.Equal(index.RetryOnConcurrencyExceptions, indexDocument.RetryOnConcurrencyExceptions);
                    Assert.Equal(ScriptedIndexResults.IdPrefix + index.IndexName, indexDocument.Id);
                }
            }
        }
Ejemplo n.º 2
0
        protected ServiceStackTestBase()
        {
            DocumentStore = NewDocumentStore();
            IndexCreation.CreateIndexes(typeof(ServiceStackTestBase).Assembly, DocumentStore);
            IndexCreation.CreateIndexes(typeof(RavenUserAuthRepository).Assembly, DocumentStore);

            Host = new TestAppHost(DocumentStore);
            Host.Init();
            Host.Start(ListeningOn);

            Client = new JsonServiceClient(ListeningOn)
            {
                AlwaysSendBasicAuthHeader = true,
                UserName = Username,
                Password = Password
            };

            RegisterUser();

            WaitForIndexing(DocumentStore);
        }
Ejemplo n.º 3
0
        /// <summary>
        ///		Configure IoC, register all dependencies
        /// </summary>
        protected virtual void ConfigureIocContainer(IServiceCollection services)
        {
            services.RegisterModules(Assembly.GetAssembly(typeof(BaseService <>)) !);

            // Register the document store & session
            services.AddScoped(_ =>
            {
                IDocumentStore store = GetDocumentStore();
                // Create all indexes
                IndexCreation.CreateIndexes(typeof(SetupDocumentStore).Assembly, store, null, store.Database);
                return(store);
            });
            services.AddScoped(c =>
            {
                var session = c.GetService <IDocumentStore>() !.OpenAsyncSession(new SessionOptions {
                    NoCaching = true
                });
                session.Advanced.WaitForIndexesAfterSaveChanges();                                  // Wait on each change to avoid adding WaitForIndexing() in each test
                return(session);
            });
        }
Ejemplo n.º 4
0
 public static IDocumentStore CreateDocumentStore()
 {
     try
     {
         ServiceStartupLogger.LogMessage("Start RavenHelper.CreateDocumentStore, creating document store");
         var documentStore = new DocumentStore
         {
             ConnectionStringName = "RavenDB",
             Conventions          =
             {
                 FindTypeTagName               = type =>
                 {
                     if (typeof(SettingsBase).IsAssignableFrom(type))
                     {
                         return("SettingsBases");
                     }
                     if (typeof(ConnectionSettingBase).IsAssignableFrom(type))
                     {
                         return("ConnectionSettingBases");
                     }
                     return(DocumentConvention.DefaultTypeTagName(type));
                 },
                 MaxNumberOfRequestsPerSession = AppSettingsHelper.GetIntSetting("RavenMaxNumberOfRequestsPerSession", 30000)
             }
         };
         ServiceStartupLogger.LogMessage("RavenHelper.CreateDocumentStore, calling Initialize");
         documentStore.Initialize();
         ServiceStartupLogger.LogMessage("RavenHelper.CreateDocumentStore, creating indexes");
         IndexCreation.CreateIndexes(typeof(MMDB.DataService.Data.Jobs.DataServiceJobBase <>).Assembly, documentStore);
         ServiceStartupLogger.LogMessage("RavenHelper.CreateDocumentStore, diabling all caching");
         documentStore.DatabaseCommands.DisableAllCaching();
         ServiceStartupLogger.LogMessage("Done RavenHelper.CreateDocumentStore");
         return(documentStore);
     }
     catch (Exception err)
     {
         ServiceStartupLogger.LogMessage("RavenHelper.CreateDocumentStore error: " + err.ToString());
         throw;
     }
 }
Ejemplo n.º 5
0
        static IDocumentStore CreateStore()
        {
            var s1 = new DocumentStore()
            {
                Url             = "http://localhost:8080",
                DefaultDatabase = "S1"
            }.Initialize();

            var s2 = new DocumentStore()
            {
                Url             = "http://localhost:8081",
                DefaultDatabase = "S2"
            }.Initialize();

            var strategy = new ShardStrategy(new Dictionary <String, IDocumentStore>()
            {
                { "S1", s1 },
                { "S2", s2 }
            });

            strategy.ShardingOn <Order>(o => o.Country, c =>
            {
                if (c.Equals("italy", StringComparison.OrdinalIgnoreCase))
                {
                    return("S1");
                }

                return("S2");
            });

            strategy.ShardingOn <Person>();

            var store = new ShardedDocumentStore(strategy)
            {
            }.Initialize();

            IndexCreation.CreateIndexes(Assembly.GetExecutingAssembly(), store);

            return(store);
        }
Ejemplo n.º 6
0
        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.Initialize();

            this._logger.LogInformation("🌟  Initialized RavenDB document store for {0} at {1}",
                                        settings.Database, settings.Url);

            // Create if not exists
            CreateDatabaseIfNotExists();

            // Create indexes
            IndexCreation.CreateIndexes(typeof(Talks_BySpeaker).Assembly, Store);
        }
Ejemplo n.º 7
0
        protected RavenControllerTest()
        {
            //NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8081);
            documentStore = new EmbeddableDocumentStore
            {
                RunInMemory = true,
                //UseEmbeddedHttpServer = true,
            };

            documentStore.RegisterListener(new NoStaleQueriesAllowed());
            documentStore.Initialize();
            IndexCreation.CreateIndexes(typeof(BusStop_Spatial).Assembly, documentStore);

            Controller = new TController {
                RavenSession = documentStore.OpenSession()
            };

            var httpContext = Substitute.For <HttpConfiguration>();
            var httpRoute   = Substitute.For <HttpRouteData>(Substitute.For <IHttpRoute>());

            Controller.ControllerContext = new HttpControllerContext(httpContext, httpRoute, new HttpRequestMessage());
        }
Ejemplo n.º 8
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            var formatters    = GlobalConfiguration.Configuration.Formatters;
            var jsonFormatter = formatters.JsonFormatter;
            var settings      = jsonFormatter.SerializerSettings;

            settings.Converters.Add(new IsoDateTimeConverter());
            settings.Formatting       = Formatting.Indented;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            Store = new DocumentStore {
                ConnectionStringName = "RavenDB"
            };
            Store.Initialize();
            RavenDbErrorLog.ConfigureWith(Store);

            AutomappingConfiguration.Bootstrap();

            //RavenProfiler.InitializeFor(Store);

            IndexCreation.CreateIndexes(typeof(HomeController).Assembly, Store);

            ConventionsBootstrapper.Bootstrap();

            ObjectSummarizer.KeyProviders.Add(new RegisteredKeyProvider()
            {
                Provider = new DbKeyFieldAsClassPropertyKeyProvider()
            });
            ObjectSummarizer.DescriptionProviders.Add(new RegisteredDescriptionProvider()
            {
                Provider = new NameOrDescriptionProperty()
            });

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            AreaRegistration.RegisterAllAreas();
        }
Ejemplo n.º 9
0
        private static IDocumentStore BuildDocumentStore(string rootDir, int?studioPort)
        {
            EmbeddedServer.Instance.StartServer(new ServerOptions
            {
                DataDirectory = rootDir,
                ServerUrl     = "http://127.0.0.1:" + studioPort,
            });

            IDocumentStore documentStore = EmbeddedServer.Instance.GetDocumentStore(new DatabaseOptions("Embedded")
            {
                Conventions = new DocumentConventions()
                {
                    MaxNumberOfRequestsPerSession = 100,
                },
            });

            documentStore.Initialize();

            IndexCreation.CreateIndexes(typeof(Program).Assembly, documentStore);

            return(documentStore);
        }
Ejemplo n.º 10
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //var b = new ScriptBundle("~/bundles/kendo").Include(
            //            "~/Scripts/kendo*");
            //b.IncludeDirectory("~/Scripts/kendo");
            //BundleTable.Bundles.Add(b);
            //var root = new MeetingCompositionRoot();
            //ControllerBuilder.Current.SetControllerFactory(root.ControllerFactory);

            Store = new DocumentStore {
                ConnectionStringName = "RavenDB"
            };
            Store.Initialize();

            IndexCreation.CreateIndexes(Assembly.GetCallingAssembly(), Store);
        }
Ejemplo n.º 11
0
        public void write_then_read_from_complex_entity_types_lazily()
        {
            using (GetNewServer())
                using (var store = new DocumentStore {
                    Url = "http://localhost:8080"
                }.Initialize())
                {
                    IndexCreation.CreateIndexes(typeof(QuestionWithVoteTotalIndex).Assembly, store);

                    string answerId = ComplexValuesFromTransformResults.CreateEntities(store);
                    // Working
                    using (IDocumentSession session = store.OpenSession())
                    {
                        var answerInfo = session.Query <Answer, Answers_ByAnswerEntity>()
                                         .Customize(x => x.WaitForNonStaleResultsAsOfNow())
                                         .Where(x => x.Id == answerId)
                                         .As <AnswerEntity>()
                                         .Lazily();
                        Assert.NotNull(answerInfo.Value.ToArray().Length);
                    }
                }
        }
Ejemplo n.º 12
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //DocumentStore = (DocumentStore)(new DocumentStore
            //{
            //    Url = "http://localhost:23456",
            //    DefaultDatabase = "RavenStore"
            //}).Initialize();

            DocumentStore = new DocumentStore {
                Url = "http://localhost:23456"
            };
            DocumentStore.DefaultDatabase = "RavenStore";
            DocumentStore.Initialize();


            IndexCreation.CreateIndexes(typeof(Products_ByCategory).Assembly, DocumentStore);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            using (var store = new DocumentStore
            {
                Url = "http://localhost:8080"
            }.Initialize())
            {
                IndexCreation.CreateIndexes(typeof(Users_ByName).Assembly, store);

                using (var session = store.OpenSession())
                {
                    var names = new[]
                    {
                        "Oren Eini", "Ayende Rahien", "Yoal", "Ido", "Yaron", "Oded Haim", "Michael Rer",
                        "Gal Rotem", "Udi Dahan", "Roy Osherove", "Haim Aharon", "Arava Eini"
                    };
                    foreach (var name in names)
                    {
                        session.Store(new User
                        {
                            Name = name
                        });
                    }

                    session.SaveChanges();
                }

                while (true)
                {
                    using (var session = store.OpenSession())
                    {
                        Console.Write("Enter user name: ");
                        var name = Console.ReadLine();

                        PerformQuery(session, name);
                    }
                }
            }
        }
        public new void SetUp()
        {
            var store = GetDocumentStore();

            store.Initialize();
            IndexCreation.CreateIndexes(typeof(Record).Assembly, store);
            WaitForIndexing(store);
            ReusableDocumentStore = store;

            Db = ReusableDocumentStore.OpenSession();

            var record1 = SimpleRecord().With(m =>
            {
                m.Gemini.Title = "sea";
                m.Gemini.DatasetReferenceDate = "2017-10-10";
            });
            var record2 = SimpleRecord().With(m =>
            {
                m.Gemini.Title = "seabirds";
                m.Gemini.DatasetReferenceDate = "2017-10-19";
            });
            var record3 = SimpleRecord().With(m =>
            {
                m.Gemini.Title = "birds";
                m.Gemini.DatasetReferenceDate = "2017-10-15";
            });
            var record4 = SimpleRecord().With(m =>
            {
                m.Gemini.Title = "coastal birds";
                m.Gemini.DatasetReferenceDate = "2017-10-17";
            });

            Db.Store(record1);
            Db.Store(record2);
            Db.Store(record3);
            Db.Store(record4);
            Db.SaveChanges();
            WaitForIndexing(ReusableDocumentStore);
        }
        static void Main(string[] args)
        {
            using (var docStore = new DocumentStore
            {
                Url = "http://localhost.fiddler:8080",
                DefaultDatabase = "Users"
            }.Initialize())
            {
                IndexCreation.CreateIndexes(typeof(User).Assembly, docStore);


                while (true)
                {
                    var search = Console.ReadLine();

                    using (var session = docStore.OpenSession())
                    {
                        DoQueryForUsers(session, search);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        private void TryCreatingIndexes(string connectionString)
        {
            try
            {
                store.DatabaseCommands.EnsureDatabaseExists("Dexter");

                Setup.Indexes.UpdateDatabaseIndexes(store);

                IndexCreation.CreateIndexes(this.GetType().Assembly, store);
            }
            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:
                    throw new DexterDatabaseConnectionException("Unable to connect to RavenDB", socketException, connectionString);

                default:
                    throw;
                }
            }
        }
        public void object_id_should_not_be_null_after_loaded_from_transformation()
        {
            using (EmbeddableDocumentStore documentStore = NewDocumentStore())
            {
                IndexCreation.CreateIndexes(typeof(QuestionWithVoteTotalIndex).Assembly, documentStore);

                const string questionId = @"question\259";
                string       answerId   = CreateEntities(documentStore);

                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);
                    Assert.NotNull(answerInfo.Question.Id);
                    Assert.True(answerInfo.Question.Id == questionId);
                }
            }
        }
Ejemplo n.º 18
0
        public void Multiple_indexes_created_with_not_existing_analyzer_should_skip_only_the_invalid_index()
        {
            using (var store = NewRemoteDocumentStore())
            {
                var indexManager = new IndexManager();
                var container    = new CompositionContainer();
                container.ComposeParts(indexManager, new Index1(), new Index2(), new Index3());

                try
                {
                    IndexCreation.CreateIndexes(container, store);
                }
                catch (AggregateException e)
                {
                    Assert.Contains("Index2", e.InnerExceptions.First().Message);
                }

                var indexInfo = store.DatabaseCommands.GetStatistics().Indexes;
                Assert.Equal(3, indexInfo.Length);                 //the third is Raven/DocumentEntityByName
                Assert.True(indexInfo.Any(index => index.Name.Equals("Index1")));
                Assert.True(indexInfo.Any(index => index.Name.Equals("Index3")));
            }
        }
Ejemplo n.º 19
0
        static void Main()
        {
            using (var documentStore = new DocumentStore {
                Url = "http://localhost:8080"
            }.Initialize())
            {
                using (var session = documentStore.OpenSession())
                {
                    IndexCreation.CreateIndexes(typeof(Posts_ByTitle).Assembly, documentStore);

                    var postsBySearch = session.Query <Post, Posts_ByTitle>()
                                        .Search(x => x.Title, "Code*")
                                        .OrderByDescending(x => x.PostDate).ToList();

                    foreach (var post in postsBySearch)
                    {
                        Console.WriteLine("Post ID: {0}, Title: {1}", post.Id, post.Title);
                    }

                    Console.ReadKey(true);
                }
            }
        }
Ejemplo n.º 20
0
        private static IDocumentStore CreateDocumentStore()
        {
            var machineName = ConfigurationManager.AppSettings["Machine"];

            if (machineName == Environment.MachineName)
            {
                var service = new ServiceController("ProductivityTracker_Raven", machineName);
                if (service.Status == ServiceControllerStatus.Stopped)
                {
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(60));
                }
            }

            var store = new DocumentStore {
                Url = string.Format("http://{0}:8080", machineName)
            };

            store.Initialize();

            IndexCreation.CreateIndexes(typeof(RecruiterIndex).Assembly, store);
            return(store);
        }
Ejemplo n.º 21
0
        private void AddRavenDBServices(IServiceCollection services)
        {
            services.AddSingleton <IDocumentStore> (s => {
                IDocumentStore store = new DocumentStore()
                {
                    Urls     = new [] { Configuration.GetValue <string> ("RavenDBEndpoint") },
                    Database = Configuration.GetValue <string> ("RavenDBDataBase")
                };
                store.Conventions.FindCollectionName = type => {
                    if (typeof(TossEntity).IsAssignableFrom(type))
                    {
                        return("TossEntity");
                    }

                    return(DocumentConventions.DefaultGetCollectionName(type));
                };

                store.Initialize();
                //taken from https://ravendb.net/docs/article-page/4.1/csharp/client-api/operations/server-wide/create-database
                try {
                    store.Maintenance.ForDatabase(store.Database).Send(new GetStatisticsOperation());
                } catch (DatabaseDoesNotExistException) {
                    try {
                        store.Maintenance.Server.Send(new CreateDatabaseOperation(new DatabaseRecord(store.Database)));
                    } catch (ConcurrencyException) {
                        // The database was already created before calling CreateDatabaseOperation
                    }
                }
                IndexCreation.CreateIndexes(typeof(Startup).Assembly, store);
                return(store);
            });

            services.AddScoped(s => s.GetRequiredService <IDocumentStore> ().OpenAsyncSession());
            services.AddSingleton <RavenDBIdUtil> ();
            services
            .AddRavenDbIdentity <ApplicationUser> ();
        }
        private IDocumentStore InitDocumentStore(AutofacCreationConverter converter)
        {
            var ds = new EmbeddableDocumentStore
            {
                DataDirectory     = _dataDirectory,
                ResourceManagerId = Guid.NewGuid(),
                RunInMemory       = RunInMemory,
            };

            if (_httpAccesss)
            {
                ds.UseEmbeddedHttpServer = true;
                NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(_httpAccesssPort);
            }

            if (converter != null && UseCreationConverter)
            {
                ds.Conventions.CustomizeJsonSerializer += s => s.Converters.Add(converter);
            }
            ds.Conventions.DisableProfiling         = true;
            ds.Conventions.JsonContractResolver     = new RecordClrTypeInJsonContractResolver();
            ds.Conventions.CustomizeJsonSerializer += s => s.TypeNameHandling = TypeNameHandling.Arrays;

            ds.Initialize();

            IndexCreation.CreateIndexes(ThisAssembly, ds);
            if (_indexAssemblies != null)
            {
                foreach (var indexAssembly in _indexAssemblies)
                {
                    IndexCreation.CreateIndexes(indexAssembly, ds);
                }
            }

            //global::Raven.Client.Indexes.IndexCreation.CreateIndexes(typeof(RegionTrajectoryIndex).Assembly, ds);
            return(ds);
        }
Ejemplo n.º 23
0
        private static void TryCreatingIndexesOrRedirectToErrorPage(Assembly[] indexAssemblies, string errorUrl)
        {
            try
            {
                foreach (var assembly in indexAssemblies)
                {
                    IndexCreation.CreateIndexes(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(errorUrl);
                    break;

                default:
                    throw;
                }
            }
        }
        public void QueryMapReduceStaticIndex()
        {
            using (var documentStore = NewDocumentStore())
            {
                documentStore.ConfigureForNodaTime();

                using (var session = documentStore.OpenSession())
                {
                    var spotLine = new LearningContractSpotLine
                    {
                        Month    = new LocalDate(2015, 02, 01),
                        Contract = new LearningContract {
                            Code = "11223344", Id = "contracts/12345"
                        }
                    };
                    session.Store(spotLine);
                    session.SaveChanges();
                }

                // have to create the index in the embedded test database per test run...
                IndexCreation.CreateIndexes(typeof(SpotLines_LineCountByMonth).Assembly, documentStore);

                using (var session = documentStore.OpenSession())
                {
                    var monthToQuery = new LocalDate(2015, 02, 01);

                    RavenQueryStatistics statistics;
                    var linesForMonth = session.Query <SpotLines_LineCountByMonth.ReduceResult, SpotLines_LineCountByMonth>()
                                        .Statistics(out statistics)
                                        .Customize(q => q.WaitForNonStaleResults(TimeSpan.FromSeconds(5)))
                                        .FirstOrDefault(c => c.Month == monthToQuery);

                    Assert.Equal("SpotLines/LineCountByMonth", statistics.IndexName);
                    Assert.Equal(1, linesForMonth.Count);
                }
            }
        }
Ejemplo n.º 25
0
        private static StreamReader _sr; // Reads text back from CMD.exe

        private static IDocumentStore RamDocumentStore(bool injectData = true)
        {
            var documentStore = new DocumentStore {
                Url = "http://localhost:8080/"
            };

            documentStore.Conventions.FindIdentityProperty = prop => prop.Name == "Id";

            documentStore.Initialize();

            if (injectData)
            {
                using (var documentSession = documentStore.OpenSession())
                {
                    // if we have no roles, system is not configured, so run system setup
                    var roles = documentSession.Query <Role>().ToList();
                    if (roles.Count == 0)
                    {
                        var systemStateManager = new SystemStateManager(documentSession);

                        var setupSystemDataCommandHander = new SetupSystemDataCommandHandler(
                            documentStore,
                            documentSession,
                            systemStateManager
                            );

                        setupSystemDataCommandHander.Handle(new SetupSystemDataCommand());
                        documentSession.SaveChanges();
                    }
                }
            }

            IndexCreation.CreateIndexes(typeof(All_Groups).Assembly, documentStore);

            return(documentStore);
        }
Ejemplo n.º 26
0
        public static void Initialize()
        {
            try
            {
                Store = new DocumentStore {
                    Url = "http://localhost:8080", DefaultDatabase = "Mvc4Sample"
                };
                SetupConventions(Store.Conventions);

                Store.Initialize();

                var types = Assembly.GetCallingAssembly().GetTypes().Where(t => t.GetCustomAttributes(typeof(ExplicitIndexAttribute), true).Length == 0);
                IndexCreation.CreateIndexes(new CompositionContainer(new TypeCatalog(types)), Store);

                ConfigureVersioning();
            }
            catch (Exception e)
            {
                if (RedirectToErrorPageIfRavenDbIsDown(e) == false)
                {
                    throw;
                }
            }
        }
        public CqrsDocumentStoreFactory(
            IAddDocumenStoreFromParameters storeAdder,
            IDocumentStoreFactory documentStoreFactory,
            ICqrsDocumentStoreFactoryInitializer initializer = null)
        {
            this.documentStoreFactory = documentStoreFactory;
            storeAdder.AddStore(
                new DocumentStoreParameters
            {
                DatabaseName    = "EventStore",
                FindTypeTagName = type => typeof(AbstractEvent).Name,
                TransformTypeTagNameToDocumentKeyPrefix = s => null
            });

            IndexCreation.CreateIndexes(typeof(AbstractEvent_EventSourcedIdAndVersion).Assembly, this.EventStore);

            storeAdder.AddStore(new DocumentStoreParameters
            {
                DatabaseName = "ReadModel",
                FindIdentityPropertyNameFromEntityName = n => n + "Id",
            });

            storeAdder.AddStore(new DocumentStoreParameters
            {
                DatabaseName = "SagaStore",
                FindIdentityPropertyNameFromEntityName = n => "CorrelationId"
            });

            if (initializer == null)
            {
                return;
            }

            initializer.SetDocumentStoreFactory(this);
            initializer.Initialize();
        }
Ejemplo n.º 28
0
        public static IDocumentStore CreateNewDocumentStoreInitializeAndCreateUtilIndexes(string connectionStringName)
        {
            var documentStore = new DocumentStore
            {
                ConnectionStringName = connectionStringName /*"ToileDeFond.Tests"*//*,
                                                             * Conventions =
                                                             * {
                                                             * JsonContractResolver = new DefaultContractResolver(shareCache: true)
                                                             * {
                                                             * DefaultMembersSearchFlags =  BindingFlags.NonPublic | BindingFlags.Instance
                                                             * },
                                                             * CustomizeJsonSerializer = serializer => serializer.PreserveReferencesHandling = PreserveReferencesHandling.Objects
                                                             * }*/
                                                            //,
                                                            //Conventions =
                                                            //                        {
                                                            //                            CustomizeJsonSerializer = serializer =>
                                                            //                                                          {
                                                            //                                                              serializer.Converters.Add(new ContentJsonConverter(() => doc));
                                                            //                                                              serializer.Converters.Add(new ModuleJsonConverter());
                                                            //                                                          }
                                                            //                        }
                , Conventions =
                {
                    CustomizeJsonSerializer             = serializer =>
                    {
                        serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                    }
                }
            };

            documentStore.Initialize();

            IndexCreation.CreateIndexes(typeof(AllDocumentsById).Assembly, documentStore);
            return(documentStore);
        }
Ejemplo n.º 29
0
        private static IDocumentStore SetupStore()
        {
            var store = new DocumentStore {
                Database = Database, Urls = Urls
            };

            if (!string.IsNullOrEmpty(Thumbprint))
            {
                using var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                certificateStore.Open(OpenFlags.ReadOnly);

                var collection  = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, Thumbprint, false);
                var certificate = collection.OfType <X509Certificate2>().FirstOrDefault();

                store.Certificate = certificate;
            }

            store.Conventions.IdentityPartsSeparator = "-";
            store.Initialize();

            IndexCreation.CreateIndexes(typeof(EverythingIndex).Assembly, store);

            return(store);
        }
Ejemplo n.º 30
0
        public ActionResult SyncIndexes()
        {
            Server.ScriptTimeout = 7200; //timeout in 2 hours

            var masterDocumentStore = _storeFactory.Create(RavenInstance.Master());

            IndexCreation.CreateIndexes(new CompositionContainer(
                                            new AssemblyCatalog(typeof(Issues).Assembly), new ExportProvider[0]),
                                        masterDocumentStore.DatabaseCommands.ForDatabase(CoreConstants.ErrorditeMasterDatabaseName),
                                        masterDocumentStore.Conventions);

            foreach (var organisation in Core.Session.MasterRaven.Query <Organisation>().GetAllItemsAsList(100))
            {
                organisation.RavenInstance = Core.Session.MasterRaven.Load <RavenInstance>(organisation.RavenInstanceId);

                using (_session.SwitchOrg(organisation))
                {
                    _session.BootstrapOrganisation(organisation);
                }
            }

            ConfirmationNotification("All indexes for all organisations have been updated");
            return(RedirectToAction("index"));
        }