Beispiel #1
0
        /// <summary>
        /// Creates a ProfiledDbConnection instance and opens it
        /// </summary>
        public static DbConnection New(IDbConnectionFactory connectionFactory, IDbProfiler dbProfiler)
        {
            var connection = new ProfiledDbConnection(connectionFactory.CreateConnection(), dbProfiler);

            connection.Open();

            return(connection);
        }
Beispiel #2
0
        /// <summary>
        /// Creates a database connection based on the specified database information object.
        /// </summary>
        internal DBConnection(DatabaseInfo databaseInfo /*, int? timeout */)
        {
            this.databaseInfo = databaseInfo;

            // NOTE SJR: We're going to have to generate code to retrieve this value.
            this.timeout = timeout;
            cn           = new ProfiledDbConnection(databaseInfo.CreateConnection(), MiniProfiler.Current);
        }
Beispiel #3
0
        protected IDbConnection GetConnection()
        {
            SqlConnection sqlConnection     = new SqlConnection(_connectionString);
            var           wrapperConnection =
                new ProfiledDbConnection(sqlConnection, MiniProfiler.Current);

            return(wrapperConnection);
        }
Beispiel #4
0
        public static DbConnection GetConnection()
        {
            var conn = new SqlConnection(@"Server=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SimpleDemoDB.mdf;Database=SimpleDemoDB;Trusted_Connection=Yes;");

            // wrap the connection with ProfiledDbConnection that tracks timings
            var dbProfiler = new ProfiledDbConnection(conn, new DbProfiler(ProfilingSession.Current.Profiler));

            return(dbProfiler);
        }
        /// <summary>
        /// The EF code first.
        /// </summary>
        /// <returns>the entity framework code first view.</returns>
        public ActionResult EFCodeFirst()
        {
            int count;
            int?newCount = null;

            EFContext context = null;

            using (MiniProfiler.Current.Step("EF Stuff"))
            {
                try
                {
                    using (MiniProfiler.Current.Step("Create Context"))
                        context = new EFContext();

                    // this is not correct, as the count from this assignment is never actually used
                    using (MiniProfiler.Current.Step("First count"))
                        count = context.People.Count();

                    using (MiniProfiler.Current.Step("Insertion"))
                    {
                        var p = new Person {
                            Name = "sam"
                        };
                        context.People.Add(p);
                        context.SaveChanges();
                    }

                    // this count is actually used.
                    using (MiniProfiler.Current.Step("Second count"))
                        count = context.People.Count();

                    const string sql = "Select count(*) from People";
                    using (MiniProfiler.Current.Step("Get Count from SqlQuery Method - no sql recorded"))
                    {
                        newCount = context.Database.SqlQuery <int>(sql).Single();
                    }
                    using (MiniProfiler.Current.Step("Get Count using ProfiledConnection - sql recorded"))
                    {
                        using (var conn = new ProfiledDbConnection(context.Database.Connection, MiniProfiler.Current))
                        {
                            conn.Open();
                            newCount = conn.Query <int>(sql).Single();
                            conn.Close();
                        }
                    }
                }
                finally
                {
                    if (context != null)
                    {
                        context.Dispose();
                    }
                }
            }

            return(Content(string.Format("EF Code First complete - count: {0}, sqlQuery count {1}", count, newCount)));
        }
        public IDbConnection GetConnection(string connectionString)
        {
            var conn = new ProfiledDbConnection(
                new SqlConnection(connectionString),
                () => ProfilingSession.Current == null
                    ? null
                    : new DbProfiler(ProfilingSession.Current.Profiler)
                );

            return(conn);
        }
        public static DbConnection GetConnection(MiniProfiler profiler)
        {
            var connection = new SQLiteConnection("Data Source=:memory:");

            // to get profiling times, we have to wrap whatever connection we're using in a ProfiledDbConnection
            // when profiler is null, this connection will not record any database timings
            var profiled = new ProfiledDbConnection(connection, profiler);

            profiled.Open();
            return(profiled);
        }
 public static IServiceCollection AddDapper(this IServiceCollection services, string connectionString)
 {
     services.AddScoped <IDbConnection>((sp) =>
     {
         //采用MiniProfiler 用于性能分析
         var client = new ProfiledDbConnection(new SqlConnection(connectionString), MiniProfiler.Current);
         client.Open();
         return(client);
     });
     return(services);
 }
