/// <summary>
        /// Creates a new <see cref="SqliteConnection"/> to execute SQLite commands.
        /// </summary>
        /// <remarks>
        /// <para>If the connection string starts with <c>file:</c>, then it is considered to be a URI filename and
        /// should be structured as such.  This allows the setting of any options (such as mode, cache, etc.)
        /// if needed.</para>
        /// <para>If the connection string does not start with file:, then it should be an absolute path (which starts
        /// with a <c>/</c>).</para>
        /// </remarks>
        /// <param name="connectionString">The connection string to use.</param>
        public SqliteConnection(string connectionString)
        {
            if (!sqliteIsInitialized)
            {
                Batteries_V2.Init();

                // You only need to configure the sqlite3 interface once.
                if (raw.sqlite3_config(raw.SQLITE_CONFIG_URI, 1) != raw.SQLITE_OK)
                {
                    throw new SQLiteException("Unable to configure sqlite3 for URI connection strings.");
                }

                sqliteIsInitialized = true;
            }

            int rc = raw.sqlite3_open(connectionString, out connection);

            if (rc != raw.SQLITE_OK)
            {
                throw new SQLiteException("Unable to open database connection to '{connectionString}'", rc, connection);
            }

            int limit = raw.sqlite3_limit(connection, raw.SQLITE_LIMIT_VARIABLE_NUMBER, -1);

            MaxParametersPerQuery = limit - 16;
        }
        public void Open(byte[] db)
        {
            Batteries_V2.Init();

            // Save the bytes to disk, since SQLite cannot open memory blobs, it has to be a file.
            try
            {
                _filename = Path.GetTempFileName();
                File.WriteAllBytes(_filename, db);
            }
            // We're not handling the system errors here. It's way too many of them. Catching all the exceptions
            // doesn't make sense. When any of those exceptions is thrown it means something is wrong with the
            // system, it's not our error. In general catching Exception is not a good practice, but in this case
            // it's just too much trouble.
            catch (Exception e)
            {
                throw new SqliteProviderError($"Failed to save the database to a file '{_filename}'", e);
            }

            // Open the db
            var openResultCode = raw.sqlite3_open_v2(_filename, out _handle, raw.SQLITE_OPEN_READONLY, null);

            if (openResultCode != raw.SQLITE_OK)
            {
                var message = raw.sqlite3_errstr(openResultCode).utf8_to_string();
                throw new SqliteProviderError($"Failed to open the database: '{message}'");
            }
        }
示例#3
0
        public static string GetDbPath()
        {
            var databasePath = "";

            switch (ExecutingPlatform.Current)
            {
            case AppPlatform.iOS:
                Batteries_V2.Init();
                databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library",
                                            DATABASE_NAME);
                break;

            case AppPlatform.Android:
                databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), DATABASE_NAME);
                break;

            case AppPlatform.UWP:
                databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), DATABASE_NAME);
                break;

            default:
                throw new NotSupportedException("Platform not supported");
            }

            Logger.Debug(CultureInfo.CurrentCulture, "Database Path: {dbPath}", databasePath);

            return(databasePath);
        }
示例#4
0
        public QRCodeItemStore(IFileHelper fileHelper, ShareQRDbContext db)
        {
            Batteries_V2.Init();

            _fileHelper = fileHelper ?? throw new ArgumentNullException(nameof(fileHelper));
            _db         = db ?? throw new ArgumentNullException(nameof(db));
        }
示例#5
0
        static OsuDbContext()
        {
            // required to initialise native SQLite libraries on some platforms.
            Batteries_V2.Init();

            // https://github.com/aspnet/EntityFrameworkCore/issues/9994#issuecomment-508588678
            raw.sqlite3_config(2 /*SQLITE_CONFIG_MULTITHREAD*/);
        }
示例#6
0
文件: Main.cs 项目: leoiii12/ShareQR
        // This is the main entry point of the application.
        static void Main(string[] args)
        {
            Batteries_V2.Init();


            // if you want to use a different Application Delegate class from "AppDelegate"
            // you can specify it here.
            UIApplication.Main(args, null, "AppDelegate");
        }
 void Initialise()
 {
     if (!initialized)
     {
         Batteries_V2.Init();
         raw.sqlite3_win32_set_directory(/*temp directory type*/ 2, ApplicationData.Current.TemporaryFolder.Path);
         initialized = true;
     }
 }
