Example #1
0
 public RocksDBStore()
 {
     StoreFactory.RegisterProvider(this);
 }
Example #2
0
 public ICacheStore CreateInstance()
 {
     LastInstance = this;
     return(new CacheStore());
 }
Example #3
0
        public HttpStatusCode RemoveRelationshipFromIndex(string connectionName, long relationshipId, string indexName, string key, object value)
        {
            var status = new StoreFactory().CreateNeo4jRestApi(connectionName).RemoveRelationshipFromIndex(connectionName, relationshipId, indexName, key, value);
            if (status != HttpStatusCode.NoContent)
            {
                throw new Exception(string.Format("Error remove relationship from index (relationship id:{0} index name:{1} http response:{2})", relationshipId, indexName, status));
            }

            return status;
        }
Example #4
0
        private void LoadProperties(bool refresh)
        {
            if (refresh)
            {
                _properties = null;
            }

            if (_properties != null)
            {
                return;
            }

            string response;
            var status = new StoreFactory().CreateNeo4jRestApi(_selfDbUrl).GetPropertiesOnRelationship(_selfDbUrl, Id, out response);
            if (status != HttpStatusCode.OK)
            {
                throw new Exception(string.Format("Error retrieving properties on relationship (relationship id:{0} http response:{1})", Id, status));
            }

            _properties = Properties.ParseJson(response);
        }
Example #5
0
        static void Main(string[] args)
        {
            // Uncomment to use SQL Server

            var configuration = new Configuration()
                                .UseSqlServer(@"Data Source =.; Initial Catalog = yessql; Integrated Security = True")
                                .SetTablePrefix("Gating");

            // Uncomment to use Sqlite

            //var store = new Store(
            //    new Configuration()
            //        .UseSqLite("Data Source=yessql.db;Cache=Shared")
            //    );

            // Uncomment to use PostgreSql

            //var store = new Store(
            //    new Configuration()
            //        .UsePostgreSql(@"Server=localhost;Port=5432;Database=yessql;User Id=root;Password=Password12!;Maximum Pool Size=1024;NoResetOnClose=true;Enlist=false;Max Auto Prepare=200")
            //        .SetTablePrefix("Gating")
            //    );

            // Uncomment to disable gating

            // store.Configuration.DisableQueryGating();

            try
            {
                using (var connection = configuration.ConnectionFactory.CreateConnection())
                {
                    connection.Open();

                    using (var transaction = connection.BeginTransaction(configuration.IsolationLevel))
                    {
                        new SchemaBuilder(configuration, transaction)
                        .DropMapIndexTable(nameof(PersonByName))
                        .DropTable("Identifiers")
                        .DropTable("Document");

                        transaction.Commit();
                    }
                }
            }
            catch { }

            using (var connection = configuration.ConnectionFactory.CreateConnection())
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction(configuration.IsolationLevel))
                {
                    var builder = new SchemaBuilder(configuration, transaction)
                                  .CreateMapIndexTable(nameof(PersonByName), column => column
                                                       .Column <string>(nameof(PersonByName.SomeName))
                                                       );

                    transaction.Commit();
                }
            }

            var store = StoreFactory.CreateAsync(configuration).GetAwaiter().GetResult();

            store.RegisterIndexes <PersonIndexProvider>();

            Console.WriteLine("Creating content...");
            using (var session = store.CreateSession())
            {
                for (var i = 0; i < 10000; i++)
                {
                    session.Save(new Person()
                    {
                        Firstname = "Steve" + i
                    });
                }
            }

            // Warmup
            Console.WriteLine("Warming up...");
            using (var session = store.CreateSession())
            {
                Task.Run(async() =>
                {
                    for (var i = 0; i < 500; i++)
                    {
                        await session.Query().For <Person>().With <PersonByName>(x => x.SomeName.StartsWith("Steve100")).ListAsync();
                        await session.Query().For <Person>().With <PersonByName>(x => x.SomeName == "Steve200").ListAsync();
                    }
                }).GetAwaiter().GetResult();
            }

            var concurrency     = 20;
            var counter         = 0;
            var MaxTransactions = 50000;
            var stopping        = false;

            var tasks = Enumerable.Range(1, concurrency).Select(i => Task.Run(async() =>
            {
                Console.WriteLine($"Starting thread {i}");

                await Task.Delay(100);

                while (!stopping && Interlocked.Add(ref counter, 1) < MaxTransactions)
                {
                    using (var session = store.CreateSession())
                    {
                        await session.Query().For <Person>().With <PersonByName>(x => x.SomeName.StartsWith("Steve100")).ListAsync();
                        await session.Query().For <Person>().With <PersonByName>(x => x.SomeName == "Steve").ListAsync();
                        await session.Query().For <Person>().With <PersonByName>().Where(x => x.SomeName == "Steve").ListAsync();
                    }
                }
            })).ToList();

            tasks.Add(Task.Delay(TimeSpan.FromSeconds(3)));

            Task.WhenAny(tasks).GetAwaiter().GetResult();

            // Flushing tasks
            stopping = true;
            Task.WhenAll(tasks).GetAwaiter().GetResult();
            stopping = false;

            Console.WriteLine(counter);
        }
