public override bool Open (String path)
        {
            var connectionString = new SqliteConnectionStringBuilder
            {
                DataSource = path,
                Version = 3,
                SyncMode = SynchronizationModes.Full
            };

            var result = true;
            try {
                shouldCommit = false;
                Connection = new SqliteConnection (connectionString.ToString ());
                Connection.Open();
            } catch (Exception ex) {
                Log.E(Tag, "Error opening the Sqlite connection using connection String: {0}".Fmt(connectionString.ToString()), ex);
                result = false;    
            }

            return result;
        }
        public void SearchCustomer_SearchByJohn()
        {
            var connectionStringBuilder =
                new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connection = new SqliteConnection(connectionStringBuilder.ToString());
            var options    = new DbContextOptionsBuilder <CustomerDBContext>()
                             .UseSqlite(connection)
                             .Options;

            using (var context = new CustomerDBContext(options))
            {
                context.Database.OpenConnection();
                context.Database.EnsureCreated();

                context.Customers.AddRange(new[]
                {
                    new Customer()
                    {
                        FirstName = "Syed", LastName = "Majeeduddin", DOB = DateTime.Now.AddYears(-25)
                    },
                    new Customer()
                    {
                        FirstName = "John", LastName = "Syed", DOB = DateTime.Now.AddYears(-35)
                    }
                });

                context.SaveChanges();

                var customerRepository = new CustomerRepository(context);

                // Act
                var customers = customerRepository.FindCustomerByName("Syed");


                // Assert
                Assert.Equal(2, customers.Result.Count);
            }
        }
Example #3
0
        public FolderRepositoryTests()
        {
            var connectionStringBuilder =
                new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connectionString = connectionStringBuilder.ToString();
            var connection       = new SqliteConnection(connectionString);

            DbContextOptions <ApplicationDbContext> options;
            var builder = new DbContextOptionsBuilder <ApplicationDbContext>();

            builder.UseSqlite(connection);
            options = builder.Options;
            var context = new ApplicationDbContext(options);

            context.Database.OpenConnection();
            context.Database.EnsureCreated();

            // Add project for the folder to use
            var project = new Project {
                Name = "TestProject"
            };

            context.Add(project);

            // Add test Folders
            var folders = Enumerable.Range(1, folderCount)
                          .Select(i => new Folder
            {
                Id        = i,
                ProjectID = project.Id,
                Name      = $"Name{i}"
            });

            context.AddRange(folders);
            int changed = context.SaveChanges();

            _context = context;
        }
Example #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSampleData();

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            var builder          = new SqliteConnectionStringBuilder(connectionString);

            builder.DataSource = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, builder.DataSource));
            connectionString   = builder.ToString();

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(connectionString)
                                                         );

            services.AddDefaultIdentity <IdentityUser>()
            .AddDefaultUI()
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddGraphity <AnimalContext>(options =>
            {
                options.AddHasRolesAuthorisationPolicy("admin-policy", "admin");
                options.AddHasRolesAuthorisationPolicy("user-policy", "");

                options.ConfigureSet(ctx => ctx.Animals)
                .SetAuthorisationPolicy("admin-policy");

                options.ConfigureSet(ctx => ctx.Countries)
                .SetAuthorisationPolicy("user-policy");
            });

            services.AddMvc();
        }