Beispiel #9
0
        public void TestProfiledStoredProcWithParameters()
        {
            using (var connection = ConnectionWithTransaction())
            {
                connection.ExecuteSql("CREATE PROC InsightTestProcMiniProfiler (@Value int = 5) AS SELECT Value=@Value");

                var profiled = new ProfiledDbConnection((DbConnection)connection, MiniProfiler.Current);
                var result   = profiled.Query <int>("InsightTestProcMiniProfiler", new { Value = 1 }).First();

                Assert.AreEqual((int)1, result);
            }
        }
Beispiel #10
0
        private async Task <DbConnection> OpenConnection(DbProviderFactory factory = null)
        {
            factory = factory ?? m_factory;

            var connection = new ProfiledDbConnection(factory.CreateConnection(), MiniProfiler.Current);

            connection.ConnectionString = m_connectionString;

            await connection.OpenAsync();

            return(connection);
        }
        public override DbConnection CreateConnection()
        {
            var          sqliteConnection = new SqlCeConnection();
            DbConnection connection       = sqliteConnection;

            if (IsProfiled)
            {
                connection = new ProfiledDbConnection(sqliteConnection, MiniProfiler.Current);
            }

            return(connection);
        }
Beispiel #12
0
        /// <summary>
        /// Gets an open READ UNCOMMITTED connection using the specified connection string, optionally timing out on the initial connect.
        /// </summary>
        /// <param name="connectionString">The connection string to use for the connection.</param>
        /// <param name="connectionTimeoutMs">(Optional) Milliseconds to wait to connect.</param>
        /// <returns>A READ UNCOMMITTED connection to the specified connection string.</returns>
        /// <exception cref="Exception">Throws if a connection isn't able to be made.</exception>
        /// <exception cref="TimeoutException">Throws if a connection can't be made in <paramref name="connectionTimeoutMs"/>.</exception>
        public static async Task <DbConnection> GetOpenAsync(string connectionString, int?connectionTimeoutMs = null)
        {
            var conn       = new ProfiledDbConnection(new SqlConnection(connectionString), MiniProfiler.Current);
            var tmpTimeout = connectionTimeoutMs.GetValueOrDefault(0);

            if (connectionTimeoutMs.GetValueOrDefault(0) == 0)
            {
                await conn.OpenAsync().ConfigureAwait(false);

                await conn.SetReadUncommittedAsync().ConfigureAwait(false);
            }
            else
            {
                // In the case of remote monitoring, the timeout will be at the NIC level, not responding to traffic,
                // in that scenario, connection timeouts don't really do much, because they're never reached, the timeout happens
                // before their timer starts.  Because of that, we need to spin up our own overall timeout
                using (MiniProfiler.Current.Step($"Opening Connection, Timeout: {conn.ConnectionTimeout}"))
                    using (var tokenSource = new CancellationTokenSource())
                    {
                        tokenSource.CancelAfter(connectionTimeoutMs.Value);
                        try
                        {
                            await conn.OpenAsync(tokenSource.Token).ConfigureAwait(false); // Throwing Null Refs

                            await conn.SetReadUncommittedAsync().ConfigureAwait(false);
                        }
                        catch (TaskCanceledException e)
                        {
                            conn.Close();
                            var csb          = new SqlConnectionStringBuilder(connectionString);
                            var sqlException = $"Error opening connection to {csb.InitialCatalog} at {csb.DataSource}, timeout out at {connectionTimeoutMs.ToComma()} ms";
                            throw new Exception(sqlException, e);
                        }
                        catch (SqlException e)
                        {
                            conn.Close();
                            var csb          = new SqlConnectionStringBuilder(connectionString);
                            var sqlException = $"Error opening connection to {csb.InitialCatalog} at {csb.DataSource}: {e.Message}";
                            throw new Exception(sqlException, e);
                        }
                        if (conn.State == ConnectionState.Connecting)
                        {
                            tokenSource.Cancel();
                            var b = new SqlConnectionStringBuilder {
                                ConnectionString = connectionString
                            };
                            throw new TimeoutException($"Timeout expired connecting to {b.InitialCatalog} on {b.DataSource} on in the alloted {connectionTimeoutMs.Value.ToComma()} ms");
                        }
                    }
            }
            return(conn);
        }