Example #6
0
        public static IEnumerable<Relationship> GetRelationship(string connectionName, string indexName, string searchQuery)
        {
            string response;
            HttpStatusCode status = new StoreFactory().CreateNeo4jRestApi(connectionName).GetRelationship(connectionName, indexName, searchQuery, out response);
            if (status != HttpStatusCode.OK)
            {
                throw new Exception(string.Format("Index not found in (index:{0})", indexName));
            }

            return ParseJson(response);
        }
Example #7
0
 public DataTable GetSelectRegion(int countryId)
 {
     return(StoreFactory.GetCountryStore().GetSelectRegion(countryId));
 }
 public StoreFactoryControlHandler(StoreFactory factory)
 {
     editingFactory = factory;
 }
Example #9
0
        public override void SetUp()
        {
            // DotNetRdf memory store.
            string connectionString = "provider=dotnetrdf";

            // Stardog store.
            //string connectionString = "provider=stardog;host=http://localhost:5820;uid=admin;pw=admin;sid=test";

            // OpenLink Virtoso store.
            //string connectionString = string.Format("{0};rule=urn:semiodesk/test/ruleset", SetupClass.ConnectionString);

            Store = StoreFactory.CreateStore(connectionString);
            Store.InitializeFromConfiguration();
            Store.Log = (l) => Debug.WriteLine(l);

            IModel model1 = Store.CreateModel(new Uri("http://test.com/test1"));

            model1.Clear();

            IModel model2 = Store.CreateModel(new Uri("http://test.com/test2"));

            model2.Clear();

            // Add an agent so we can check if types are correctly queried.
            Agent a1 = model1.CreateResource <Agent>(ex.John);

            a1.FirstName = "John";
            a1.LastName  = "Doe";
            a1.Commit();

            Group g1 = model1.CreateResource <Group>(ex.TheSpiders);

            g1.Name = "The Spiders";
            g1.Commit();

            Group g2 = model2.CreateResource <Group>(ex.AlicaKeys);

            g2.Name = "Alicia Keys";
            g2.Commit();

            Person p1 = model1.CreateResource <Person>(ex.Alice);

            p1.FirstName      = "Alice";
            p1.LastName       = "Cooper";
            p1.Age            = 69;
            p1.Birthday       = new DateTime(1948, 2, 4);
            p1.Group          = g1;
            p1.Status         = true;
            p1.AccountBalance = 100000f;
            p1.Commit();

            Person p2 = model1.CreateResource <Person>(ex.Bob);

            p2.FirstName      = "Bob";
            p2.LastName       = "Dylan";
            p2.Age            = 76;
            p2.Birthday       = new DateTime(1941, 5, 24);
            p2.AccountBalance = 10000.1f;
            p2.Commit();

            Person p3 = model2.CreateResource <Person>(ex.Eve);

            p3.FirstName      = "Eve";
            p3.LastName       = "Jeffers-Cooper";
            p3.Birthday       = new DateTime(1978, 11, 10);
            p3.Age            = 38;
            p3.Group          = g2;
            p3.AccountBalance = 1000000.1f;
            p3.Commit();

            p1.KnownPeople.Add(p2);
            p1.Commit();

            p2.KnownPeople.Add(p1);
            p2.KnownPeople.Add(p2);
            p2.Commit();

            p3.Interests.Add(g2);
            p3.Interests.Add(p3);
            p3.Commit();

            Image i1 = model1.CreateResource <Image>();

            i1.DepictedAgent = p1;
            i1.Commit();

            Model = Store.CreateModelGroup(model1, model2);
        }