Example #5
0
        public static TestBudget CreateBudget(BudgetBackends budgetBackend, Budget initialBudget = null)
        {
            TestBudget testBudget = null;

            if (budgetBackend == BudgetBackends.Memory)
            {
                testBudget          = new TestBudget();
                testBudget.DeviceID = Guid.NewGuid();

                testBudget.EventStore  = new TestEventStore(new MemoryEventStore());
                testBudget.BudgetStore = new MemoryBudgetStore(testBudget.EventStore);
            }
            else if (budgetBackend == BudgetBackends.SQLite)
            {
                testBudget          = new TestBudget();
                testBudget.DeviceID = Guid.NewGuid();

                SqliteConnectionStringBuilder builder = new SqliteConnectionStringBuilder();
                builder.Mode       = SqliteOpenMode.Memory;
                builder.Cache      = SqliteCacheMode.Shared;
                builder.DataSource = "BudgetTests";

                testBudget.BudgetStore = new SQLiteBudgetStore(testBudget.DeviceID, builder.ToString(), (es) => new TestEventStore(es));
                testBudget.EventStore  = testBudget.BudgetStore.EventStore as TestEventStore;
            }

            if (initialBudget == null)
            {
                initialBudget = InitializeBudget();
            }

            testBudget.BudgetModel = BudgetModel.CreateNew(testBudget.DeviceID, testBudget.BudgetStore, initialBudget);
            testBudget.BudgetModel.SaveChanges();

            testBudget.EventStore.TestEvents.Clear();
            testBudget.TestEvents = testBudget.EventStore.TestEvents;
            testBudget.Budget     = initialBudget;

            return(testBudget);
        }
        static void Main(string[] args)
        {
            //Create Connection
            var cStrBuilder = new SqliteConnectionStringBuilder();

            cStrBuilder.DataSource = "./myDb.db";

            using (var Connection = new SqliteConnection(cStrBuilder.ConnectionString)){
                //want to use using so it closes after it's done
                Connection.Open();
                //create table
                var tableCmd = Connection.CreateCommand();
                tableCmd.CommandText = "CREATE TABLE stores(name VARCHAR(50));";
                tableCmd.ExecuteNonQuery();
                //Insert Some Records
                using (var transaction = Connection.BeginTransaction()){
                    var insertCmd = Connection.CreateCommand();
                    insertCmd.CommandText = "INSERT INTO stores VALUES('chico books')";
                    insertCmd.ExecuteNonQuery();

                    insertCmd.CommandText = "INSERT INTO stores VALUES('Santa Cruz books')";
                    insertCmd.ExecuteNonQuery();

                    transaction.Commit();
                }
                var selectCmd = Connection.CreateCommand();
                selectCmd.CommandText = "SELECT * FROM stores";
                using (var reader = selectCmd.ExecuteReader()){
                    while (reader.Read())
                    {
                        var result = reader.GetString(0);// getting the first column data[0]
                        Console.WriteLine(result);
                    }
                }
            }

            // Insert records

            // Read Records
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // thanks to https://exceptionnotfound.net/setting-a-custom-default-page-in-asp-net-core-razor-pages/
            services.AddMvc().AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/Home/Index", "");
            });

            //--------------------------------------------------------------------
            //var connection = Configuration.GetConnectionString("DefaultConnection");
            //Swapped over to sqlite in-memory database
            var connectionStringBuilder = new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connectionString = connectionStringBuilder.ToString();
            var connection       = new SqliteConnection(connectionString);

            connection.Open();  //see https://github.com/aspnet/EntityFramework/issues/6968
            services.AddDbContext <EfCoreContext>(options => options.UseSqlite(connection));
            //--------------------------------------------------------------------

            services.GenericServicesSimpleSetup <EfCoreContext>(Assembly.GetAssembly(typeof(BookListDto)));

            //This is the version you would use if you were registering multiple DbContext
            //services.ConfigureGenericServicesEntities(typeof(BookDbContext), typeof(OrderDbContext))
            //    .ScanAssemblesForDtos(Assembly.GetAssembly(typeof(BookListDto)))
            //    .RegisterGenericServices();

            //--------------------------------------------------------------------------------------------
            //I removed the code below, as this was only needed for the hand-coded versions of the services
            ////Now I use AutoFac to do some of the more complex registering of services
            //var containerBuilder = new ContainerBuilder();

            ////Now I use the ServiceLayer AutoFac module that registers all the other DI items, such as my biz logic
            //containerBuilder.RegisterModule(new ServiceLayerModule());

            //containerBuilder.Populate(services);
            //var container = containerBuilder.Build();
            //return new AutofacServiceProvider(container);
        }