示例#8
0
        // This is the main entry point of the application.
        private static void Main(string[] args)
        {
            Registrar.ExtraAssemblies = new[] { typeof(StyleProperties).Assembly };

            Batteries_V2.Init();

            // if you want to use a different Application Delegate class from "AppDelegate"
            // you can specify it here.
            UIApplication.Main(args, null, "AppDelegate");
        }
示例#9
0
        public App()
        {
            InitializeComponent();

            Batteries_V2.Init();

#if DEBUG
            Console.SetOut(new DebugStreamWriter());
#endif
        }
 static StorageAdapter()
 {
     try
     {
         Batteries_V2.Init();
     }
     catch (Exception e)
     {
         AppCenterLog.Error(AppCenterLog.LogTag, "Failed to initialize sqlite3 provider.", e);
     }
 }
        public SqliteBase()
        {
            //开启sqlite多线程模式

            //Batteries_V2.Init();

            //raw.sqlite3_shutdown();
            //SQLitePCL.raw.SetProvider(new SQLite3Provider_e_sqlite3());

            Batteries_V2.Init();

            var sp = new SQLite3Provider_e_sqlite3();

            SQLitePCL.raw.SetProvider(sp);

            var ret = SQLitePCL.raw.sqlite3_config(SQLitePCL.raw.SQLITE_CONFIG_MULTITHREAD);

            //SQLitePCL.raw.SetProvider(new SQLite3Provider_e_sqlite3());
            //Batteries_V2.Init();
            if (ret == raw.SQLITE_OK)
            {
                //success
                Console.WriteLine("Setup Mutex Success.");
            }
            else
            {
                //fault
                Console.WriteLine("Setup Mutex Faild.");
            }



            var threads = SQLitePCL.raw.sqlite3_threadsafe();


            if (threads == 2)
            {
                Console.WriteLine("Curent Thread: MultiThread");
            }
            else if (threads == 1)
            {
                Console.WriteLine("Curent Thread: Serialized");
            }
            else
            {
                Console.WriteLine("Curent Thread: Mutexing code omitted");
            }


            //Batteries_V2.Init();

            // base(connstr);
        }
        internal static sqlite3 GetSqliteConnection(string filename)
        {
            if (!sqliteIsInitialized)
            {
                Batteries_V2.Init();
                sqliteIsInitialized = true;
            }

            int rc = raw.sqlite3_open(filename, out sqlite3 connection);

            VerifySQLiteResponse(rc, raw.SQLITE_OK, connection);
            return(connection);
        }
示例#13
0
        public Startup(IHostingEnvironment env)
        {
            this.env = env;
            Batteries_V2.Init();

            IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(this.env.ContentRootPath)
                                            .AddJsonFile("appsettings.json").AddEnvironmentVariables();

            this.config = builder.Build();

            //Migrations
            DatabaseMigrationRunner.Start(this.config["ConnectionStrings:seed_dotnetContextConnection"]);
        }
示例#14
0
        public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
        {
            Forms.SetFlags("CollectionView_Experimental");
            Forms.Init();

            Batteries_V2.Init();
            CachedImageRenderer.Init();
            AnimationViewRenderer.Init();
            CarouselView.FormsPlugin.iOS.CarouselViewRenderer.Init();

            RegisterDependencies();
            LoadApplication(new App());
            return(base.FinishedLaunching(uiApplication, launchOptions));
        }
示例#15
0
        public static void Main(string[] args)
        {
            AppCommon.SetUpMain(new IOSPlatformHelper());
            var logger = AppCommon.ServiceProvider.GetRequiredService <ILogger>();

            logger.LogTrace("Application.Main() called (just after logger created)");

            Batteries_V2.Init(); // required on iOS when using EF Core v2

            logger.LogTrace("Calling UIApplication.Main()");
            UIApplication.Main(args, null, "AppDelegate");
            logger.LogTrace("After calling UIApplication.Main()");

            logger.LogTrace("Application.Main() returning");
        }