Example #10
0
 public Pull(StoreFactory storeFactory, Func<string> idFactory)
 {
     this.storeFactory = storeFactory;
     this.idFactory = idFactory;
 }
Example #11
0
 public void SetUp()
 {
     _store = StoreFactory.CreateStore("provider=virtuoso;host=localhost;port=1111;uid=dba;pw=dba;rule=urn:semiodesk/test/ruleset");
 }
Example #12
0
        static async Task MainAsync(string[] args)
        {
            var store = await StoreFactory.CreateAsync(
                new Configuration()
                .UseSqlServer(@"Data Source =.; Initial Catalog = yessql; Integrated Security = True")
                .SetTablePrefix("FullText")
                );

            using (var connection = store.Configuration.ConnectionFactory.CreateConnection())
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction())
                {
                    new SchemaBuilder(store.Configuration, transaction)
                    .CreateReduceIndexTable(nameof(ArticleByWord), table => table
                                            .Column <int>("Count")
                                            .Column <string>("Word")
                                            );

                    transaction.Commit();
                }
            }

            // register available indexes
            store.RegisterIndexes <ArticleIndexProvider>();

            // creating articles
            using (var session = store.CreateSession())
            {
                session.Save(new Article {
                    Content = "This is a white fox"
                });
                session.Save(new Article {
                    Content = "This is a brown cat"
                });
                session.Save(new Article {
                    Content = "This is a pink elephant"
                });
                session.Save(new Article {
                    Content = "This is a white tiger"
                });
            }

            using (var session = store.CreateSession())
            {
                Console.WriteLine("Simple term: 'white'");
                var simple = await session.Query <Article, ArticleByWord>().Where(a => a.Word == "white").ListAsync();

                foreach (var article in simple)
                {
                    Console.WriteLine(article.Content);
                }

                Console.WriteLine("Boolean query: 'white or fox or pink'");
                var boolQuery = await session.Query <Article, ArticleByWord>().Where(a => a.Word.IsIn(new[] { "white", "fox", "pink" })).ListAsync();

                foreach (var article in boolQuery)
                {
                    Console.WriteLine(article.Content);
                }
            }
        }
 private void SaveFactory(string filePath)
 {
     StoreFactory.SaveFactory(filePath, editingFactory);
 }
Example #14
0
        /// <summary>
        /// 检测版本
        /// </summary>
        public void Check()
        {
            SoftVersion ver     = null;
            var         lastVer = GetLatest();

            if (lastVer == null || lastVer.Count == 0)
            {
                //没有任何版本信息则移除
                return;
            }
            else
            {
                //本地已经是最新版本就不检测了
                if (CurVersion == lastVer[0].Version && MaxVsersionID == lastVer[0].VersionID)
                {
                    return;
                }
            }
            if (Version == "latest")
            {
                var r = lastVer;
                if (r != null && r.Count > 0)
                {
                    ver = r[0];
                    if (ver.Version == CurVersion && ver.VersionID == MaxVsersionID)
                    {
                        //已经更新过了
                        return;
                    }
                    if (ver.Clear)
                    {
                        Clear();
                    }
                }
            }
            else
            {
                var r = QueryVersion();
                if (r != null && r.Count > 0)
                {
                    ver = r.FindLast(x => x.Version == Version);
                    var max = r.FindAll(x => x.Version.CompareTo(Version) > 0 && x.Clear);
                    if (max != null && max.Count > 0)
                    {
                        CurVersion = "";
                        Clear();
                    }
                }
            }
            if (ver != null)
            {
                //比较,版本不同或者更新了文件,则比较
                if (ver.Version != CurVersion || ver.VersionID != MaxVsersionID)
                {
                    //
                    Updown(ver);
                }
                LastVersion = ver;
            }
            else
            {
                //没有找到该版本了,则清空全部下载最新版本

                var r = lastVer;
                if (r != null && r.Count > 0)
                {
                    ver = r[0];
                }
                if (CurVersion == ver.Version && ver.VersionID == MaxVsersionID)
                {
                    //已经是最新的了
                    return;
                }
                Clear();
                Updown(ver);
                LastVersion = ver;
            }
            //
            ILargerStore store = StoreFactory.GetStore();

            if (store != null)
            {
                while (!store.GetDownloadComplete())
                {
                    Thread.Sleep(1000);
                }
            }
        }