Example #8
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //optionsBuilder.UseLoggerFactory(_loggerFactory)
            //  .EnableSensitiveDataLogging();

            if (string.IsNullOrEmpty(_ConnectionString))
            {
                string currentPath = Utilities.OperatingDirectory;
                // allows the application to find the database file
                currentPath = !RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
                              $"{Path.DirectorySeparatorChar}{currentPath}" :
                              currentPath;

                var connectionStringBuilder = new SqliteConnectionStringBuilder {
                    DataSource = Path.Join(currentPath, "Database", "Database.db")
                };
                var connectionString = connectionStringBuilder.ToString();
                var connection       = new SqliteConnection(connectionString);

                if (!optionsBuilder.IsConfigured)
                {
                    optionsBuilder.UseSqlite(connection);
                }
            }

            else
            {
                switch (_provider)
                {
                default:
                case "mysql":
                    optionsBuilder.UseMySql(_ConnectionString, _options => _options.EnableRetryOnFailure());
                    break;

                case "postgresql":
                    optionsBuilder.UseNpgsql(_ConnectionString, _options => _options.EnableRetryOnFailure());
                    break;
                }
            }
        }
Example #9
0
        protected SqlHelper(String tableName)
        {
            Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SolderHelper"));
            String databaseName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SolderHelper", "SolderHelper.db");

            try
            {
                if (!File.Exists(databaseName))
                {
                    if (IsUnix())
                    {
                        SqliteConnection.CreateFile(databaseName);
                    }
                    else
                    {
                        SQLiteConnection.CreateFile(databaseName);
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }
            if (IsUnix())
            {
                SqliteConnectionStringBuilder c = new SqliteConnectionStringBuilder {
                    DataSource = databaseName
                };
                ConnectionString = c.ConnectionString;
            }
            else
            {
                SQLiteConnectionStringBuilder c = new SQLiteConnectionStringBuilder {
                    DataSource = databaseName
                };
                ConnectionString = c.ConnectionString;
            }
            TableName = tableName;
        }
        public SQLiteDbContextOptions(DbOptions dbOptions, DbModuleOptions options, ILoggerFactory loggerFactory, ILoginInfo loginInfo) : base(dbOptions, options, new SQLiteAdapter(dbOptions, options), loggerFactory, loginInfo)
        {
            SqlMapper.AddTypeHandler <Guid>(new GuidTypeHandler());

            options.Version = dbOptions.Version;
            string dbFilePath = Path.Combine(AppContext.BaseDirectory, "Db");

            if (DbOptions.Server.NotNull())
            {
                dbFilePath = Path.GetFullPath(DbOptions.Server);
            }

            dbFilePath = Path.Combine(dbFilePath, options.Database);

            var connStrBuilder = new SqliteConnectionStringBuilder
            {
                DataSource = $"{dbFilePath}.db",
                Mode       = SqliteOpenMode.ReadWriteCreate
            };

            options.ConnectionString = connStrBuilder.ToString();
        }
        public void AddCustomer_ReturnsCustomerByName()
        {
            var connectionStringBuilder =
                new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connection = new SqliteConnection(connectionStringBuilder.ToString());
            var options    = new DbContextOptionsBuilder <CustomerDBContext>()
                             .UseSqlite(connection)
                             .Options;

            using (var context = new CustomerDBContext(options))
            {
                context.Database.OpenConnection();
                context.Database.EnsureCreated();

                context.Customers.AddRange(new[]
                {
                    new Customer()
                    {
                        FirstName = "Syed", LastName = "Majeeduddin", DOB = DateTime.Now.AddYears(-25)
                    }
                });

                context.SaveChanges();

                var customerRepository = new CustomerRepository(context);
                var dto = new CustomerDto()
                {
                    FirstName = "Mathew", LastName = "Hayden", DateOfBirth = Convert.ToDateTime("1982/12/10")
                };

                // Act
                var customer = customerRepository.AddCustomer(dto);

                // Assert
                Assert.Equal("Mathew", (customer.Result).FirstName);
            }
        }
Example #12
0
        static ConnectionFactories()
        {
            Factories.Add(new OrmConnectionFactory(new MySqlDialectProvider(),
                                                   "server=localhost;user=root;password=depfac$2000;database=test"));
            Factories.Add(new OrmConnectionFactory(new MySqlConnectorDialectProvider(),
                                                   "server=localhost;user=root;password=depfac$2000;database=test2"));
            Factories.Add(new OrmConnectionFactory(new SqlServerDialectProvider(),
                                                   @"server=localhost;User id=sa;Password=depfac$2000;database=test"));
            Factories.Add(new OrmConnectionFactory(new PostgreSQLDialectProvider(),
                                                   "server=localhost;user id=postgres;password=depfac$2000;database=test;Enlist=true"));

            var builder = new SqliteConnectionStringBuilder();

            builder            = new SqliteConnectionStringBuilder();
            builder.DataSource = Path.Combine(Path.GetTempPath(), "test2.db");
            builder.Mode       = SqliteOpenMode.ReadWriteCreate;
            builder.Cache      = SqliteCacheMode.Shared;

            Factories.Add(new OrmConnectionFactory(new SqliteDialectProvider(), builder.ToString()));
            Factories.Add(new OrmConnectionFactory(new SDSQLite.SqliteDialectProvider(),
                                                   $"Data Source={Path.Combine(Path.GetTempPath(), "test.db")};foreign keys=true;Version=3;New=True;BinaryGUID=False"));
        }
Example #13
0
        public IActionResult DatosEnvioEnviar(Envio envio)
        {
            string userEmail = User.FindFirst(ClaimTypes.Name).Value;


            var connectionBuilder = new SqliteConnectionStringBuilder();

            connectionBuilder.DataSource = "Proyecto.db";
            using (var con = new SqliteConnection(connectionBuilder.ConnectionString))
            {
                con.Open();
                string query = "INSERT INTO DetallesPedido (direccion, contacto,latitud,longitud,comentario, userEmail) values('" + envio.Direccion + "', '" + envio.DatosContacto + "','" + envio.Latitud + "', '" + envio.Longitud + "','" + envio.Comentario + "','" + userEmail + "')";
                var    cmd   = new SqliteCommand(query, con);
                cmd.ExecuteNonQuery();

                string query2 = "select * from carrito where idUsuario =(select id from usuario where email =\'" + userEmail + "\')";
                var    cmd2   = new SqliteCommand(query2, con);
                var    reader = cmd2.ExecuteReader();

                while (reader.Read())
                {
                    string nombre     = String.Format("{0}", reader["nombre"]);
                    string idProducto = String.Format("{0}", reader["idProducto"]);
                    int    cantidad   = Int32.Parse(String.Format("{0}", reader["cantidad"]));
                    string email      = userEmail;
                    double precio     = Double.Parse(String.Format("{0}", reader["precio"]));
                    double total      = cantidad * precio;

                    string query3 = "insert into CarroPedido (nombre, idProducto,cantidad, userEmail,total) values('" + nombre + "', '" + idProducto + "', + '" + cantidad + "', '" + email + "', '" + total + "')";
                    var    cmd3   = new SqliteCommand(query3, con);
                    cmd3.ExecuteNonQuery();
                }

                con.Close();
            }


            return(RedirectToAction("DatosEnvio"));
        }
Example #14
0
        public void CreateTable(string command, string path)
        {
            var connectionStringBuilder = new SqliteConnectionStringBuilder();

            //Use DB in project directory.  If it does not exist, create it:
            connectionStringBuilder.DataSource = path;

            using (var connection = new SqliteConnection(connectionStringBuilder.ConnectionString))
            {
                connection.Open();

                //Create a table (drop if already exists first):

                var delTableCmd = connection.CreateCommand();
                delTableCmd.CommandText = "DROP TABLE IF EXISTS favorite_beers";
                delTableCmd.ExecuteNonQuery();

                var createTableCmd = connection.CreateCommand();
                createTableCmd.CommandText = "CREATE TABLE favorite_beers(name VARCHAR(50))";
                createTableCmd.ExecuteNonQuery();
            }
        }
Example #15
0
        public TestFixture()
        {
            _server = new TestServer(WebHost.CreateDefaultBuilder()
                                     .UseStartup <Startup>()
                                     .UseEnvironment("Development"));
            _client = _server.CreateClient();

            var connectionStringBuilder =
                new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connectionString = connectionStringBuilder.ToString();
            var connection       = new SqliteConnection(connectionString);

            var optionsBuilder = new DbContextOptionsBuilder <AppDbContext>();

            optionsBuilder.UseSqlite(connection);

            _db = new AppDbContext(optionsBuilder.Options, true);
            _db.Database.OpenConnection();
            _db.Database.EnsureCreated();
        }
Example #16
0
        public async Task ToBeCreated()
        {
            var sb = new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connection = new SqliteConnection(sb.ToString());
            var options    = new DbContextOptionsBuilder <LibraryContext>()
                             .UseSqlite(connection)
                             .Options;

            using (LibraryContext context = new LibraryContext(options))
            {
                await context.Database.OpenConnectionAsync();

                context.Database.EnsureCreated();

                var repository = new BookRepository(context);
                await CreateFakeBookAsync(repository);

                Assert.NotNull(await repository.GetAllAsync());
            }
        }
        /// <inheritdoc />
        public LocalFileSnapshotStoreTests()
        {
            _databaseName = $"{Guid.NewGuid():N}.db";

            var connectionStringBuilder = new SqliteConnectionStringBuilder
            {
                DataSource = _databaseName,
                Mode       = SqliteOpenMode.ReadWriteCreate
            };

            var provider = new ServiceCollection()
                           .AddLogging()
                           .AddDbContext <SqliteSnapshotContext>(
                builder => builder.EnableDetailedErrors()
                .EnableSensitiveDataLogging()
                .UseSqlite(connectionStringBuilder.ToString(),
                           options => options.MigrationsAssembly("Bechtle.A365.ConfigService.Migrations")))
                           .BuildServiceProvider();

            Store = new LocalFileSnapshotStore(provider.GetRequiredService <ILogger <LocalFileSnapshotStore> >(),
                                               provider.GetRequiredService <SqliteSnapshotContext>());
        }
Example #18
0
        public async Task Dapper()
        {
            var builder = new SqliteConnectionStringBuilder();

            builder.DataSource = ":memory:";
            builder.Cache      = SqliteCacheMode.Shared;

            var createTable = $"CREATE TABLE {nameof(Serialization)} ({nameof(Serialization.Number)} INTEGER)";
            var insert      = $"INSERT INTO {nameof(Serialization)} ({nameof(Serialization.Number)}) VALUES (5)";
            var selectAll   = $"SELECT * FROM {nameof(Serialization)}";

            await using var connection = new SqliteConnection(builder.ConnectionString);
            await connection.OpenAsync();

            await connection.ExecuteAsync(createTable);

            await connection.ExecuteAsync(insert);

            var materialized = await connection.QueryFirstAsync <Serialization>(selectAll);

            Assert.Equal(5, materialized.Number);
        }
Example #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Set up Sqlite DB
            var builder = new SqliteConnectionStringBuilder()
            {
                DataSource = "Products.db",
                Mode       = SqliteOpenMode.ReadWriteCreate,
                Cache      = SqliteCacheMode.Default,
            };

            var connection = new SqliteConnection(builder.ConnectionString);

            connection.Open();
            connection.EnableExtensions(true);

            services.AddDbContext <ProductContext>(opt => opt.UseSqlite(connection));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Set up dependency injection for controller's logger
            services.AddScoped <ILogger, Logger <ProductController> >();
        }
Example #20
0
        private static ServiceProvider GetServiceProvider(LogLevel minimumLogLevel)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging(lb => lb
                                         .AddProvider(new MinimalConsoleLoggerProvider())
                                         .SetMinimumLevel(minimumLogLevel)
                                         .AddFilter("Microsoft.EntityFrameworkCore", LogLevel.Warning));

            serviceCollection.AddTransient(sp => new EntityContextFactory(() => sp.GetRequiredService <IEntityContext>()));
            serviceCollection.AddDbContext <SqliteEntityContext>(
                (sp, ob) =>
            {
                var settings = sp.GetRequiredService <IKrogerScrapeSettings>();

                var builder        = new SqliteConnectionStringBuilder();
                builder.DataSource = settings.DatabasePath;

                ob.UseSqlite(builder.ConnectionString);
            },
                contextLifetime: ServiceLifetime.Transient,
                optionsLifetime: ServiceLifetime.Transient);
            serviceCollection.AddTransient <IEntityContext>(sp => sp.GetRequiredService <SqliteEntityContext>());

            serviceCollection.AddTransient <Deserializer>();
            serviceCollection.AddTransient <EntityRepository>();
            serviceCollection.AddTransient <KrogerClient>();
            serviceCollection.AddTransient(sp => new KrogerClientFactory(() => sp.GetRequiredService <KrogerClient>()));

            serviceCollection.AddTransient <ScrapeCommandLogic>();
            serviceCollection.AddTransient <StopOrphansCommandLogic>();
            serviceCollection.AddTransient <JsonCommandLogic>();

            serviceCollection.AddSingleton <KrogerScrapeSettingsFactory>();
            serviceCollection.AddTransient(sp => sp.GetRequiredService <KrogerScrapeSettingsFactory>().Create());
            serviceCollection.AddTransient <IKrogerClientSettings>(sp => sp.GetRequiredService <KrogerScrapeSettingsFactory>().Create());

            return(serviceCollection.BuildServiceProvider());
        }
        private static string BuildDatabase(string dbFilename)
        {
            if (!File.Exists(dbFilename))
            {
                File.WriteAllBytes(dbFilename, new byte[0]);
            }

            var connstr = new SqliteConnectionStringBuilder()
            {
                DataSource = dbFilename
            }.ToString();
            SqliteConnection conn = new SqliteConnection(connstr);

            conn.Open();
            long tableCount = 0;

            using (SqliteCommand cmd = new SqliteCommand("SELECT COUNT(1) FROM sqlite_master WHERE type='table';", conn))
            {
                tableCount = (long)cmd.ExecuteScalar();
            }
            if (tableCount == 0)
            {
                var    assembly = typeof(Startup).Assembly;
                string sql;

                using (var sr = new StreamReader(assembly.GetManifestResourceStream(assembly.GetManifestResourceNames().Single(f => f.EndsWith(".quartz.sql")))))
                {
                    sql = sr.ReadToEnd();
                }
                //"quartz.sql");
                Console.WriteLine(sql);
                using (var cmd = new SqliteCommand(sql, conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
            conn.Close();
            return(connstr);
        }
    /// <summary>
    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    public override bool Exists()
    {
        var connectionOptions = new SqliteConnectionStringBuilder(_connection.ConnectionString);

        if (connectionOptions.DataSource.Equals(":memory:", StringComparison.OrdinalIgnoreCase) ||
            connectionOptions.Mode == SqliteOpenMode.Memory)
        {
            return(true);
        }

        using var readOnlyConnection = _connection.CreateReadOnlyConnection();
        try
        {
            readOnlyConnection.Open(errorsExpected: true);
        }
        catch (SqliteException ex) when(ex.SqliteErrorCode == SQLITE_CANTOPEN)
        {
            return(false);
        }

        return(true);
    }
Example #23
0
        public void DeleteOsallistujaAsync(int varaus_id)
        {
            // SQLite-kannan tiedot
            var connectionStringBuilder = new SqliteConnectionStringBuilder();

            connectionStringBuilder.DataSource = "./varaus.db";

            // Avataan yhteys tietokantaan
            using (var connection = new SqliteConnection(connectionStringBuilder.ConnectionString))
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction())
                {
                    var deleteCommand = connection.CreateCommand();

                    deleteCommand.CommandText = "DELETE FROM koulutus_ilmoittautumiset WHERE varaus_id=" + varaus_id;
                    deleteCommand.ExecuteNonQuery();
                    transaction.Commit();
                }
            }
        }
Example #24
0
        public LingoesDict()
        {
            string FileName = @"dic/njcd.db";

            var connectionString = new SqliteConnectionStringBuilder()
            {
                Cache      = SqliteCacheMode.Shared,
                Mode       = SqliteOpenMode.ReadOnly,
                DataSource = FileName,
            }.ToString();

            using var connection = new SqliteConnection(connectionString);
            connection.Open();

            var word = "私私私私私私私私私私";

            var command = connection.CreateCommand();

            command.CommandText =
                @"
                SELECT content 
                FROM entry 
                WHERE word = $word
            ";
            command.Parameters.AddWithValue("$word", word);

            using var raw = command.ExecuteReader();

            raw.Read(); // 使用while 可以遍历行
            if (raw[0] != null)
            {
                Console.WriteLine(raw[0]);
                ContentToObj(raw[0].ToString() !);
            }
            else
            {
                //没找到
            }
        }
Example #25
0
        public override bool Open(String path)
        {
            var connectionString = new SqliteConnectionStringBuilder
            {
                DataSource = path,
                Version    = 3,
                SyncMode   = SynchronizationModes.Full
            };

            var result = true;

            try {
                shouldCommit = false;
                Connection   = new SqliteConnection(connectionString.ToString());
                Connection.Open();
            } catch (Exception ex) {
                Log.E(Tag, "Error opening the Sqlite connection using connection String: {0}".Fmt(connectionString.ToString()), ex);
                result = false;
            }

            return(result);
        }
        public async Task <string> Download(string userId)
        {
            var dbFile = Path.GetTempFileName();

            SqliteConnectionStringBuilder connectionStringBuilder = new SqliteConnectionStringBuilder();

            connectionStringBuilder.DataSource = dbFile;

            using (SqliteConnection db = new SqliteConnection(connectionStringBuilder.ToString()))
            {
                await db.OpenAsync();

                await InitSchema(db);
                await CopyCollectionsToClientData(userId, db);
                await CopyNotesToClientData(userId, db);
                await CopyCardsToClientData(userId, db);
                await CopyRevLogsToClientData(userId, db);
                await CopyGravesToClientData(userId, db);
            }

            return(dbFile);
        }
        public void ApplySort_3Organizations_ReturnInExpectedOrder()
        {
            //Arrange

            var connectionStringBuilder = new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };

            var connection = new SqliteConnection(connectionStringBuilder.ToString());

            var options = new DbContextOptionsBuilder <OrganizationsContext>()
                          .UseLoggerFactory(new LoggerFactory(
                                                new[] { new LogToActionLoggerProvider((log => { _output.WriteLine(log); })) }))
                          .UseSqlite(connection)
                          .Options;
            var mappingConfig = TestHelpers.SetMapper();

            IMapper mapper = mappingConfig.CreateMapper();


            using (var context = new OrganizationsContext(options))
            {
                context.Database.OpenConnection();
                context.Database.EnsureCreated();
                Helpers.TestHelpers.AddFiveOrganizations(context);

                var organizationResourceParameters = new OrganizationResourceParameters {
                    OrderBy = "Name desc"
                };
                Assert.Equal("Organization1", context.Organizations.First().Name);

                var orderedOrganizations = context.Organizations.ApplySort(organizationResourceParameters.OrderBy,
                                                                           _propertyMappingService.GetPropertyMapping <OrganizationDto, Organization>());

                //Assert
                Assert.Equal("Organization2", orderedOrganizations.First().Name);
                Assert.Equal("Org1", orderedOrganizations.Last().Name);
            }
        }