示例#16
0
        static void Main(string[] args)
        {
            Batteries_V2.Init();

            PerfTest("SQLitePCL.raw", testRAW);
            PerfTest("SQLitePCL.raw (no statement caching)", testRAW_unprepared);
            PerfTest("SQLitePCL.raw (no connection caching)", testRAW_unprepared2);

            PerfTest("System.Data.SQLite.SqliteConnection", n => testADO(new SQLiteConnection("Data Source=:memory:"), n));
            PerfTest("System.Data.SQLite.SqliteConnection(Dapper)", n => testDapper(new SQLiteConnection("Data Source=:memory:"), n));

            //PerfTest("Microsoft.Data.Sqlite.SqliteConnection", n => testADO(new Microsoft.Data.Sqlite.SqliteConnection("Data Source=:memory:;Mode=Memory"), n));

            PerfTest("Sql Server LocalDb", n => testADO(new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB"), n));
            PerfTest("Sql Server LocalDb(Dapper)", n => testDapper(new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB"), n));
            PerfTest("Sql Server LocalDb(Microsoft.Data.SqlClient)", n => testADO(new Microsoft.Data.SqlClient.SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB"), n));
            PerfTest("Sql Server LocalDb(Microsoft.Data.SqlClient, Dapper)", n => testDapper(new Microsoft.Data.SqlClient.SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB"), n));
        }
示例#17
0
        public Startup(IHostingEnvironment env)
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();

            try
            {
                this.env = env;
                Batteries_V2.Init();

                IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(this.env.ContentRootPath)
                                                .AddJsonFile("appsettings.json").AddEnvironmentVariables();

                this.config = builder.Build();

                //Migrations
                DatabaseMigrationRunner.Start(this.config["ConnectionStrings:seed_dotnetContextConnection"]);
            }
            catch (Exception e)
            {
                logger.Error(e);
                throw;
            }
        }
示例#18
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string databasePath;

            switch (Device.RuntimePlatform)
            {
            case Device.iOS:
                Batteries_V2.Init();
                databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..",
                                            "Library", DatabaseName);
                break;

            case Device.Android:
                databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                                            DatabaseName);
                break;

            default:
                throw new NotImplementedException("Platform not supported");
            }

            optionsBuilder.UseSqlite($"Filename={databasePath}");
        }
示例#19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Moritz Schmidt, Andreas Weber, REST-Api", Version = "v3"
                });
                c.IncludeXmlComments(this.GetSwaggerPath());
            });

            services.AddDbContext <DataBase>(options =>
            {
                options.UseSqlite(@"DataSource=mydatabase.db;");
            });

            services.AddTransient <StudiCardRepository>();
            services.AddTransient <ErrorHandlingRepository>();

            Batteries_V2.Init();
            Console.WriteLine("Initialized database, in case the host is a linux system.");
        }
示例#20
0
 static ResultSetTests()
 {
     Batteries_V2.Init();
 }
 public void TestMethod1()
 {
     Batteries_V2.Init();
 }
示例#22
0
 static DatabaseBackupTests()
 {
     Batteries_V2.Init();
 }
 static SQLiteValueTests()
 {
     Batteries_V2.Init();
 }