Example #15
0
 public int ExperimentalCountry(Country country)
 {
     return(StoreFactory.GetCountryStore().ExperimentalCountry(country));
 }
Example #16
0
        static async Task MainAsync(string[] args)
        {
            var store = await StoreFactory.CreateAndInitializeAsync(
                new Configuration()
                .UseSqlServer(@"Data Source =.; Initial Catalog = yessql; Integrated Security = True")
                .SetTablePrefix("Hi")
                );

            using (var connection = store.Configuration.ConnectionFactory.CreateConnection())
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction(store.Configuration.IsolationLevel))
                {
                    new SchemaBuilder(store.Configuration, transaction)
                    .CreateMapIndexTable <BlogPostByAuthor>(table => table
                                                            .Column <string>("Author")
                                                            )
                    .CreateReduceIndexTable <BlogPostByDay>(table => table
                                                            .Column <int>("Count")
                                                            .Column <int>("Day")
                                                            );

                    transaction.Commit();
                }
            };

            // register available indexes
            store.RegisterIndexes <BlogPostIndexProvider>();

            // creating a blog post
            var post = new BlogPost
            {
                Title        = "Hello YesSql",
                Author       = "Bill",
                Content      = "Hello",
                PublishedUtc = DateTime.UtcNow,
                Tags         = new[] { "Hello", "YesSql" }
            };

            // saving the post to the database
            using (var session = store.CreateSession())
            {
                session.Save(post);

                await session.SaveChangesAsync();
            }

            // loading a single blog post
            using (var session = store.CreateSession())
            {
                var p = await session.Query().For <BlogPost>().FirstOrDefaultAsync();

                Console.WriteLine(p.Title); // > Hello YesSql
            }

            // loading blog posts by author
            using (var session = store.CreateSession())
            {
                var ps = await session.Query <BlogPost, BlogPostByAuthor>().Where(x => x.Author.StartsWith("B")).ListAsync();

                foreach (var p in ps)
                {
                    Console.WriteLine(p.Author); // > Bill
                }
            }

            // loading blog posts by day of publication
            using (var session = store.CreateSession())
            {
                var ps = await session.Query <BlogPost, BlogPostByDay>(x => x.Day == DateTime.UtcNow.ToString("yyyyMMdd")).ListAsync();

                foreach (var p in ps)
                {
                    Console.WriteLine(p.PublishedUtc); // > [Now]
                }
            }

            // counting blog posts by day
            using (var session = store.CreateSession())
            {
                var days = await session.QueryIndex <BlogPostByDay>().ListAsync();

                foreach (var day in days)
                {
                    Console.WriteLine(day.Day + ": " + day.Count); // > [Today]: 1
                }
            }
        }
Example #17
0
 public int AddCountry(Country country)
 {
     return(StoreFactory.GetCountryStore().AddCountry(country));
 }
 public int DeteleMovieType(MovieType movietype)
 {
     return(StoreFactory.GetMovieTypeStore().DeteleMovieType(movietype));
 }
Example #19
0
 public int UpdateCountry(Country country)
 {
     return(StoreFactory.GetCountryStore().UpdateCountry(country));
 }
Example #20
0
        public static Relationship AddRelationshipToIndex(string connectionName, long relationshipId, string indexName, string key, object value)
        {
            string response;
            var status = new StoreFactory().CreateNeo4jRestApi(connectionName).AddRelationshipToIndex(connectionName, relationshipId, indexName, key, value, out response);
            if (status != HttpStatusCode.Created)
            {
                throw new Exception(string.Format("Error creating index for relationship (http response:{0})", status));
            }

            return InitializeFromRelationshipJson(response);
        }
Example #21
0
 public int DeleteCountryOfRegion(Country country)
 {
     return(StoreFactory.GetCountryStore().DeleteCountryOfRegion(country));
 }
Example #22
0
        public HttpStatusCode DeleteRelationship()
        {
            var status = new StoreFactory().CreateNeo4jRestApi(_selfDbUrl).DeleteRelationship(_selfDbUrl, Id);
            if (status != HttpStatusCode.NoContent)
            {
                throw new Exception(string.Format("Error deleteing relationship (relationship id:{0} http response:{1})", Id, status));
            }

            return status;
        }