Beispiel #13
0
        /// <summary>
        /// Creates a database connection based on the specified database information object.
        /// </summary>
        internal DBConnection(DatabaseInfo databaseInfo)
        {
            this.databaseInfo = databaseInfo;

            // Build the connection string.
            string connectionString;

            if (databaseInfo is SqlServerInfo)
            {
                var sqlServerInfo = databaseInfo as SqlServerInfo;
                connectionString = "Data Source=" + (sqlServerInfo.Server ?? "(local)");
                if (sqlServerInfo.LoginName != null)
                {
                    connectionString += "; User ID=" + sqlServerInfo.LoginName;
                    connectionString += "; Password='******'".FormatWith(sqlServerInfo.Password);
                }
                else
                {
                    connectionString += "; Integrated Security=SSPI";
                }
                connectionString += "; Initial Catalog=" + sqlServerInfo.Database;
                if (!sqlServerInfo.SupportsConnectionPooling)
                {
                    connectionString += "; Pooling=false";
                }
            }
            else if (databaseInfo is MySqlInfo)
            {
                var mySqlInfo = databaseInfo as MySqlInfo;
                connectionString = "Host=localhost; User Id=root; Password=password; Initial Catalog=" + mySqlInfo.Database;
                if (!mySqlInfo.SupportsConnectionPooling)
                {
                    connectionString += "; Pooling=false";
                }
            }
            else if (databaseInfo is OracleInfo)
            {
                var oracleInfo = databaseInfo as OracleInfo;
                connectionString = "Data Source=" + oracleInfo.DataSource + "; User Id=" + oracleInfo.UserAndSchema + "; Password="******"sys" ? "; DBA Privilege=SYSDBA" : "");
                if (!oracleInfo.SupportsConnectionPooling)
                {
                    connectionString = StringTools.ConcatenateWithDelimiter("; ", connectionString, "Pooling=false");
                }
            }
            else
            {
                throw new ApplicationException("Invalid database information object type.");
            }

            cn = new ProfiledDbConnection(databaseInfo.CreateConnection(connectionString), MiniProfiler.Current);
        }
Beispiel #14
0
 /// <summary>
 /// To Open a new connection.
 /// </summary>
 /// <param name="objSqlConn">Sql connection object</param>
 /// <returns>if the connection establish successfully then return true else false</returns>
 public void OpenConnection(ref DbConnection objSqlConn)
 {
     try
     {
         objSqlConn = new ProfiledDbConnection(new SqlConnection(connString), MiniProfiler.Current);
         if (objSqlConn.State == ConnectionState.Closed)
         {
             objSqlConn.Open();
         }
     }
     catch
     {  }
 }