示例#24
0
        static async Task Main(string csvName = "tnt/dump_release_tntvillage_2019-08-30.csv", string tntReadme = "tnt/README.txt", string dbName = "tnt.sqlite")
        {
            Batteries_V2.Init();

            if (!File.Exists(csvName))
            {
                Console.WriteLine("Invalid path for CSV file");
                return;
            }

            if (!File.Exists(tntReadme))
            {
                Console.WriteLine("Invalid path for TNT README");
                return;
            }

            var res = sqlite3_open_v2(dbName, out var db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, null);

            if (res != SQLITE_OK)
            {
                var err = db.errmsg();
                Console.WriteLine($"Error opening DB: ({res}) {err}");
                return;
            }

            CreateTables(db);

            var readme = await File.ReadAllTextAsync(tntReadme);

            var categoryMatches = CategoryRegex.Matches(readme);
            var categories      = categoryMatches
                                  .Select(m => (id: int.Parse(m.Groups[1].ToString()), name: m.Groups[2].ToString()));

            var csvItems = ParseCsv(csvName).ToList();

            using (var stmt = db.prepare("INSERT INTO categories (id, name) VALUES (?, ?)"))
            {
                foreach (var(id, name) in categories)
                {
                    stmt.reset();

                    stmt.bind_int(1, id);
                    stmt.bind_text(2, name);

                    stmt.step_done();
                }
            }

            var stopWatch = new Stopwatch();

            stopWatch.Start();

            var dbItemCount = db.query_scalar <long>("SELECT count(*) FROM items");

            if (dbItemCount != csvItems.Count)
            {
                Console.WriteLine("Seeding DB");
                SeedDb(db, csvItems);
                Console.WriteLine("Seeding completed");
            }
            else
            {
                Console.WriteLine("Seeding not needed");
            }

            stopWatch.Stop();
            Console.WriteLine($"Stopwatch: {stopWatch.ElapsedMilliseconds} ms");
            db.exec("INSERT OR REPLACE INTO metadata (key, value) VALUES ('db_build_time_ms', ?)", stopWatch.ElapsedMilliseconds);
            db.exec("INSERT OR REPLACE INTO metadata (key, value) VALUES ('clean', 1)");
            db.close_v2();
        }
示例#25
0
 static StatementTests()
 {
     Batteries_V2.Init();
 }
示例#26
0
 static Example()
 {
     Batteries_V2.Init();
 }
示例#27
0
 static PrettyTests()
 {
     Batteries_V2.Init();
 }
示例#28
0
        private static async Task StartApp(StartupOptions options)
        {
            ServerApplicationPaths appPaths = CreateApplicationPaths(options);

            // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
            Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);

            IConfiguration appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false);

            CreateLogger(appConfig, appPaths);

            _logger = _loggerFactory.CreateLogger("Main");

            AppDomain.CurrentDomain.UnhandledException += (sender, e)
                                                          => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");

            // Intercept Ctrl+C and Ctrl+Break
            Console.CancelKeyPress += (sender, e) =>
            {
                if (_tokenSource.IsCancellationRequested)
                {
                    return; // Already shutting down
                }

                e.Cancel = true;
                _logger.LogInformation("Ctrl+C, shutting down");
                Environment.ExitCode = 128 + 2;
                Shutdown();
            };

            // Register a SIGTERM handler
            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                if (_tokenSource.IsCancellationRequested)
                {
                    return; // Already shutting down
                }

                _logger.LogInformation("Received a SIGTERM signal, shutting down");
                Environment.ExitCode = 128 + 15;
                Shutdown();
            };

            _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version);

            ApplicationHost.LogEnvironmentInfo(_logger, appPaths);

            // Increase the max http request limit
            // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
            ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);

            // Disable the "Expect: 100-Continue" header by default
            // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
            ServicePointManager.Expect100Continue = false;

// CA5359: Do Not Disable Certificate Validation
#pragma warning disable CA5359

            // Allow all https requests
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });
#pragma warning restore CA5359

            Batteries_V2.Init();
            if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
            {
                _logger.LogWarning("Failed to enable shared cache for SQLite");
            }

            using (var appHost = new CoreAppHost(
                       appPaths,
                       _loggerFactory,
                       options,
                       new ManagedFileSystem(_loggerFactory.CreateLogger <ManagedFileSystem>(), appPaths),
                       new NullImageEncoder(),
                       new NetworkManager(_loggerFactory.CreateLogger <NetworkManager>()),
                       appConfig))
            {
                await appHost.InitAsync(new ServiceCollection()).ConfigureAwait(false);

                appHost.ImageProcessor.ImageEncoder = GetImageEncoder(appPaths, appHost.LocalizationManager);

                await appHost.RunStartupTasksAsync().ConfigureAwait(false);

                try
                {
                    // Block main thread until shutdown
                    await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
                }
                catch (TaskCanceledException)
                {
                    // Don't throw on cancellation
                }
            }

            if (_restartOnShutdown)
            {
                StartNewInstance(options);
            }
        }
 static SQLite3Tests()
 {
     Batteries_V2.Init();
 }
 static SQLiteDatabaseConnectionTests()
 {
     Batteries_V2.Init();
 }