Example #28
0
        public string DataCheck(string id, DataContext context)
        {
            // Check lims.db for task ID entry
            List <Entities.Task> task = context.Tasks.Where(t => t.id == id).ToList();

            if (task.Count == 0)
            {
                return(String.Format("No task ID found with that id: {0}.", id));
            }

            // Check lims_data.db for input and output data entries.
            var conStrBuilder = new SqliteConnectionStringBuilder();

            conStrBuilder.DataSource = this.backupDB;
            using (var conn = new SqliteConnection(conStrBuilder.ConnectionString))
            {
                conn.Open();
                string inQuery = "SELECT COUNT(*) FROM InputData WHERE id=@id";
                var    inCmd   = conn.CreateCommand();
                inCmd.CommandText = inQuery;
                inCmd.Parameters.Add("@id", SqliteType.Text).Value = id;
                int inCount = Convert.ToInt32(inCmd.ExecuteScalar());

                string outQuery = "SELECT COUNT(*) FROM OutputData WHERE id=@id";
                var    outCmd   = conn.CreateCommand();
                outCmd.CommandText = outQuery;
                outCmd.Parameters.Add("@id", SqliteType.Text).Value = id;
                int outCount = Convert.ToInt32(outCmd.ExecuteScalar());

                inCmd.Dispose();
                outCmd.Dispose();
                conn.Close();
                if (inCount == 0 || outCount == 0)
                {
                    return(String.Format("Data for task ID: {0} is no longer backed up. Backup expired.", id));
                }
            }
            return("");
        }