Beispiel #15
0
        /// <summary>
        /// Gets an open READ UNCOMMITTED connection using the specified connection string, optionally timing out on the initial connect.
        /// </summary>
        /// <param name="connectionString">The connection string to use for the connection.</param>
        /// <param name="connectionTimeoutMs">(Optional) Milliseconds to wait to connect.</param>
        /// <returns>A READ UNCOMMITTED connection to the specified connection string.</returns>
        /// <exception cref="Exception">Throws if a connection isn't able to be made.</exception>
        /// <exception cref="TimeoutException">Throws if a connection can't be made in <paramref name="connectionTimeoutMs"/>.</exception>
        public static DbConnection GetOpen(string connectionString, int?connectionTimeoutMs = null)
        {
            var conn = new ProfiledDbConnection(new SqlConnection(connectionString), MiniProfiler.Current);

            void setReadUncommitted(DbConnection c)
            {
                using (var cmd = c.CreateCommand())
                {
                    cmd.CommandText = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
                    cmd.ExecuteNonQueryAsync();
                }
            }

            if (connectionTimeoutMs.GetValueOrDefault(0) == 0)
            {
                conn.OpenAsync();
                setReadUncommitted(conn);
            }
            else
            {
                // In the case of remote monitoring, the timeout will be at the NIC level, not responding to traffic,
                // in that scenario, connection timeouts don't really do much, because they're never reached, the timeout happens
                // before their timer starts.  Because of that, we need to spin up our own overall timeout
                using (MiniProfiler.Current.Step($"Opening Connection, Timeout: {conn.ConnectionTimeout}"))
                {
                    try
                    {
                        conn.Open();
                    }
                    catch (SqlException e)
                    {
                        var csb          = new SqlConnectionStringBuilder(connectionString);
                        var sqlException = $"Error opening connection to {csb.InitialCatalog} at {csb.DataSource} timeout was: {connectionTimeoutMs.ToComma()} ms";
                        throw new Exception(sqlException, e)
                              .AddLoggedData("Timeout", conn.ConnectionTimeout.ToString());
                    }
                }

                setReadUncommitted(conn);
                if (conn.State == ConnectionState.Connecting)
                {
                    var b = new SqlConnectionStringBuilder {
                        ConnectionString = connectionString
                    };

                    throw new TimeoutException($"Timeout expired connecting to {b.InitialCatalog} on {b.DataSource} on in the alloted {connectionTimeoutMs.ToComma()} ms");
                }
            }
            return(conn);
        }
        public async Task <IList <string> > Test(int delay, CancellationToken cancellationToken)
        {
            var result = new List <string>();

            using (this.profiler.Profile(new ProfileOperationSpecification("test")))
            {
                using (var connection = new ProfiledDbConnection(new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString)))
                {
                    {
                        var id = (await connection.QueryAsync <int>(
                                      "select top 1 Id from TestRocksProfilingTable where 1 = 1 order by Id desc; " +
                                      $"waitfor delay '{TimeSpan.FromMilliseconds(delay)}';")).FirstOrNull();

                        result.Add($"Selected via ADO+Dapper: {id}");
                    }

                    using (var command = connection.CreateCommand())
                    {
                        if (connection.State != ConnectionState.Open)
                        {
                            await connection.OpenAsync(cancellationToken);
                        }

                        command.CommandText = "select top 1 Id from TestRocksProfilingTable where 2 = 2 order by Id desc; " +
                                              $"waitfor delay '{TimeSpan.FromMilliseconds(delay)}';";

                        var id = await command.ExecuteScalarAsync(cancellationToken) as int?;

                        result.Add($"Selected via ADO: {id}");
                    }

                    using (var command = connection.CreateCommand())
                    {
                        if (connection.State != ConnectionState.Open)
                        {
                            await connection.OpenAsync(cancellationToken);
                        }

                        command.CommandText = "select top 1 Id from TestRocksProfilingTable where 3 = 3 order by Id desc; " +
                                              $"waitfor delay '{TimeSpan.FromMilliseconds(delay)}';";

                        var id = await command.ExecuteScalarAsync(cancellationToken) as int?;

                        result.Add($"Selected via ADO (2): {id}");
                    }
                }

                return(result);
            }
        }
Beispiel #17
0
        /// <summary>
        /// Returns an open connection that will have its queries profiled.
        /// </summary>
        public static DbConnection GetSqliteConnection()
        {
            DbConnection cnn = new System.Data.SQLite.SQLiteConnection("Data Source=:memory:");

            // to get profiling times, we have to wrap whatever connection we're using in a ProfiledDbConnection
            // when MiniProfiler.Current is null, this connection will not record any database timings
            if (MiniProfiler.Current != null)
            {
                cnn = new ProfiledDbConnection(cnn, MiniProfiler.Current);
            }

            cnn.Open();
            return(cnn);
        }
        public UnitOfWork(IConfiguration configuration)
        {
            var connStr = configuration.GetConnectionString("MySqlConnection");

            //if (!string.IsNullOrEmpty("MySQL Data Provider"))
            //    _providerName = "MySQL Data Provider";
            //else
            //    throw new Exception("ConnectionStrings中没有配置提供程序ProviderName!");
            //_dbFactory = DbProviderFactories.GetFactory(_providerName);
            //_connection = _dbFactory.CreateConnection();
            //_connection.ConnectionString = connStr;
            _connection = new ProfiledDbConnection(new MySqlConnection(connStr), MiniProfiler.Current);

            _connection.Open();
            SetParamPrefix();
        }
Beispiel #19
0
        public void GetDbConnectionType_ByDelegate()
        {
            FeatureSupportWrapper.GetDbConnectionType = (conn) =>
            {
                if (conn is ProfiledDbConnection)
                {
                    return(((ProfiledDbConnection)conn).WrappedConnection.GetType());
                }
                return(conn?.GetType());
            };

            using (var conn = new ProfiledDbConnection(new NpgsqlConnection(), MiniProfiler.Current))
            {
                Assert.Equal("npgsqlconnection", FeatureSupportWrapper.GetDbConnectionType(conn).Name.ToLower());
            }
        }