Example #23
0
 public DataTable GetCountries()
 {
     return(StoreFactory.GetCountryStore().GetCountries());
     // return new CountryStore().GetCountries();
 }
Example #24
0
        public void SaveProperties(Properties properties)
        {
            var status = new StoreFactory().CreateNeo4jRestApi(_selfDbUrl).SetPropertiesOnRelationship(_selfDbUrl, Id, properties.ToString());
            if (status != HttpStatusCode.NoContent)
            {
                throw new Exception(string.Format("Error setting properties on relationship (relationship id:{0} http response:{1})", Id, status));
            }

            LoadProperties(true);
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            StoreQuery _query = StoreFactory.GetQuery(ConfigManager.YK_SYSTEM);

            dgvDetail.DataSource = _query.GetSupportInfo(cobBeginDate.Value, cobEndDate.Value);
        }
        public StoreModel AddStore()
        {
            var s = new StoreFactory();

            return(s.Create());
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public Result runFullConsistencyCheck(org.neo4j.io.layout.DatabaseLayout databaseLayout, org.neo4j.kernel.configuration.Config config, org.neo4j.helpers.progress.ProgressMonitorFactory progressFactory, final org.neo4j.logging.LogProvider logProvider, final org.neo4j.io.fs.FileSystemAbstraction fileSystem, final org.neo4j.io.pagecache.PageCache pageCache, final boolean verbose, java.io.File reportDir, org.neo4j.consistency.checking.full.ConsistencyFlags consistencyFlags) throws org.neo4j.consistency.checking.full.ConsistencyCheckIncompleteException
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
        public virtual Result RunFullConsistencyCheck(DatabaseLayout databaseLayout, Config config, ProgressMonitorFactory progressFactory, LogProvider logProvider, FileSystemAbstraction fileSystem, PageCache pageCache, bool verbose, File reportDir, ConsistencyFlags consistencyFlags)
        {
            AssertRecovered(databaseLayout, config, fileSystem, pageCache);
            Log log = logProvider.getLog(this.GetType());

            config.augment(GraphDatabaseSettings.read_only, TRUE);
            config.augment(GraphDatabaseSettings.pagecache_warmup_enabled, FALSE);

            StoreFactory factory = new StoreFactory(databaseLayout, config, new DefaultIdGeneratorFactory(fileSystem), pageCache, fileSystem, logProvider, EmptyVersionContextSupplier.EMPTY);

            ConsistencySummaryStatistics summary;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.File reportFile = chooseReportPath(reportDir);
            File reportFile = ChooseReportPath(reportDir);

            Suppliers.Lazy <PrintWriter> reportWriterSupplier = GetReportWriterSupplier(fileSystem, reportFile);
            Log reportLog = new ConsistencyReportLog(reportWriterSupplier);

            // Bootstrap kernel extensions
            Monitors                 monitors     = new Monitors();
            LifeSupport              life         = new LifeSupport();
            JobScheduler             jobScheduler = life.Add(JobSchedulerFactory.createInitialisedScheduler());
            TokenHolders             tokenHolders = new TokenHolders(new DelegatingTokenHolder(new ReadOnlyTokenCreator(), Org.Neo4j.Kernel.impl.core.TokenHolder_Fields.TYPE_PROPERTY_KEY), new DelegatingTokenHolder(new ReadOnlyTokenCreator(), Org.Neo4j.Kernel.impl.core.TokenHolder_Fields.TYPE_LABEL), new DelegatingTokenHolder(new ReadOnlyTokenCreator(), Org.Neo4j.Kernel.impl.core.TokenHolder_Fields.TYPE_RELATIONSHIP_TYPE));
            DatabaseKernelExtensions extensions   = life.Add(instantiateKernelExtensions(databaseLayout.DatabaseDirectory(), fileSystem, config, new SimpleLogService(logProvider, logProvider), pageCache, jobScheduler, RecoveryCleanupWorkCollector.ignore(), TOOL, monitors, tokenHolders));
            DefaultIndexProviderMap  indexes      = life.Add(new DefaultIndexProviderMap(extensions, config));

            try
            {
                using (NeoStores neoStores = factory.OpenAllNeoStores())
                {
                    // Load tokens before starting extensions, etc.
                    tokenHolders.PropertyKeyTokens().InitialTokens      = neoStores.PropertyKeyTokenStore.Tokens;
                    tokenHolders.LabelTokens().InitialTokens            = neoStores.LabelTokenStore.Tokens;
                    tokenHolders.RelationshipTypeTokens().InitialTokens = neoStores.RelationshipTypeTokenStore.Tokens;

                    life.Start();

                    LabelScanStore labelScanStore = new NativeLabelScanStore(pageCache, databaseLayout, fileSystem, Org.Neo4j.Kernel.Impl.Api.scan.FullStoreChangeStream_Fields.Empty, true, monitors, RecoveryCleanupWorkCollector.ignore());
                    life.Add(labelScanStore);

                    int              numberOfThreads = DefaultConsistencyCheckThreadsNumber();
                    Statistics       statistics;
                    StoreAccess      storeAccess;
                    AccessStatistics stats = new AccessStatistics();
                    if (verbose)
                    {
                        statistics  = new VerboseStatistics(stats, new DefaultCounts(numberOfThreads), log);
                        storeAccess = new AccessStatsKeepingStoreAccess(neoStores, stats);
                    }
                    else
                    {
                        statistics  = Statistics.NONE;
                        storeAccess = new StoreAccess(neoStores);
                    }
                    storeAccess.Initialize();
                    DirectStoreAccess stores = new DirectStoreAccess(storeAccess, labelScanStore, indexes, tokenHolders);
                    FullCheck         check  = new FullCheck(progressFactory, statistics, numberOfThreads, consistencyFlags, config, true);
                    summary = check.Execute(stores, new DuplicatingLog(log, reportLog));
                }
            }
            finally
            {
                life.Shutdown();
                if (reportWriterSupplier.Initialised)
                {
                    reportWriterSupplier.get().close();
                }
            }

            if (!summary.Consistent)
            {
                log.Warn("See '%s' for a detailed consistency report.", reportFile.Path);
                return(Result.failure(reportFile));
            }
            return(Result.success(reportFile));
        }
 public void GetResourceDBPediaTest()
 {
     var       store = StoreFactory.CreateStore("provider=sparqlendpoint;endpoint=http://live.dbpedia.org/sparql");
     IModel    m     = store.GetModel(new Uri("http://dbpedia.org"));
     IResource res   = m.GetResource(new Uri("http://dbpedia.org/resource/Munich"));
 }
 public int ExperimentalType(MovieType movietype)
 {
     return(StoreFactory.GetMovieTypeStore().ExperimentalType(movietype));
 }
        /// <summary>
        /// Adds tenant level data access services.
        /// </summary>
        /// <param name="builder">The <see cref="OrchardCoreBuilder"/>.</param>
        public static OrchardCoreBuilder AddDataAccess(this OrchardCoreBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddScoped <IDataMigrationManager, DataMigrationManager>();
                services.AddScoped <IModularTenantEvents, AutomaticDataMigrations>();

                services.AddOptions <StoreCollectionOptions>();
                services.AddTransient <IConfigureOptions <SqliteOptions>, SqliteOptionsConfiguration>();

                // Adding supported databases
                services.TryAddDataProvider(name: "Sql Server", value: "SqlConnection", hasConnectionString: true, sampleConnectionString: "Server=localhost;Database=Orchard;User Id=username;Password=password", hasTablePrefix: true, isDefault: false);
                services.TryAddDataProvider(name: "Sqlite", value: "Sqlite", hasConnectionString: false, hasTablePrefix: false, isDefault: true);
                services.TryAddDataProvider(name: "MySql", value: "MySql", hasConnectionString: true, sampleConnectionString: "Server=localhost;Database=Orchard;Uid=username;Pwd=password", hasTablePrefix: true, isDefault: false);
                services.TryAddDataProvider(name: "Postgres", value: "Postgres", hasConnectionString: true, sampleConnectionString: "Server=localhost;Port=5432;Database=Orchard;User Id=username;Password=password", hasTablePrefix: true, isDefault: false);

                // Configuring data access
                services.AddSingleton(sp =>
                {
                    var shellSettings = sp.GetService <ShellSettings>();

                    // Before the setup, a 'DatabaseProvider' may be configured without a required 'ConnectionString'.
                    if (shellSettings.State == TenantState.Uninitialized || shellSettings["DatabaseProvider"] == null)
                    {
                        return(null);
                    }

                    var storeConfiguration = GetStoreConfiguration(sp);

                    switch (shellSettings["DatabaseProvider"])
                    {
                    case "SqlConnection":
                        storeConfiguration
                        .UseSqlServer(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted)
                        .UseBlockIdGenerator();
                        break;

                    case "Sqlite":
                        var shellOptions            = sp.GetService <IOptions <ShellOptions> >();
                        var sqliteOptions           = sp.GetService <IOptions <SqliteOptions> >()?.Value ?? new SqliteOptions();
                        var option                  = shellOptions.Value;
                        var databaseFolder          = Path.Combine(option.ShellsApplicationDataPath, option.ShellsContainerName, shellSettings.Name);
                        var databaseFile            = Path.Combine(databaseFolder, "yessql.db");
                        var connectionStringBuilder = new SqliteConnectionStringBuilder
                        {
                            DataSource = databaseFile,
                            Cache      = SqliteCacheMode.Shared,
                            Pooling    = sqliteOptions.UseConnectionPooling
                        };

                        Directory.CreateDirectory(databaseFolder);
                        storeConfiguration
                        .UseSqLite(connectionStringBuilder.ToString(), IsolationLevel.ReadUncommitted)
                        .UseDefaultIdGenerator();
                        break;

                    case "MySql":
                        storeConfiguration
                        .UseMySql(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted)
                        .UseBlockIdGenerator();
                        break;

                    case "Postgres":
                        storeConfiguration
                        .UsePostgreSql(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted)
                        .UseBlockIdGenerator();
                        break;

                    default:
                        throw new ArgumentException("Unknown database provider: " + shellSettings["DatabaseProvider"]);
                    }

                    if (!String.IsNullOrWhiteSpace(shellSettings["TablePrefix"]))
                    {
                        storeConfiguration = storeConfiguration.SetTablePrefix(shellSettings["TablePrefix"] + "_");
                    }

                    var store   = StoreFactory.CreateAndInitializeAsync(storeConfiguration).GetAwaiter().GetResult();
                    var options = sp.GetService <IOptions <StoreCollectionOptions> >().Value;
                    foreach (var collection in options.Collections)
                    {
                        store.InitializeCollectionAsync(collection).GetAwaiter().GetResult();
                    }

                    var indexes = sp.GetServices <IIndexProvider>();

                    store.RegisterIndexes(indexes);

                    return(store);
                });

                services.AddScoped(sp =>
                {
                    var store = sp.GetService <IStore>();

                    if (store == null)
                    {
                        return(null);
                    }

                    var session = store.CreateSession();

                    var scopedServices = sp.GetServices <IScopedIndexProvider>();

                    session.RegisterIndexes(scopedServices.ToArray());

                    ShellScope.Current
                    .RegisterBeforeDispose(scope =>
                    {
                        return(scope.ServiceProvider
                               .GetRequiredService <IDocumentStore>()
                               .CommitAsync());
                    })
                    .AddExceptionHandler((scope, e) =>
                    {
                        return(scope.ServiceProvider
                               .GetRequiredService <IDocumentStore>()
                               .CancelAsync());
                    });

                    return(session);
                });

                services.AddScoped <IDocumentStore, DocumentStore>();
                services.AddSingleton <IFileDocumentStore, FileDocumentStore>();

                services.AddTransient <IDbConnectionAccessor, DbConnectionAccessor>();
            });

            return(builder);
        }
 public int AddMovieType(MovieType movietype)
 {
     return(StoreFactory.GetMovieTypeStore().AddMovieType(movietype));
 }
Example #32
0
 public void SetUp()
 {
     Store = StoreFactory.CreateStore("provider=dotnetrdf");
 }
 public int UpdateMovieType(MovieType movietype)
 {
     return(StoreFactory.GetMovieTypeStore().UpdateMovieType(movietype));
 }
 public IndexStoreTestContext()
 {
     TestConfiguration = new FindConfiguration("http://myfindurl", "myindex", null);
     StoreFactory = new StoreFactory(TestConfiguration);
 }
Example #35
0
 public Push(StoreFactory storeFactory)
 {
     this.storeFactory = storeFactory;
 }