Example #29
0
        public SyncSchemaFixture()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            var builder = new SqliteConnectionStringBuilder {
                DataSource = ClientSqliteFilePath
            };

            this.ClientSqliteConnectionString = builder.ConnectionString;

            if (File.Exists(ClientSqliteFilePath))
            {
                File.Delete(ClientSqliteFilePath);
            }

            var backup = Path.Combine(Directory.GetCurrentDirectory(), "Backup", "AdventureWorksLT2012.bak");

            // create databases
            helperDb.RestoreDatabase(serverDbName, backup);
            helperDb.CreateDatabase(client1DbName);
        }
        public string BuildConnectionString(INopConnectionStringInfo nopConnectionString)
        {
            if (nopConnectionString is null)
            {
                throw new ArgumentNullException(nameof(nopConnectionString));
            }

            if (nopConnectionString.IntegratedSecurity)
            {
                throw new NopException("Data provider supports connection only with password");
            }

            var builder = new SqliteConnectionStringBuilder
            {
                DataSource = CommonHelper.DefaultFileProvider.MapPath($"~/App_Data/{nopConnectionString.DatabaseName}.sqlite"),
                Password   = nopConnectionString.Password,
                Mode       = SqliteOpenMode.ReadWrite,
                Cache      = SqliteCacheMode.Shared
            };

            return(builder.ConnectionString);
        }