Beispiel #20
0
        private void DestroyDbConnection(IDbConnection connection)
        {
            ProfiledDbConnection profiled = connection as ProfiledDbConnection;

            if (profiled != null) // for some reason, MiniProfiler profiled Db Connections are disposed at some point.
            {
                if (profiled.WrappedConnection != null)
                {
                    profiled.WrappedConnection.Close();
                }
            }
            else
            {
                connection.Close();
            }
        }
Beispiel #21
0
        public DbConnection GetConnection(MiniProfiler profiler = null)
        {
            using (profiler.Step(nameof(GetConnection)))
            {
                DbConnection cnn = new System.Data.SqlClient.SqlConnection("Server=(localdb)\\mssqllocaldb;Database=IMDBChallenge;Trusted_Connection=True;MultipleActiveResultSets=true");

                // to get profiling times, we have to wrap whatever connection we're using in a ProfiledDbConnection
                // when MiniProfiler.Current is null, this connection will not record any database timings
                if (MiniProfiler.Current != null)
                {
                    cnn = new ProfiledDbConnection(cnn, MiniProfiler.Current);
                }

                cnn.Open();
                return(cnn);
            }
        }
    public async Task <LabExecution> GetLabExecutionForUserAsync(int userId, int labId, CancellationToken cancellationToken)
    {
        // We have to match against user IDs, which does not seem to be supported by EF
        var dbConn             = new ProfiledDbConnection(_dbContext.Database.GetDbConnection(), MiniProfiler.Current);
        var labExecutionEntity = (await dbConn.QueryAsync <LabExecutionEntity>(@"
                 SELECT le.*
                 FROM `LabExecutions` le
                 INNER JOIN `Groups` g ON g.`Id` = le.`GroupId`
                 WHERE le.`LabId` = @labId
                 AND g.`Id` = (
                     SELECT u.`GroupId`
                     FROM `Users` u
                     WHERE u.`Id` = @userId
                 )", new { labId, userId })).FirstOrDefault();

        return(_mapper.Map <LabExecutionEntity, LabExecution>(labExecutionEntity));
    }
Beispiel #23
0
        /// <summary>
        /// Returns an open connection that will have its queries profiled.
        /// </summary>
        /// <param name="profiler">The mini profiler.</param>
        /// <returns>the data connection abstraction.</returns>
        public DbConnection GetConnection(MiniProfiler profiler = null)
        {
            using (profiler.Step("GetOpenConnection"))
            {
                DbConnection cnn = new SqliteConnection(Startup.SqliteConnectionString);

                // to get profiling times, we have to wrap whatever connection we're using in a ProfiledDbConnection
                // when MiniProfiler.Current is null, this connection will not record any database timings
                if (MiniProfiler.Current != null)
                {
                    cnn = new ProfiledDbConnection(cnn, MiniProfiler.Current);
                }

                cnn.Open();
                return(cnn);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Gets an open READ UNCOMMITTED connection using the specified connection string, optionally timing out on the initial connect
        /// </summary>
        /// <param name="connectionString">The connection string to use for the connection</param>
        /// <param name="connectionTimeout">Milliseconds to wait to connect, optional</param>
        /// <returns>A READ UNCOMMITTED connection to the specified connection string</returns>
        public static async Task <DbConnection> GetOpenAsync(string connectionString, int?connectionTimeout = null)
        {
            var conn = new ProfiledDbConnection(new SqlConnection(connectionString), MiniProfiler.Current);

            if (connectionTimeout.GetValueOrDefault(0) == 0)
            {
                await conn.OpenAsync();
                await SetReadUncommitted(conn);
            }
            else
            {
                // In the case of remote monitoring, the timeout will be at the NIC level, not responding to traffic,
                // in that scenario, connection timeouts don't really do much, because they're never reached, the timeout happens
                // before their timer starts.  Because of that, we need to spin up our own overall timeout
                using (MiniProfiler.Current.Step("Opening Connection, Timeout: " + conn.ConnectionTimeout))
                    using (var tokenSource = new CancellationTokenSource())
                    {
                        tokenSource.CancelAfter(connectionTimeout.Value);
                        try
                        {
                            await conn.OpenAsync(tokenSource.Token); // Throwing Null Refs
                        }
                        catch (SqlException e)
                        {
                            var csb          = new SqlConnectionStringBuilder(connectionString);
                            var sqlException = string.Format("Error opening connection to {0} at {1} timeout was: {2} ms", csb.InitialCatalog, csb.DataSource, connectionTimeout.ToComma());
                            throw new Exception(sqlException, e);
                        }
                        await SetReadUncommitted(conn);

                        if (conn.State == ConnectionState.Connecting)
                        {
                            tokenSource.Cancel();
                            var b = new SqlConnectionStringBuilder {
                                ConnectionString = connectionString
                            };

                            throw new TimeoutException("Timeout expired connecting to " + b.InitialCatalog + " on " +
                                                       b.DataSource + " on in the alloted " +
                                                       connectionTimeout.Value.ToComma() + " ms");
                        }
                    }
            }
            return(conn);
        }
Beispiel #25
0
        /// <summary>
        /// Asynchronously returns an open connection that will have its queries profiled.
        /// </summary>
        /// <param name="profiler">The mini profiler.</param>
        /// <returns>the data connection abstraction.</returns>
        public async Task <DbConnection> GetConnectionAsync(MiniProfiler profiler = null)
        {
            using (profiler.Step("GetOpenConnectionAsync"))
            {
                DbConnection cnn = new SqliteConnection(Startup.SqliteConnectionString);

                // to get profiling times, we have to wrap whatever connection we're using in a ProfiledDbConnection
                // when MiniProfiler.Current is null, this connection will not record any database timings
                if (MiniProfiler.Current != null)
                {
                    cnn = new ProfiledDbConnection(cnn, MiniProfiler.Current);
                }

                await cnn.OpenAsync().ConfigureAwait(false);

                return(cnn);
            }
        }
        public static async Task <DbDataReader> ExecuteReaderAsync(
            this MySqlConnection conn,
            string spName,
            IEnumerable <MySqlParameter> parameters,
            MySqlTransaction transaction)
        {
            using (var cmd = new ProfiledDbConnection(conn).CreateCommand())
            {
                cmd.CommandText = spName;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Transaction = transaction;

                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }

                return(await cmd.ExecuteReaderAsync());
            }
        }
Beispiel #27
0
        /// <summary>
        /// The EF core.
        /// </summary>
        /// <returns>The entity framework core.</returns>
        public ActionResult EFCore()
        {
            int count;
            int?newCount = null;

            EFContext context = null;

            //using (var connection = new ProfiledDbConnection(new SqliteConnection("DataSource=:memory:"), MiniProfiler.Current))

            // dotnet\sdk\NuGetFallbackFolder\microsoft.data.sqlite.core\2.0.0\lib\netstandard2.0\Microsoft.Data.Sqlite.dll
            using (var connection = new SqliteConnection("DataSource=:memory:"))
                using (MiniProfiler.Current.Step("EF Core Stuff"))
                {
                    try
                    {
                        connection.Open();

                        var options = new DbContextOptionsBuilder <EFContext>()
                                      .UseSqlite(connection)
                                      .Options;

                        using (MiniProfiler.Current.Step("Create Context"))
                        {
                            context = new EFContext(options);
                        }

                        using (MiniProfiler.Current.Step("Create Schema"))
                        {
                            context.Database.EnsureCreated();
                        }

                        // this is not correct, as the count from this assignment is never actually used
                        using (MiniProfiler.Current.Step("First count"))
                        {
                            count = context.People.Count();
                        }

                        using (MiniProfiler.Current.Step("Insertion"))
                        {
                            var p = new Person {
                                Name = "sam"
                            };
                            context.People.Add(p);
                            context.SaveChanges();
                        }

                        // this count is actually used.
                        using (MiniProfiler.Current.Step("Second count"))
                        {
                            count = context.People.Count();
                        }

                        using (MiniProfiler.Current.Step("Get Count from SqlQuery Method - no sql recorded"))
                        {
                            newCount = context.People.FromSql("Select * from People").Count();
                        }
                        using (MiniProfiler.Current.Step("Get Count using ProfiledConnection - sql recorded"))
                        {
                            using (var conn = new ProfiledDbConnection(context.Database.GetDbConnection(), MiniProfiler.Current))
                            {
                                conn.Open();
                                newCount = conn.Query <int>("Select Count(*) from People").Single();
                                conn.Close();
                            }
                        }
                    }
                    finally
                    {
                        context?.Dispose();
                    }
                }

            return(Content(string.Format("EF Code First complete - count: {0}, sqlQuery count {1}", count, newCount)));
        }
Beispiel #28
0
        public static IContainer RegisterDependencies(IServiceCollection services, IHostingEnvironment env, IConfiguration rootConfiguration)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            var builder = new ContainerBuilder();

            builder.Populate(services);
            RegisterCredentials(builder);

            if (env.IsDevelopment())
            {
                OverrideWithLocalCredentials(builder);
            }

            builder.Register <IDiscoveryCache>(b =>
            {
                var configuration = b.Resolve <IConfiguration>();
                var cache         = new DiscoveryCache(configuration["Auth:Client:Url"]);
                return(cache);
            }).SingleInstance();

            builder.Register(b =>
            {
                return(rootConfiguration);
            }).SingleInstance();

            builder.Register(b =>
            {
                var redis = b.Resolve <ConnectionMultiplexer>();
                return(redis.GetDatabase());
            }).InstancePerLifetimeScope();

            builder.Register(b =>
            {
                var configuration = b.Resolve <IConfiguration>();
                var redis         = b.Resolve <ConnectionMultiplexer>();
                return(redis.GetServer(configuration["Redis:Url"]));
            }).InstancePerLifetimeScope();

            builder.RegisterType <IEventDispatcher>().AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(assemblies).AsClosedTypesOf(typeof(IEventHandler <>)).InstancePerDependency();

            builder.RegisterType <CommandDispatcher>().As <ICommandDispatcher>().InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(assemblies).AsClosedTypesOf(typeof(ICommandHandler <>)).InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(assemblies).AsClosedTypesOf(typeof(ICommandHandler <,>)).InstancePerLifetimeScope();

            builder.RegisterType <QueryDispatcher>().As <IQueryDispatcher>().InstancePerRequest().InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(assemblies).AsClosedTypesOf(typeof(IQueryHandler <,>)).InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(assemblies).AsClosedTypesOf(typeof(AppAbstractValidation <>)).InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(assemblies).AsClosedTypesOf(typeof(IReadCacheHandler <,>)).InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(assemblies).AsClosedTypesOf(typeof(IWriteCacheHandler <,>)).InstancePerLifetimeScope();

            builder.Register <ILogger>(b =>
            {
                var format = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {NewLine}{Message:lj}{NewLine}{Exception}";

                return(new LoggerConfiguration()
                       .MinimumLevel.Debug()
                       .WriteTo.Console(outputTemplate: format)
                       .WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Error, outputTemplate: format)
                       .WriteTo.Logger(cl => cl.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Information).WriteTo.File("Logs/queries.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Information, outputTemplate: format))
                       .CreateLogger());
            });

            builder.Register <IClock>(b =>
            {
                return(SystemClock.Instance);
            }).SingleInstance();

            builder.Register <IMemoryCache>(b =>
            {
                return(new MemoryCache(new MemoryCacheOptions()));
            }).SingleInstance();

            builder.RegisterType <ProfileDbConnection>().AsImplementedInterfaces().SingleInstance();
            builder.Register <IDatabaseConnector <JobDatabaseCredentials> >(b =>
            {
                var databaseCredentials = b.Resolve <JobDatabaseCredentials>();
                var profiler            = b.Resolve <IDbProfiler>();
                ProfiledDbConnection databaseConnection = new ProfiledDbConnection(new SqlConnection(databaseCredentials.ConnectionString), profiler);
                return(new DapperConnector <JobDatabaseCredentials>(databaseConnection));
            }).InstancePerLifetimeScope();

            builder.RegisterType <GuidService>().AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterType <CurrentUserProvider>().AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterType <RandomService>().AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <EventHubService>().AsImplementedInterfaces().SingleInstance();

            builder.Register <IClock>(b =>
            {
                return(SystemClock.Instance);
            }).SingleInstance();

            builder.Register(b =>
            {
                var connectionStringBuilder = b.Resolve <EventHubsConnectionStringBuilder>();
                return(EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString()));
            }).InstancePerLifetimeScope();

            return(builder.Build());
        }
        /// <summary>
        /// Unwraps the given connection and returns the inner connection.
        /// </summary>
        /// <param name="connection">The outer connection.</param>
        /// <returns>The inner connection.</returns>
        public override IDbConnection GetInnerConnection(IDbConnection connection)
        {
            ProfiledDbConnection profiledConnection = (ProfiledDbConnection)connection;

            return(profiledConnection.InnerConnection);
        }
 public ProfiledTransactionWrapper(DbTransaction transaction, ProfiledDbConnection connection)
     : base(transaction, connection)
 {
     Transaction = transaction;
 }