/// <summary> /// Configures the connection to use the <see cref="ILoggerFactory"/> resolved from the container. /// </summary> /// <param name="builder">Builder to configure.</param> /// <param name="provider">Container used to resolve the factory.</param> /// <returns>The builder instance so calls can be chained.</returns> public static LinqToDbConnectionOptionsBuilder UseDefaultLogging(this LinqToDbConnectionOptionsBuilder builder, IServiceProvider provider) { var factory = provider.GetRequiredService <ILoggerFactory>(); return(UseLoggerFactory(builder, factory)); }
/// <summary> /// Configures the connection to use the <see cref="ILoggerFactory"/> passed in. /// </summary> /// <param name="builder">Builder to configure.</param> /// <param name="factory">Factory used to resolve loggers.</param> /// <returns>The builder instance so calls can be chained.</returns> public static LinqToDbConnectionOptionsBuilder UseLoggerFactory(this LinqToDbConnectionOptionsBuilder builder, ILoggerFactory factory) { var adapter = new LinqToDbLoggerFactoryAdapter(factory); return(builder.WithTraceLevel(TraceLevel.Verbose).WriteTraceWith(adapter.OnTrace)); }
private static DataConnection createConnection() { var builder = new LinqToDbConnectionOptionsBuilder(); builder.UseSQLite(connectionString); return(new DataConnection(builder.Build())); }
/// <summary> /// Registers <typeparamref name="TContext"/> as a service in the <see cref="IServiceCollection" />. /// You use this method when using dependency injection in your application, such as with ASP.NET. /// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890. /// </summary> /// <example> /// <code> /// public void ConfigureServices(IServiceCollection services) /// { /// var connectionString = "connection string to database"; /// /// services.AddLinqToDbContext<IMyContext, MyContext>(options => { /// options.UseSqlServer(connectionString); /// }); /// } /// </code> /// </example> /// <typeparam name="TContext"> /// The class or interface that will be used to resolve the context from the container. /// </typeparam> /// <typeparam name="TContextImplementation"> /// The concrete implementation type used to fulfill requests for <typeparamref name="TContext"/> from the container. /// Must inherit from <see cref="IDataContext"/> and <typeparamref name="TContext"/> /// and expose a constructor that takes <see cref="LinqToDbConnectionOptions{TContext}" /> (where T is <typeparamref name="TContextImplementation"/>) /// and passes it to the base constructor of <see cref="DataConnection" />. /// </typeparam> /// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param> /// <param name="configure"> /// <para> /// An action to configure the <see cref="LinqToDbConnectionOptionsBuilder" /> for the context. /// </para> /// <para> /// In order for the options to be passed into your context, you need to expose a constructor on your context that takes /// <see cref="LinqToDbConnectionOptions{TContext}" /> and passes it to the base constructor of <see cref="DataConnection" />. /// </para> /// </param> /// <param name="lifetime"> /// The lifetime with which to register the Context service in the container. /// For one connection per request use <see cref="ServiceLifetime.Scoped"/> (the default). /// </param> /// <remarks> /// This method should be used when a custom context is required or /// when multiple contexts with different configurations are required. /// </remarks> /// <returns> /// The same service collection so that multiple calls can be chained. /// </returns> public static IServiceCollection AddLinqToDbContext <TContext, TContextImplementation>( this IServiceCollection serviceCollection, Action <IServiceProvider, LinqToDbConnectionOptionsBuilder> configure, ServiceLifetime lifetime = ServiceLifetime.Scoped) where TContextImplementation : TContext, IDataContext { var hasTypedConstructor = HasTypedContextConstructor <TContextImplementation>(); serviceCollection.TryAdd(new ServiceDescriptor(typeof(TContext), typeof(TContextImplementation), lifetime)); serviceCollection.TryAdd(new ServiceDescriptor(typeof(LinqToDbConnectionOptions <TContextImplementation>), provider => { var builder = new LinqToDbConnectionOptionsBuilder(); configure(provider, builder); return(builder.Build <TContextImplementation>()); }, lifetime)); if (!hasTypedConstructor) { serviceCollection.TryAdd(new ServiceDescriptor(typeof(LinqToDbConnectionOptions), provider => provider.GetService(typeof(LinqToDbConnectionOptions <TContextImplementation>)), lifetime)); } return(serviceCollection); }
/// <summary> /// Creates the default <see cref="LinqToDbConnectionOptions" />. <paramref name="traceLevel" /> and <paramref name="logger" /> /// are optional but need to be set together if a level other than <see cref="TraceLevel.Off" /> is used. /// </summary> /// <param name="dataProvider">The Linq2Db data provider used to create database-specific queries.</param> /// <param name="connectionString">The connection string for the target database.</param> /// <param name="traceLevel">The level that is used to log data connection messages (optional). Defaults to <see cref="TraceLevel.Off" />.</param> /// <param name="logger">The logger for <see cref="DataConnection" /> when <paramref name="traceLevel" /> is set to a value other than <see cref="TraceLevel.Off" />.</param> /// <exception cref="NullReferenceException">Thrown when <paramref name="dataProvider" /> or <paramref name="connectionString" /> are null.</exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="traceLevel" /> is set to a value other than <see cref="TraceLevel.Off" /> and <paramref name="logger" /> is null - /// or when <paramref name="connectionString" /> is an empty string or contains only white space. /// </exception> public static LinqToDbConnectionOptions CreateLinq2DbConnectionOptions(IDataProvider dataProvider, string connectionString, TraceLevel traceLevel = TraceLevel.Off, ILogger <DataConnection>?logger = null) { dataProvider.MustNotBeNull(nameof(dataProvider)); connectionString.MustNotBeNullOrWhiteSpace(nameof(connectionString)); var optionsBuilder = new LinqToDbConnectionOptionsBuilder().UseConnectionString(dataProvider, connectionString) .WithTraceLevel(traceLevel); if (traceLevel == TraceLevel.Off) { return(optionsBuilder.Build()); } if (logger == null) { throw new ArgumentException($"You must provide a logger when traceLevel is set to \"{traceLevel}\".", nameof(logger)); } return(optionsBuilder.WithTraceLevel(traceLevel) .WriteTraceWith(logger.LogLinq2DbMessage) .Build()); }
private async Task <string> ProcessAsync(string s3BucketName, string s3ObjectKey) { var apiServerLogKeyword = Environment.GetEnvironmentVariable("apiServerLogKeyword"); var dedicatedServerLogKeyword = Environment.GetEnvironmentVariable("dedicatedServerLogKeyword"); if (!s3ObjectKey.ToLower().Contains(apiServerLogKeyword) && !s3ObjectKey.ToLower().Contains(dedicatedServerLogKeyword)) { return(string.Empty); } var readCount = 0; var processCount = 0; var insertCount = 0; var sw = Stopwatch.StartNew(); LinqToDBForEFTools.Initialize(); var optBuilder = new LinqToDbConnectionOptionsBuilder(); optBuilder.UseMySql(GetConnectionString()); using (var dataConnection = new DataConnection(optBuilder.Build())) { // todo: 1つのeventに2つ以上のファイルが含まれることがないか確認する var request = new GetObjectRequest { BucketName = s3BucketName, Key = s3ObjectKey, }; using (var getResponse = await S3Client.GetObjectAsync(request)) using (var streamReader = new StreamReader(getResponse.ResponseStream)) using (var tran = dataConnection.BeginTransaction()) { try { if (s3ObjectKey.ToLower().Contains(apiServerLogKeyword)) { (readCount, processCount, insertCount) = await new ApiServerLogProcessor(dataConnection).ProcessAsync(streamReader); } else if (s3ObjectKey.ToLower().Contains(dedicatedServerLogKeyword)) { (readCount, processCount, insertCount) = await new DedicatedServerLogProcessor(dataConnection).ProcessAsync(streamReader); } tran.Commit(); } catch { tran.Rollback(); throw; } } return($"{sw.Elapsed.TotalMilliseconds:N0} msec. read: {readCount:N0} lines. process: {processCount:N0} lines. insert: {insertCount:N0} rows."); } }
protected static RepoDbDB GetDb() { var builder = new LinqToDbConnectionOptionsBuilder(); builder.UsePostgreSQL(DatabaseHelper.ConnectionString); return(new RepoDbDB(builder.Build())); }
public void TraceSwitchShouldUseFromBuilder() { var staticTraceLevel = DataConnection.TraceSwitch.Level; var builderTraceLevel = staticTraceLevel + 1; var builder = new LinqToDbConnectionOptionsBuilder().WithTraceLevel(builderTraceLevel); using (var db = new DataConnection(builder.Build())) { Assert.AreEqual(builderTraceLevel, db.TraceSwitchConnection.Level); Assert.AreNotEqual(staticTraceLevel, db.TraceSwitchConnection.Level); } }
public void OnTraceConnectionShouldUseFromBuilder() { bool defaultTraceCalled = false; DataConnection.OnTrace = info => defaultTraceCalled = true; bool builderTraceCalled = false; var builder = new LinqToDbConnectionOptionsBuilder().WithTracing(info => builderTraceCalled = true); using (var db = new DataConnection(builder.Build())) { db.OnTraceConnection(new TraceInfo(db, TraceInfoStep.BeforeExecute)); } Assert.True(builderTraceCalled, "because the builder trace should have been called"); Assert.False(defaultTraceCalled, "because the static trace should not have been called"); }
public void WriteTraceInstanceShouldUseFromBuilder() { var staticWriteCalled = false; DataConnection.WriteTraceLine = (s, s1, arg3) => staticWriteCalled = true; var builderWriteCalled = false; var builder = new LinqToDbConnectionOptionsBuilder() .WriteTraceWith((s, s1, a3) => builderWriteCalled = true); using (var db = new DataConnection(builder.Build())) { db.WriteTraceLineConnection(null, null, TraceLevel.Info); } Assert.True(builderWriteCalled, "because the data connection should have used the action from the builder"); Assert.False(staticWriteCalled, "because the data connection should have used the action from the builder"); }
public void CanUseWithLoggingFromFactory() { var builder = new LinqToDbConnectionOptionsBuilder(); var factory = new TestLoggerFactory(); builder.UseLoggerFactory(factory); Assert.NotNull(builder.WriteTrace); var expectedMessage = "this is a test log"; builder.WriteTrace !(expectedMessage, "some category", TraceLevel.Info); Assert.That(factory.Loggers, Has.One.Items); var testLogger = factory.Loggers.Single(); Assert.Contains(expectedMessage, testLogger.Messages); }
protected static LinqToDbConnectionOptions <NotesConnection> ChangeType <T>(LinqToDbConnectionOptions <T> TDataContext) where T : DataConnection { var builder = new LinqToDbConnectionOptionsBuilder(); builder.UseSqlServer(TDataContext.ConnectionString); #if DEBUG builder.WriteTraceWith((a, b, c) => { Console.WriteLine(a); Console.WriteLine(b); }); #endif return(builder.Build <NotesConnection>()); }
public void CanUseLoggingFactoryFromIoc() { var builder = new LinqToDbConnectionOptionsBuilder(); var factory = new TestLoggerFactory(); var services = new ServiceCollection(); services.AddSingleton <ILoggerFactory>(factory); builder.UseDefaultLogging(services.BuildServiceProvider()); Assert.NotNull(builder.WriteTrace); var expectedMessage = "this is a test log"; builder.WriteTrace !(expectedMessage, "some category", TraceLevel.Info); Assert.That(factory.Loggers, Has.One.Items); var testLogger = factory.Loggers.Single(); Assert.Contains(expectedMessage, testLogger.Messages); }
public static void Main(string[] args) { // create options builder /*builder. Mode = SqliteOpenMode.ReadOnly; * builder.Cache = SqliteCacheMode.Shared; * builder.ForeignKeys = true; * builder.RecursiveTriggers = true;*/ // configure connection string //builder.UseSQLite(@"e:\StorageDB\StorageDB.sqlite"); var b = new System.Data.SQLite.SQLiteConnectionStringBuilder(@"Data Source=e:\\StorageDB\\StorageDB.sqlite"); b.CacheSize = 8192; b.JournalMode = System.Data.SQLite.SQLiteJournalModeEnum.Wal; b.ForeignKeys = true; b.RecursiveTriggers = true; b.Enlist = true; b.PageSize = 4096; b.SyncMode = System.Data.SQLite.SynchronizationModes.Full; b.ReadOnly = true; b.Pooling = true; var o = new LinqToDbConnectionOptionsBuilder(); var p = o.UseSQLite(b.ToString()); //System.Data.SQLite.SQLiteFunction // pass configured options to data connection constructor //List<Item> items = null; /*using (var dc = new SQLiteProvider(p.Build())) * { * * // items = (from i in dc.Items where i.ItemFileName.StartsWith("P") select i).ToList(); * } * * foreach (var i in items) * Console.WriteLine($"{i}");*/ Console.ReadKey(); }
public static LinqToDbConnectionOptionsBuilder UseDB2iSeries_OleDb(this LinqToDbConnectionOptionsBuilder builder, IDbConnection connection, bool disposeConnection) => builder.UseConnection(new DB2iSeriesDataProvider_OleDb(connection.ConnectionString), connection, disposeConnection);
public static LinqToDbConnectionOptionsBuilder UseDB2iSeries_OleDb(this LinqToDbConnectionOptionsBuilder builder, Func <IDbConnection> connectionFactory) => builder.UseConnectionFactory(new DB2iSeriesDataProvider_OleDb(connectionFactory().ConnectionString), connectionFactory);
public static LinqToDbConnectionOptionsBuilder UseDB2iSeries_OleDb(this LinqToDbConnectionOptionsBuilder builder, string connectionString) => builder.UseConnectionString(new DB2iSeriesDataProvider_OleDb(connectionString), connectionString);
public static IServiceCollection AddLinqToDb(this IServiceCollection services, LinqToDbConnectionOptionsBuilder builder) { var co = builder.Build(); services.AddTransient <DataConnection>(sp => new DataConnection(co)); return(services); }