Example #31
0
        public AppDatabase ReadConnection(string connectionString, DatabaseProvider provider)
        {
            if (provider == DatabaseProvider.Other)
            {
                var sb = new SqliteConnectionStringBuilder(connectionString);
                return(new AppDatabase(sb.ConnectionString, provider));
            }

            if (provider == DatabaseProvider.MsSql)
            {
                var sb = new SqlConnectionStringBuilder(connectionString);
                return(new AppDatabase(sb.DataSource, sb.InitialCatalog, sb.UserID, sb.Password, provider, 1433));
            }

            if (provider == DatabaseProvider.MySql)
            {
                var sb = new MySqlConnectionStringBuilder(connectionString);
                return(new AppDatabase(sb.Server, sb.Database, sb.UserID, sb.Password, provider, sb.Port));
            }

            return(null);
        }
Example #32
0
        protected override PSDriveInfo NewDrive(PSDriveInfo drive)
        {            
            if( drive is SQLiteDrive )
            {
                return drive;
            }

			var cs = drive.Root;
            if( String.IsNullOrEmpty( cs ) || ! cs.StartsWith("[") )
            {
                if (String.IsNullOrEmpty(cs))
                {
                    var builder = new SqliteConnectionStringBuilder();
                    builder.DataSource = ":memory:";
                    cs = builder.ToString();
                }
            
                drive = new PSDriveInfo(
                    drive.Name,
                    drive.Provider,
                    "/",
                    drive.Description,
                    drive.Credential);
            }

			return new SQLiteDrive( drive, String.Format( "[{0}]", cs), DynamicParameters as DriveParams );
        }